def get_config(): config = ConfigParser() config.read('config.ini') config.adddefaultsection('game') config.setdefault('game', 'outside_coordinates', True) config.setdefault('game', 'show_pieces', True) config.setdefault('game', 'square_coordinates', False) return config
class NewGame(AnchorLayout): app = ObjectProperty(None) config = ObjectProperty(None) settings = ObjectProperty(None) def __init__(self, **kwargs): super(NewGame, self).__init__(**kwargs) self.config = ConfigParser() self.config.read(tttraders_user_conf('tttraders.ini')) self.settings.register_type("int", TTSettingInt) for tab in TradersGame.ConfigTabs: lst = TradersGame.Config[tab] for c in lst: if c.get("key", None): self.config.adddefaultsection(c['section']) self.config.setdefault(c['section'], c['key'], c.get("default", None)) self.settings.add_json_panel(tab, self.config, data=json.dumps(lst))
class MenuScreen(Screen): def __init__(self): Screen.__init__(self) self.name = 'menu' self.config = ConfigParser() self.config.add_section("deck") self.config.add_section("card") self.config.adddefaultsection("menu") self.config.set("deck", "start_studying", 1) self.config.set("deck", "change_deck_mode", "Normal") self.config.set("deck", "show_list", True) self.config.set("deck", "undo", True) self.config.set("deck", "redo", True) self.config.set("card", "add", "") self.config.set("card", "edit", True) self.config.set("card", "remove", True) self.config.add_callback(self.check_deck_locks, "deck", "redo") self.config.add_callback(self.check_deck_locks, "deck", "undo") self.config.add_callback(self.check_card_locks, "card", "edit") self.config.add_callback(self.check_card_locks, "card", "add") self.menu = SettingsWithNoMenu() self.menu.register_type("screen", FlashcardAppManager.SettingNewScreen) self.menu.register_type("action", FlashcardAppManager.SettingDoAction) self.menu.add_json_panel("Flashcards", self.config, os.path.join(os.path.dirname(__file__), 'menu.json')) self.add_widget(self.menu) def check_deck_locks(self, section, key, value): print(self.config.get(section, key)) def check_card_locks(self, section, key, value): print()
from kivy.factory import Factory from kivy.app import App from kivy.properties import StringProperty from kivy.lang import Builder import csv import os import json app = App.get_running_app() from kivy.config import ConfigParser config = ConfigParser() config.read('myconfig.ini') config.adddefaultsection('pycon2018') config.setdefault('pycon2018', 'register_data_dir', 'data') class ScreenRegister(Factory.Screen): _data = {} '''Holds the data in :attr:`data_file_dir` was processed or not. :attr:`_data` is a :type:`String`, defaults to False. ''' data_file_dir = StringProperty(config.get( 'pycon2018', 'register_data_dir')) '''This is the data dir where the registeration data is stored. All csv files should be present in this folder.
class UserPrefs(EventDispatcher): ''' A class to manage user preferences for the RaceCapture app ''' DEFAULT_DASHBOARD_SCREENS = ['5x_gauge_view', 'laptime_view', 'tach_view', 'rawchannel_view'] DEFAULT_PREFS_DICT = {'range_alerts': {}, 'gauge_settings':{}, 'screens':DEFAULT_DASHBOARD_SCREENS, 'alerts': {}} DEFAULT_ANALYSIS_CHANNELS = ['Speed'] prefs_file_name = 'prefs.json' def __init__(self, data_dir, user_files_dir, save_timeout=0.2, **kwargs): self._prefs_dict = UserPrefs.DEFAULT_PREFS_DICT self.config = ConfigParser() self.data_dir = data_dir self.user_files_dir = user_files_dir self.prefs_file = path.join(self.data_dir, self.prefs_file_name) self.register_event_type("on_pref_change") self.load() def on_pref_change(self, section, option, value): pass def set_range_alert(self, key, range_alert): ''' Sets a range alert with the specified key :param key the key for the range alert :type string :param range_alert the range alert :type object ''' self._prefs_dict["range_alerts"][key] = range_alert self.save() def get_range_alert(self, key, default=None): ''' Retrives a range alert for the specified key :param key the key for the range alert :type key string :param default the default value, optional :type default user specified :return the range alert, or the default value ''' return self._prefs_dict["range_alerts"].get(key, default) def get_alertrules(self, channel): ''' Retrieve the alert_rules for the specified channel. If the alertrules do not exist for the specified channel, return an empty default AlertRuleCollection :return AlertRuleCollection ''' alertrules = self._prefs_dict['alerts'].get(channel) if alertrules is None: alertrules = AlertRuleCollection(channel, []) self._prefs_dict['alerts'][channel] = alertrules return alertrules def set_alertrules(self, channel, alertrules): self._prefs_dict['alerts'][channel] = alertrules self.save() def set_gauge_config(self, gauge_id, config_value): ''' Stores a gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type gauge_id string :param config_value the configuration value to set :type config_value string ''' self._prefs_dict["gauge_settings"][gauge_id] = config_value self.save() def get_gauge_config(self, gauge_id): ''' Get the gauge configuration for the specified gauge_id :param gauge_id the key for the gauge :type string :return the gauge configuration ''' return self._prefs_dict["gauge_settings"].get(gauge_id, False) def get_dashboard_screens(self): return copy(self._prefs_dict['screens']) def set_dashboard_screens(self, screens): self._prefs_dict['screens'] = copy(screens) self.save() # Regular preferences below here def get_last_selected_track_id(self): return self.get_pref('track_detection', 'last_selected_track_id') def get_last_selected_track_timestamp(self): return self.get_pref_int('track_detection', 'last_selected_track_timestamp') def get_user_cancelled_location(self): return self.get_pref('track_detection', 'user_cancelled_location') def set_last_selected_track(self, track_id, timestamp, user_cancelled_location='0,0'): self.set_pref('track_detection', 'last_selected_track_id', track_id) self.set_pref('track_detection', 'last_selected_track_timestamp', timestamp) self.set_pref('track_detection', 'user_cancelled_location', user_cancelled_location) self.save() @property def datastore_location(self): return os.path.join(self.data_dir, 'datastore.sq3') def save(self, *largs): ''' Saves the current configuration ''' Logger.info('UserPrefs: Saving preferences') with open(self.prefs_file, 'w+') as prefs_file: data = self.to_json() prefs_file.write(data) def set_config_defaults(self): ''' Set defaults for preferences ''' # Base system preferences self.config.adddefaultsection('help') self.config.adddefaultsection('preferences') self.config.setdefault('preferences', 'distance_units', 'miles') self.config.setdefault('preferences', 'temperature_units', 'Fahrenheit') self.config.setdefault('preferences', 'show_laptimes', 1) self.config.setdefault('preferences', 'startup_screen', 'Home Page') default_user_files_dir = self.user_files_dir self.config.setdefault('preferences', 'config_file_dir', default_user_files_dir) self.config.setdefault('preferences', 'export_file_dir', default_user_files_dir) self.config.setdefault('preferences', 'firmware_dir', default_user_files_dir) self.config.setdefault('preferences', 'import_datalog_dir', default_user_files_dir) self.config.setdefault('preferences', 'send_telemetry', '0') self.config.setdefault('preferences', 'record_session', '1') self.config.setdefault('preferences', 'global_help', True) # Connection type for mobile if is_mobile_platform(): if is_android(): self.config.setdefault('preferences', 'conn_type', 'Bluetooth') elif is_ios(): self.config.setdefault('preferences', 'conn_type', 'WiFi') else: self.config.setdefault('preferences', 'conn_type', 'Serial') # Dashboard preferences self.config.adddefaultsection('dashboard_preferences') self.config.setdefault('dashboard_preferences', 'last_dash_screen', '5x_gauge_view') self.config.setdefault('dashboard_preferences', 'pitstoptimer_enabled', 1) self.config.setdefault('dashboard_preferences', 'pitstoptimer_trigger_speed', 5) self.config.setdefault('dashboard_preferences', 'pitstoptimer_alert_speed', 25) self.config.setdefault('dashboard_preferences', 'pitstoptimer_exit_speed', 55) # Track detection pref self.config.adddefaultsection('track_detection') self.config.setdefault('track_detection', 'last_selected_track_id', 0) self.config.setdefault('track_detection', 'last_selected_track_timestamp', 0) self.config.setdefault('track_detection', 'user_cancelled_location', '0,0') self.config.adddefaultsection('analysis_preferences') self.config.setdefault('analysis_preferences', 'selected_sessions_laps', '{"sessions":{}}') self.config.setdefault('analysis_preferences', 'selected_analysis_channels', ','.join(UserPrefs.DEFAULT_ANALYSIS_CHANNELS)) self.config.adddefaultsection('setup') self.config.setdefault('setup', 'setup_enabled', 1) def load(self): Logger.info('UserPrefs: Data Dir is: {}'.format(self.data_dir)) self.config.read(os.path.join(self.data_dir, 'preferences.ini')) self.set_config_defaults() try: with open(self.prefs_file, 'r') as data: content = data.read() content_dict = json.loads(content) if content_dict.has_key("gauge_settings"): for id, channel in content_dict["gauge_settings"].iteritems(): self._prefs_dict["gauge_settings"][id] = channel if content_dict.has_key('screens'): self._prefs_dict['screens'] = content_dict['screens'] if content_dict.has_key('alerts'): for channel, alertrules in content_dict['alerts'].iteritems(): self._prefs_dict['alerts'][channel] = AlertRuleCollection.from_dict(alertrules) except Exception as e: Logger.error('Error loading preferences, using defaults. {}'.format(e)) def init_pref_section(self, section): ''' Initializes a preferences section with the specified name. if the section already exists, there is no effect. :param section the name of the preference section :type string ''' self.config.adddefaultsection(section) def get_pref_bool(self, section, option, default=None): ''' Retrieve a preferences value as a bool. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default bool :return bool preference value ''' try: return self.config.getboolean(section, option) except (NoOptionError, ValueError): return default def get_pref_float(self, section, option, default=None): ''' Retrieve a preferences value as a float. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default float :return float preference value ''' try: return self.config.getfloat(section, option) except (NoOptionError, ValueError): return default def get_pref_int(self, section, option, default=None): ''' Retrieve a preferences value as an int. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return int preference value ''' try: return self.config.getint(section, option) except (NoOptionError, ValueError): return default def get_pref(self, section, option, default=None): ''' Retrieve a preferences value as a string. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return string preference value ''' try: return self.config.get(section, option) except (NoOptionError, ValueError): return default def get_pref_list(self, section, option, default=[]): """ Retrieve a preferences value as a list. return default value if preference does not exist :param section the configuration section for the preference :type section string :param option the option for the section :type option string :param default :type default user specified :return list of string values """ try: return self.config.get(section, option).split(',') except (NoOptionError, ValueError): return default def set_pref(self, section, option, value): ''' Set a preference value :param section the configuration section for the preference :type string :param option the option for the section :type string :param value the preference value to set :type value user specified ''' current_value = None try: current_value = self.config.get(section, option) except NoOptionError: pass self.config.set(section, option, value) self.config.write() if value != current_value: self.dispatch('on_pref_change', section, option, value) def set_pref_list(self, section, option, value): """ Set a preference value by list :param section the configuration section for the preference :type string :param option the option for the section :type string :param value the preference value to set :type value list (list of strings) """ try: self.set_pref(section, option, ','.join(value)) except TypeError: Logger.error('UserPrefs: failed to set preference list for {}:{} - {}'.format(section, option, value)) def to_json(self): ''' Serialize preferences to json ''' data = {'range_alerts': {}, 'gauge_settings':{}, 'screens': [], 'alerts': {}} for name, range_alert in self._prefs_dict["range_alerts"].iteritems(): data["range_alerts"][name] = range_alert.to_dict() for id, channel in self._prefs_dict["gauge_settings"].iteritems(): data["gauge_settings"][id] = channel for name, alertrules in self._prefs_dict['alerts'].iteritems(): data['alerts'][name] = alertrules.to_dict() data['screens'] = self._prefs_dict['screens'] return json.dumps(data, sort_keys=True, indent=2, separators=(',', ': '))
class mainApp(App): def build(self): Window.clearcolor = (228. / 255., 228. / 255., 228. / 255., 1) self.title = "GrunwaldCalc" Window.minimum_width = 300 Window.minimum_height = 200 self.config = ConfigParser() self.config.read("config.ini") self.config.adddefaultsection("Settings") self.config.setdefault("Settings", "Language", locale.getdefaultlocale()[0]) self.language = self.config.getdefault("Settings", "Language", locale.getdefaultlocale()[0]) self.settings = Settings() self.day_calc = DayCalc.Calculate() self.date_finder = DateFinder.WikiScrape() self.day_calc.changeLanguage(self.language) self.date_finder.changeLanguage(self.language) self.container = BoxLayout(orientation="vertical") self.search_layout = BoxLayout(orientation="horizontal", size_hint=(1, 0.25), height=100) self.results_layout = AnchorLayout(anchor_y="top") self.container.add_widget(self.search_layout) self.container.add_widget(self.results_layout) try: with open("./languages/" + self.language + ".lang", encoding="UTF-8") as language_file: self.language_file = json.load(language_file) except FileNotFoundError: self.language = "en_US" with open("./languages/" + self.language + ".lang", encoding="UTF-8") as language_file: self.language_file = json.load(language_file) self.search_box = TextInput(hint_text=(self.language_file["hint"]), size_hint=(0.7, None), height=50, multiline=False) self.search_button = Button(text=self.language_file["button-text"], size_hint=(0.3, None), height=50) self.search_layout.add_widget(self.search_box) self.search_layout.add_widget(self.search_button) self.search_box.bind(on_text_validate=self.start_main) self.search_button.bind(on_press=self.start_main) return self.container def start_main(self, instance): text_value = ''.join(char for char in self.search_box.text if char.isnumeric()) if 4 < len(text_value) < 9: self.results_layout.clear_widgets() self.date = self.day_calc.findWeekday(text_value) self.result_label = Label( text=self.language_file["single-date"].format(self.date), markup=True) self.results_layout.add_widget(self.result_label) else: self.results_layout.clear_widgets() try: self.event_dates = (self.date_finder.findEventDate( self.search_box.text)) self.event_weekdays = [] for date in self.event_dates: self.event_weekdays.append( self.day_calc.findWeekday(self.event_dates[date])) if len(self.event_dates) == 2: self.result_label = Label( text=self.language_file["from-to-date"].format( self.event_dates['from'], self.event_weekdays[0], self.event_dates['to'], self.event_weekdays[1]), markup=True, size_hint=(1, None)) self.result_label.text_size = (self.results_layout.width - 40, self.results_layout.height) self.results_layout.add_widget(self.result_label) else: self.result_label = Label( text=self.language_file["from-to-date"].format( self.event_dates['date'], self.event_weekdays[0]), markup=True, size_hint=(1, None)) self.result_label.text_size = (self.results_layout.width - 40, self.results_layout.height) self.results_layout.add_widget(self.result_label) except LookupError: self.result_label = Label( text=self.language_file["lookup-error"], markup=True) self.results_layout.add_widget(self.result_label)
import os from kivy.event import EventDispatcher from kivy.config import ConfigParser from kivy.properties import ConfigParserProperty from kivystudio.tools import get_user_data_dir from kivy.core.window import Window Window.maximize() config = ConfigParser('kivystudio') config.adddefaultsection('application') config.adddefaultsection('graphics') config_file = os.path.join(get_user_data_dir('kivystudio'), 'config.ini') config.read(config_file) class SettingDispatcher(EventDispatcher): auto_save = ConfigParserProperty(0, 'application', 'auto_save', 'kivystudio', val_type=int) auto_emulate = ConfigParserProperty(1, 'application', 'auto_emulate', 'kivystudio', val_type=int) dpi_scale = ConfigParserProperty(1,