예제 #1
0
    def load_style_from_config(obj: object, class_name: str, app_name: str = None):
        # If style was not already loaded
        if class_name not in WidgetStyle.STYLE:
            config = None

            if app_name == 'ACLIB_' + class_name:
                log('Load style for app "{}"'.format(app_name))

            # Try to load from app style config
            if app_name:
                app_style_file = path(STYLE_DIR, app_name + '.ini')
                if os.path.isfile(app_style_file):
                    config = Config(app_style_file, check_modules=True)

            # Try to load from widget style config
            if not config:
                class_style_file = path(STYLE_DIR, class_name + '.ini')
                if os.path.isfile(class_style_file):
                    config = Config(class_style_file, check_modules=True)

            # Store the style
            if config:
                if class_name in config.dict:
                    WidgetStyle.STYLE[class_name] = config.dict[class_name]
                else:
                    WidgetStyle.STYLE[class_name] = config.dict['DEFAULT']

                if app_name:
                    for widget, values in config.dict.items():
                        WidgetStyle.STYLE[widget] = values

        if class_name in WidgetStyle.STYLE:
            for prop, val in WidgetStyle.STYLE[class_name].items():
                if hasattr(obj, prop):
                    setattr(obj, prop, val)
예제 #2
0
파일: ac_meta.py 프로젝트: styinx/ACLIB
    def init(self):
        car_model = self._data.car.model
        self._acd = decrypt_ACD(path(AC_CAR_DIR, car_model, 'data.acd'))

        if get('write_acd'):
            source_dir = path(AC_CAR_DIR, car_model, 'data.acd')
            target_dir = path(METADATA_DIR, car_model)
            write_ACD(source_dir, target_dir, self._acd)

        self._car = Car(self._data, self._acd[1])
        self._tyres = Tyres(self._data, self._acd[1])
        self._environment = Environment(self._data)

        self.fire(ACMeta.EVENT.READY)
예제 #3
0
    def __init__(self, data):
        track_name = data.environment.track_name
        track_config = data.environment.track_configuration

        if not track_config:
            file = open(path(AC_TRACK_DIR, track_name, 'ui', 'ui_track.json'), 'r')
        else:
            file = open(path(AC_TRACK_DIR, track_name, 'ui', track_config, 'ui_track.json'), 'r')

        self._track_config = json.loads(file.read(), strict=False)
        file.close()
        self._track_meta = Config(path(METADATA_DIR, track_name, 'ACLIB_track.ini'))

        self._track_meta.set('length', Environment.parse_track_length(self._track_config['length']))
예제 #4
0
    def __init__(self):
        local.application = self
        self.engine = engine()

        self.dispatch = SharedDataMiddleware(self.dispatch, {
            '/media': settings.path('media'),
        })
예제 #5
0
파일: vcs.py 프로젝트: jbalogh/bosley
def apply_testing_patch():
    try:
        call('git am %s' % settings.path('data/testing.patch'))
    except CommandError, status:
        call('git am --abort')
        log.error('Failed to apply testing patch!')
        raise
예제 #6
0
class ACLIBCollapsable(ACLabel):
    TEXTURES = {
        'plus': path(TEXTURE_DIR, 'plus.png'),
        'minus': path(TEXTURE_DIR, 'minus.png')
    }

    def __init__(self, parent: ACWidget, target: ACWidget):
        super().__init__(parent)

        self._collapsed = False

        self._grid = ACGrid(3, 2, self)
        self._button = ACButton(self._grid)
        self._content = ACLabel(self._grid)

        self._button.background_color = WHITE
        self._button.background_texture = ACLIBCollapsable.TEXTURES['plus']

        self._grid.add(self._button, 0, 0)
        self._grid.add(self._content, 0, 1)

        self.content = target

    @property
    def content(self):
        return self._content.child

    @content.setter
    def content(self, content: ACWidget):
        self._content.child = content

    @property
    def collapsed(self) -> bool:
        return self._collapsed

    @collapsed.setter
    def collapsed(self, collapsed: bool):
        self._collapsed = collapsed

        if collapsed:
            self._button.background_texture = ACLIBCollapsable.TEXTURES[
                'minus']
            self._content.visible = False
        else:
            self._button.background_texture = ACLIBCollapsable.TEXTURES['plus']
            self._content.visible = True
예제 #7
0
def load_language(symbol):
    TEXT[symbol] = {}

    cfg = Config(path(LANGUAGE_DIR, symbol + '.ini'),
                 separator=':',
                 only_strings=True)
    for key, val in cfg.dict['DEFAULT'].items():
        if hasattr(TEXT_IDS, key):
            TEXT[symbol][getattr(TEXT_IDS, key)] = val
예제 #8
0
class TopHandler(BaseHandler):

    vocabulary = settings.path(settings.ROOT, "models", "vocab.bin")
    model      = settings.path(settings.ROOT, "models", "japanese_talk_api.chainermodel")
    VOCAB = pickle.load(open(vocabulary, 'rb'))
    MODEL = pickle.load(open(model, 'rb'))

    def get(self):

        query = self.get_argument("q", default="")

        res = {
            "input": query,
            "output": ""
        }

        if query != "":
            parser = argparse.ArgumentParser()

            parser.add_argument('--seed',       type=int,   default=None)
            parser.add_argument('--sample',     type=int,   default=1)
            parser.add_argument('--primetext',  type=str,   default='')
            parser.add_argument('--length',     type=int,   default=2000)
            parser.add_argument('--gpu',        type=int,   default=-1)

            args = parser.parse_args([])

            args.primetext = query
            args.sample = 1
            args.length = 500
            output = prediction(args, vocab=self.VOCAB, model=self.MODEL)

            output = output[len(query):].lstrip("?\n").lstrip("?\n").lstrip("??\n").lstrip("??\n").lstrip().split("\n\n")[0]

            res["output"] = output

        self.set_header("Content-Type", "application/json; charset=utf-8")
        self.write(
            json.dumps(res, ensure_ascii=False))
예제 #9
0
파일: car.py 프로젝트: styinx/ACLIB
    def __init__(self, data, acd: dict):
        car_file = open(path(AC_CAR_DIR, data.car.model, 'ui', 'ui_car.json'),
                        'r',
                        encoding='utf-8')
        self._car_config = json.loads(car_file.read(), strict=False)
        car_file.close()
        self._car_meta = Config(
            path(METADATA_DIR, data.car.model, 'ACLIB_car.ini'))

        self._car_meta.select('Car')
        self._car_meta.set('name', self._car_config['name'])
        self._car_meta.set('class', self._car_config['tags'][0][1:])
        self._car_meta.set('type', self._car_config['class'])
        self._car_meta.set('brand', self._car_config['brand'])
        self._car_meta.set('brand_badge',
                           'content/cars/' + data.car.model + '/ui/badge.png')

        self._car_meta.select('Engine')
        engine_file = Config(acd['engine.ini'])
        engine_file.select('ENGINE_DATA')
        self._car_meta.set('rpm_min', engine_file.get('MINIMUM'))
        self._car_meta.set('rpm_max', engine_file.get('LIMITER'))
        engine_file.select('DAMAGE')
        self._car_meta.set('rpm_damage', engine_file.get('RPM_THRESHOLD'))
예제 #10
0
    def load_app_config(app: object, app_name: str):
        app_config_file = path(CONFIG_DIR, app_name + '.ini')
        if os.path.isfile(app_config_file):
            config = Config(app_config_file)

            if config:
                section = 'DEFAULT'
                if app_name in config:
                    section = app_name
                for prop, val in config.dict[section].items():
                    if hasattr(app, prop):
                        setattr(app, prop, val)

            return config
        return Config(app_config_file)
예제 #11
0
파일: log.py 프로젝트: jbalogh/bosley
def stab_java():
    dir = settings.path('logs')
    if not os.path.exists(dir):
        os.makedirs(dir)

    level = logging.DEBUG

    # Roll over every 3 days, only keep 3 backups.
    h = handlers.TimedRotatingFileHandler(os.path.join(dir, 'bosley.log'),
                                          when='D', interval=3, backupCount=3)
    h.setLevel(level)

    f = logging.Formatter('%(asctime)s %(levelname)s:%(module)s: %(message)s')
    h.setFormatter(f)

    logging.root.addHandler(h)
    logging.root.setLevel(level)
예제 #12
0
파일: log.py 프로젝트: styinx/ACLIB
class Log:
    LOG_2_AC = False
    HANDLE = None
    FILE = path(ACLIB_DOC_DIR, 'log.txt')
    LOGS = 0
    CONSOLE = 0
    MAX_LOGS = 1000
    MAX_CONSOLE = 1000

    @staticmethod
    def init():
        Log.HANDLE = open(Log.FILE, 'w+')

    @staticmethod
    def shutdown():
        Log.HANDLE.close()

    @staticmethod
    def stringify(*what, end: str = '\n'):
        return '{0}{1}'.format(' '.join(map(str, what)), end)
예제 #13
0
파일: app.py 프로젝트: gooftroop/Zeus
    def __init__(self):

        winnebadjango = DjangoWSGIContainer(dwsgi.WSGIHandler())

        base_urls.populate_url_definitions()
        urls = base_urls.url_definitions
        # urls = url_definitions
        urls.append((r"/atlas/(?:api/)?ping", core.Ping))
        urls.append((r"/atlas/(?:api/)?login", core.LoginHandler))
        urls.append((r"/atlas/(?:api/)?logout", core.LogoutHandler))
        urls.append((r"/atlas/(?:api/)?error/?(?P<error>[^ &<])?", core.ErrorHandler))
        urls.append((r"/atlas/(?:api/)?test/mock", atlas.TestHandler))
        urls.append((r"/atlas/(?:api/)?keys/(?P<target>[^ &<]+)", atlas.KeyHandler))
        urls.append((r"/atlas/(?:api/)?commands/?(?P<action>[^ &<]+)?", core.CommandHandler))
        urls.append((r"/atlas/(?:api/)?schema(?P<name>/[^ &<]+)?", core.Schema))
        urls.append((r"/atlas/(?:api/)?upload/?(?P<filename>[^ &<]+)?", core.FileUploadHandler))
        urls.append((r"/atlas/static/(.*)", tornado.web.StaticFileHandler, {
            'path': settings.path(settings.ROOT, "winnebadjango/public/atlas/static")
        }))
        urls.append((r"/atlas/(.*)", core.DjangoHandler, {'fallback': winnebadjango}))

        tornado.web.Application.__init__(self, urls, **settings.APP_SETTINGS)
예제 #14
0
 def __init__(self, path):
     super().__init__()
     self.path_set = settings.path(self, path)
     uic.loadUi(str(self.path['main']/'UI'/'main_window.ui'), self)
     self.splitter.moveSplitter(0, 1)    # moves splitter 0 as close to 1 as possible
     self.setWindowIcon(QtGui.QIcon(str(self.path['main']/'UI'/'graphics'/'main_icon.png')))
     
     # Start threadpools
     self.threadpool = QtCore.QThreadPool()
     self.threadpool.setMaxThreadCount(2) # Sets thread count to 1 (1 for gui - this is implicit, 1 for calc)
     
     # Set selected tabs
     for tab_widget in [self.option_tab_widget, self.plot_tab_widget]:
         tab_widget.setCurrentIndex(0)
     
     # Set Clipboard
     self.clipboard = QApplication.clipboard()
     
     self.var = {'reactor': {'t_unit_conv': 1}}
     self.SIM = mech_fcns.Simulation_Result()
     self.mech_loaded = False
     self.convert_units = convert_units.Convert_Units(self)
     self.series = settings.series(self)
     
     self.sim_explorer = sim_explorer_widget.SIM_Explorer_Widgets(self)
     self.plot = plot(self)
     options_panel_widgets.Initialize(self)
     self.mech = mech_fcns.Chemical_Mechanism()
     
     # Setup save sim
     self.save_sim = save_widget.Save_Dialog(self)
     self.save_sim_button.clicked.connect(self.save_sim.execute)
     self.action_Save.triggered.connect(self.save_sim.execute)
     
     # Initialize Settings
     self.initialize_settings()
     
     self.show()
예제 #15
0
#!/usr/bin/env python
from django.core.management import execute_manager
import sys

try:
    import settings # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
    sys.exit(1)

from settings import path
sys.path.insert(0, path("apps/"))
sys.path.insert(0, path("lib/"))
sys.path.insert(0, path("./"))

if __name__ == "__main__":
    execute_manager(settings)
예제 #16
0
파일: ML.py 프로젝트: ohlindavid/Exjobb
import matplotlib.pyplot as plt
import os, sys
import tensorflow.keras.backend as K
from settings import path, pathPred
from generator import signalLoader
import pickle
import math

nchan = 31  #Antal kanaler
L = 81  #EEG-längd per epok innan TF-analys
T = 81 * 4 / 2049

labels = np.zeros((1, 60))
labels2 = np.ones((1, 60))
labels = np.append(labels, labels2)
names = os.listdir(path())
labelsnames = np.concatenate([[names], [labels]], 0)
labelsnames = np.transpose(labelsnames)
np.random.shuffle(labelsnames)
labelsnames = np.transpose(labelsnames)
names = labelsnames[0, :]
labels = labelsnames[1, :]
labels = labels.astype(np.float)

predlabels = np.zeros((1, 32))
predlabels2 = np.zeros((1, 32))
predlabels = np.append(labels, labels2)
prednames = os.listdir(pathPred())

TR_ACC = []
TR_LOSS = []
예제 #17
0
파일: urls.py 프로젝트: Soares/graveyard
from settings import path
from django.conf import settings
from django.conf.urls.defaults import patterns, include
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Example:
    # (r'^equatize/', include('equatize.foo.urls')),

    (r'^admin/doc/', include('django.contrib.admindocs.urls')),
    (r'^admin/', include(admin.site.urls)),
    (r'^$', 'django.views.generic.simple.direct_to_template',
        {'template': 'main.html'}),
)

if settings.DEBUG:
    urlpatterns += patterns('',
        (r'^tinymce/(?P<path>.*)$', 'django.views.static.serve',
            {'document_root': path(settings.MEDIA_ROOT, 'tinymce-dev', 'jscripts', 'tiny_mce')}),
        (r'^%s/(?P<path>.*\.(?!js|css).*)$' % settings.MEDIA_URL, 'django.views.static.serve',
            {'document_root': settings.MEDIA_ROOT}),
    )
예제 #18
0
import cv2
import tools
import settings

cap = cv2.VideoCapture(0)
faceCascade = cv2.CascadeClassifier(settings.path())
font = cv2.FONT_HERSHEY_DUPLEX
is_save_face = int(input("是否需要保存图片[0-False, 1-True]:"))
path = "face_images/"
origin_count, total_count = 0, 0
if is_save_face:
    face_id = str(input("人脸编号:"))
    face_count = int(input("人脸数量:"))
    path = path + str(face_id)
    origin_count = tools.mkdir(path)
    total_count = origin_count + face_count

while cap.isOpened():
    ret_flag, frame = cap.read()
    frame = cv2.flip(frame, 1)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    # 人脸检测
    faces = faceCascade.detectMultiScale(
        gray,  # 灰度图,使用灰度图会提高效率
        scaleFactor=1.05,  # 图片缩小的值
        minNeighbors=20,  # 判断次数
        minSize=(72, 72)  # 人脸最小尺寸
    )
    for (x, y, w, h) in faces:
        # 画脸的方框
        # 图像源,原点,终点,线的颜色,粗细
예제 #19
0
파일: tyres.py 프로젝트: styinx/ACLIB
    def __init__(self, data, acd: dict):
        self._acd = acd
        self._brake_config = Config(self._acd['brakes.ini'], only_strings=True)
        self._tyre_config = Config(self._acd['tyres.ini'], only_strings=True)
        self._tyre_meta = Config(
            path(METADATA_DIR, data.car.model, 'ACLIB_tyres.ini'))

        compound = ''
        for sec_name, section in self._tyre_config.dict.items():
            if 'NAME' in section:
                compound = section['NAME']

            if compound and section:
                self._tyre_meta.select(compound)

                if sec_name.find('THERMAL_FRONT') > -1 or sec_name.find(
                        'THERMAL_REAR') > -1:
                    position = 'front' if sec_name.find(
                        'THERMAL_FRONT') > -1 else 'rear'
                    self._tyre_meta.set(
                        position + '_temp_curve',
                        self._lut_dict(section['PERFORMANCE_CURVE']))

                elif sec_name.find('FRONT') > -1 or sec_name.find('REAR') > -1:
                    position = 'front' if sec_name.find(
                        'FRONT') > -1 else 'rear'
                    self._tyre_meta.set(position + '_ideal_pressure',
                                        section['PRESSURE_IDEAL'])
                    self._tyre_meta.set(position + '_wear_curve',
                                        self._lut_dict(section['WEAR_CURVE']))

        self._tyre_meta.select('Brakes')
        if 'TEMPS_FRONT' in self._brake_config.dict:
            if 'PERF_CURVE' in self._brake_config['TEMPS_FRONT']:
                self._tyre_meta.set(
                    'front_brake_temp_curve',
                    self._lut_dict(
                        self._brake_config['TEMPS_FRONT']['PERF_CURVE']))

                self._tyre_meta.set(
                    'rear_brake_temp_curve',
                    self._lut_dict(
                        self._brake_config['TEMPS_REAR']['PERF_CURVE']))
            else:
                # If there is no data on the brake temperature we use a default
                self._tyre_meta.set(
                    'front_brake_temp_curve',
                    self._inline_lut_dict(
                        '(|0=0.70|300=0.8|500=1.0|600=1.0|800=0.7|1200=0.2|)'))
                self._tyre_meta.set(
                    'rear_brake_temp_curve',
                    self._inline_lut_dict(
                        '(|0=0.70|300=0.8|500=1.0|600=1.0|800=0.7|1200=0.2|)'))
        else:
            # If there is no data on the brake temperature we use a default
            self._tyre_meta.set(
                'front_brake_temp_curve',
                self._inline_lut_dict(
                    '(|0=0.70|300=0.8|500=1.0|600=1.0|800=0.7|1200=0.2|)'))
            self._tyre_meta.set(
                'rear_brake_temp_curve',
                self._inline_lut_dict(
                    '(|0=0.70|300=0.8|500=1.0|600=1.0|800=0.7|1200=0.2|)'))
예제 #20
0
class ACLIBScaler(ACGrid):
    """
    Use this widget to get a plus and minus button that scales another widget.
    Use 'absolute = True' to have an absolute scale to increase/decrease the widget with pixel size.
    'scale = 1' means that the target will scale 1 pixel in width and height.
    Using 'absolute = False' will scale the target relative.
    'scale = 0.1' will increase/decrease the target by 10%.
    """

    TEXTURES = {
        'plus': path(TEXTURE_DIR, 'plus.png'),
        'minus': path(TEXTURE_DIR, 'minus.png')
    }

    def __init__(self,
                 parent: ACWidget,
                 target: ACWidget,
                 step: float = 1,
                 absolute: bool = False):
        super().__init__(1, 2, parent)

        self._target = target
        self._absolute = absolute
        self._step = abs(step)
        self._scale = 0 if self._absolute else 1
        self._original_size = target.size
        self._current_size = target.size

        self._plus = ACButton(self)
        self._minus = ACButton(self)

        self._plus.background_color = WHITE
        self._plus.background_texture = ACLIBScaler.TEXTURES['plus']
        self._minus.background_color = WHITE
        self._minus.background_texture = ACLIBScaler.TEXTURES['minus']

        self.add(self._plus, 0, 0)
        self.add(self._minus, 0, 1)

        self._plus.on(ACWidget.EVENT.ON_MOUSE_DOWN, self.on_plus)
        self._minus.on(ACWidget.EVENT.ON_MOUSE_DOWN, self.on_minus)

    def initial_size(self, size: tuple):
        self._target.size = size
        self._original_size = size

    def on_plus(self, *args):
        self._scale += self._step

        if self._absolute:
            w, h = self._original_size
            self._target.size = (w + self._scale, h + self._scale)
        else:
            w, h = self._original_size
            self._target.size = (round(w * self._scale),
                                 round(h * self._scale))

    def on_minus(self, *args):
        if self._absolute:
            self._scale -= self._step
            w, h = self._original_size
            self._target.size = (w - self._scale, h - self._scale)
        else:
            self._scale = max(self._step, self._scale - self._step)
            w, h = self._original_size
            self._target.size = (round(w * self._scale),
                                 round(h * self._scale))
예제 #21
0
class Comparator(ACApp):
    TEXTURES = {
        'left': path(TEXTURE_DIR, 'arrow-left-slim.png'),
        'right': path(TEXTURE_DIR, 'arrow-right-slim.png')
    }

    MODE = ['Lap Time', 'Sector Time']

    def __init__(self, data: ACData = None, meta: ACMeta = None):
        super().__init__('ACLIB Comparator', 200, 200, 300, 55, True)

        self.hide_decoration()
        self.background_color = Color(0.1, 0.1, 0.1, 0.5)

        self._data = data
        self._meta = meta

        self._mode = 0
        self._opponents = []

        self._grid = ACGrid(12, 11, self)
        self._header = CR_Header(self._grid, 'Lap Time')
        self._left = CR_Icon(self._grid, Comparator.TEXTURES['left'])
        self._right = CR_Icon(self._grid, Comparator.TEXTURES['right'])
        self._add = CR_Button(self._grid, 'Add Opponent')
        self._remove = CR_Button(self._grid, 'Remove Opponent')

        self._grid.add(self._left, 0, 0, 1, 6)
        self._grid.add(self._header, 1, 0, 10, 6)
        self._grid.add(self._right, 11, 0, 1, 6)
        self._grid.add(self._add, 0, 6, 6, 5)
        self._grid.add(self._remove, 6, 6, 6, 5)

        self._left.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_left)
        self._right.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_right)
        #self._add.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_add)
        #self._remove.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_remove)

        self._add_opponent(0)
        self._add_opponent(1)

    def _add_opponent(self, i):
        w, h = self.size

        opponent = ComparatorRow(self._grid, self._data, self._meta)
        opponent.position = 0, h + i * 50
        opponent.size = w, 50
        self._opponents.append(opponent)

        # self._grid.add_rows(2)
        # w, h = self.size
        # self.size = w, h + 40
        # self._grid.add(opponent, 0, 4 + len(self._opponents) * 2, 12, 2)

    def _on_mode_changed(self):
        for opponent in self._opponents:
            opponent.change_mode(self._mode)

    def _on_left(self, *args):
        if self._mode > 0:
            self._mode -= 1
        else:
            self._mode = len(Comparator.MODE) - 1
        self._header.text = Comparator.MODE[self._mode]

        self._on_mode_changed()

    def _on_right(self, *args):
        if self._mode < len(Comparator.MODE) - 1:
            self._mode += 1
        else:
            self._mode = 0
        self._header.text = Comparator.MODE[self._mode]

        self._on_mode_changed()

    def _on_add(self, *args):
        self._grid.add_rows(2)
        w, h = self.size
        self.size = w, h + 40

    def _on_remove(self, *args):
        if len(self._opponents) > 0:
            self._grid.remove_rows(2)
            w, h = self.size
            self.size = w, h - 40

    def update(self, delta: float):
        super().update(delta)

        for o in self._opponents:
            o.update(delta)
예제 #22
0
class ComparatorRow(ACGrid):
    TEXTURES = {
        'left': path(TEXTURE_DIR, 'arrow-left-slim.png'),
        'right': path(TEXTURE_DIR, 'arrow-right-slim.png')
    }
    COLORS = {
        'gb': PURPLE,
        'pb': Color(0.0, 0.75, 0, 1.0),
        'pw': Color(0.7, 0.7, 0, 1.0)
    }

    def __init__(self, parent: ACWidget, data: ACData, meta: ACMeta):
        super().__init__(12, 2, parent)

        self.background_color = Color(0, 0, 0, 0.5)

        self._data = data
        self._meta = meta

        self._mode = 0
        self._index = 0
        self._player = self._data.players[self._index]
        self._server = self._data.server
        self._sec_format = '{s:02d}.{ms:03d}'
        self._on_player_lap_changed_callback_id = None

        self._label = CR_Name(self, self._player.name)
        self._label.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._focus_player)
        self._multi = ACMultiWidget(self)

        self._laps = ACHBox(self)
        self._bst = CR_Label(self._laps, 'BST: --:--:---')
        self._lst = CR_Label(self._laps, 'LST: --:--:---')

        self._sector_box = ACHBox(self)
        self._sectors = []
        self._sectors.append(CR_Label(self._sector_box, 'S1: --:---'))
        self._sectors.append(CR_Label(self._sector_box, 'S2: --:---'))
        self._sectors.append(CR_Label(self._sector_box, 'S3: --:---'))

        self._left = CR_Icon(self, ComparatorRow.TEXTURES['left'])
        self._right = CR_Icon(self, ComparatorRow.TEXTURES['right'])

        self._laps.add(self._bst)
        self._laps.add(self._lst)

        self._sector_box.add(self._sectors[0])
        self._sector_box.add(self._sectors[1])
        self._sector_box.add(self._sectors[2])

        self._multi.add(self._laps)
        self._multi.add(self._sector_box)

        self.add(self._left, 0, 0)
        self.add(self._label, 1, 0, 10, 1)
        self.add(self._right, 11, 0)
        self.add(self._multi, 0, 1, 12, 1)

        self.change_mode(self._mode)

        self._left.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_left)
        self._right.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_right)

    def _focus_player(self, *args):
        ac.focusCar(self._index)

    def _update_index(self):
        self._player = self._data.players[self._index]
        self._label.text = self._player.name

    def _on_left(self, *args):
        if self._index > 0:
            self._index -= 1
        else:
            self._index = self._server.cars - 1

        self._update_index()

    def _on_right(self, *args):
        if self._index < self._server.cars - 1:
            self._index += 1
        else:
            self._index = 0

        self._update_index()

    def change_mode(self, mode: int):
        self._mode = mode

        if self._mode == 0:
            self._laps.visible = True
            self._sector_box.visible = False
        elif self._mode == 1:
            self._laps.visible = False
            self._sector_box.visible = True

    def update_best_last_lap(self, lap: int):
        # todo add multiplayer events
        pass

    def update(self, delta: float):
        super().update(delta)

        # Update every 300 ms.
        if (self.update_timer * 10) % 3 == 0:

            if self._mode == 1:
                player = self._player[self._index]

                for i in range(0, 3):
                    self._sectors[i].text = 'S{}: {}'.format(
                        i + 1,
                        Format.duration(player.sector_time(i),
                                        form=self._sec_format))

                    if i != player.sector_index and player.sector_time(i) > 0:
                        if player.sector_time(i) == player.gb_sector_time(i):
                            self._sectors[i].font = CR_Label.BRIGHT
                            self._sectors[
                                i].background_color = ComparatorRow.COLORS[
                                    'gb']
                        elif player.sector_time(i) == player.pb_sector_time(i):
                            self._sectors[i].font = CR_Label.DARK
                            self._sectors[
                                i].background_color = ComparatorRow.COLORS[
                                    'pb']
                        else:
                            self._sectors[i].font = CR_Label.DARK
                            self._sectors[
                                i].background_color = ComparatorRow.COLORS[
                                    'pw']
                    else:
                        self._sectors[i].font = CR_Label.BRIGHT
                        self._sectors[i].background_color = BLACK

        # Update every second.
        if self._update_timer > 1.0:
            self.reset_update_timer()

            if self._mode == 0:
                player = self._player[self._index]

                self._bst.text = 'BST: ' + Format.duration(player.best_lap)
                self._lst.text = 'LST: ' + Format.duration(player.last_lap)

                if player.last_lap > 0 and player.last_lap == player.gb_lap_time:
                    self._lst.font = CR_Label.BRIGHT
                    self._lst.background_color = ComparatorRow.COLORS['gb']
                elif player.last_lap == player.pb_lap_time:
                    self._lst.font = CR_Label.DARK
                    self._lst.background_color = ComparatorRow.COLORS['pb']
                else:
                    self._lst.font = CR_Label.BRIGHT
                    self._lst.background_color = BLACK

                if player.best_lap > 0 and player.best_lap == player.gb_lap_time:
                    self._bst.font = CR_Label.BRIGHT
                    self._bst.background_color = ComparatorRow.COLORS['gb']
                elif player.best_lap == player.pb_lap_time:
                    self._bst.font = CR_Label.DARK
                    self._bst.background_color = ComparatorRow.COLORS['pb']
                else:
                    self._bst.font = CR_Label.BRIGHT
                    self._bst.background_color = BLACK
예제 #23
0
class ACLIBListBox(ACLayout):
    """
    This widget enables scrolling on a list of items. Items must inherit from ACWidget.
    The widget has a scrollbar and two buttons. One arrow scrolls the list upwards, the other arrow scrolls downwards.
    The number of elements that are shown is configurable. Items that are not inside the item range are hidden.
    """

    TEXTURES = {
        'up': path(TEXTURE_DIR, 'triangle_up.png'),
        'down': path(TEXTURE_DIR, 'triangle_down.png')
    }

    def __init__(self,
                 parent: ACWidget,
                 elements: int = 5,
                 highlight: bool = True):
        super().__init__(parent)

        self._elements = elements
        self._highlight = highlight
        self._bar_width = 10
        self._index = 0
        self._widgets = []

        self._bar = ACButton(self)
        self._bar.background_color = WHITE

        self._up = ACButton(self)
        self._up.background_texture = ACLIBListBox.TEXTURES['up']
        self._up.background_color = LIGHTGRAY
        self._up.size = self._bar_width, self._bar_width

        self._down = ACButton(self)
        self._down.background_texture = ACLIBListBox.TEXTURES['down']
        self._down.background_color = LIGHTGRAY
        self._down.size = self._bar_width, self._bar_width

        if self._highlight:
            self._highlight_label = ACLabel(self)
            self._highlight_label.background_color = Color(1.0, 0.0, 0.0, 0.75)

        self._up.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_up)
        self._down.on(ACWidget.EVENT.ON_MOUSE_DOWN, self._on_down)

    # Private

    def _on_position_changed(self, *args):
        if hasattr(self, '_up'):
            x, y = self.position
            w, h = self.size
            right = x + w - self._bar_width
            self._bar.position = right, y + self._bar_width
            self._up.position = right, y
            self._down.position = right, y + h - self._bar_width
            if self._highlight:
                self._highlight_label.position = x, y

    def _on_size_changed(self, *args):
        if hasattr(self, '_up'):
            x, y = self.position
            w, h = self.size
            right = x + w - self._bar_width
            self._bar.size = self._bar_width, h - self._bar_width * 2
            self._bar.position = right, y + self._bar_width
            self._up.position = right, y
            self._down.position = right, y + h - self._bar_width
            if self._highlight:
                self._highlight_label.size = w - self._bar_width, h / self._elements

    def _reposition(self):
        x, y = self.position
        w, h = self.size

        element_height = h / self._elements

        # Hide items that are out of range.
        for i in range(0, self._index):
            self._widgets[i].visible = False
        for i in range(self._index + self._elements,
                       max(self._index + self._elements, len(self._widgets))):
            self._widgets[i].visible = False

        # Set the position and size of the items inside the list.
        for i in range(self._index,
                       min(len(self._widgets), self._index + self._elements)):
            self._widgets[i].position = x, y
            self._widgets[i].size = w - self._bar_width, element_height
            self._widgets[i].visible = True
            y += element_height

    def _on_up(self, *args):
        if self._index > 0:
            self.index = self._index - 1
        self._reposition()

    def _on_down(self, *args):
        if self._index < len(self._widgets) - self._elements:
            self.index = self._index + 1
        self._reposition()

    # Public

    def render(self, delta: int):
        super().render(delta)
        x, y = self.position
        w, h = self.size

        element_height = h / self._elements
        rect(x, y, w - self._bar_width, element_height, RED, False)

    @property
    def value(self):
        if 0 <= self._index < len(self._widgets):
            return self._widgets[self._index]
        return None

    @property
    def index(self):
        return self._index

    @index.setter
    def index(self, index: int):
        if 0 <= index < len(self._widgets):
            self._index = index
            self._reposition()
            self.fire(ACWidget.EVENT.INDEX_CHANGED, self._index)

    @property
    def count(self):
        return self._elements

    @count.setter
    def count(self, count: int):
        self._elements = count
        self._reposition()

    def add(self, widget: ACWidget):
        self._widgets.append(widget)

        self._reposition()

    def remove(self, widget: ACWidget = None, index: int = -1):
        if widget:
            self._widgets.remove(widget)
        elif 0 <= index < len(self._widgets):
            del self._widgets[index]

        self._reposition()

    def clear(self):
        for w in self._widgets:
            del w
        self._index = 0
예제 #24
0
파일: manage.py 프로젝트: Callek/tuxedo
#!/usr/bin/env python
import site

from django.core.management import execute_manager


try:
    import settings # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write(
        "Error: Can't find the file 'settings.py' in the directory containing "
        "%r. It appears you've customized things.\nYou'll have to run "
        "django-admin.py, passing it your settings module.\n(If the file "
        "settings.py does indeed exist, it's causing an ImportError "
        "somehow.)\n" % __file__)
    sys.exit(1)


site.addsitedir(settings.path('apps'))


if __name__ == "__main__":
    execute_manager(settings)
예제 #25
0
파일: runtests.py 프로젝트: jbalogh/bosley
import traceback
from Queue import Queue

import lockfile

import remote
import settings
import vcs
from models import Revision, TestFile, Test, Assertion, BrokenTest, Result
from utils import force_unicode, metadata, Session

log = logging.getLogger(__file__)

CommitLock = threading.Lock()

LOCKFILE_PATH = settings.path('bosley.lock')


def handle(commit):
    """Setup the repo at commit and run the tests."""
    lock = lockfile.FileLock(LOCKFILE_PATH)
    # Don't block waiting for a lock. TODO: make this configurable.
    try:
        lock.acquire(0)
        log.debug('Processing %s' % commit)
        try:
            vcs.checkout(commit)

            try:
                # TODO: fixme!
                vcs.call('./reset.sh')
예제 #26
0
#!/usr/bin/env python
import site

from django.core.management import execute_manager

try:
    import settings  # Assumed to be in the same directory.
except ImportError:
    import sys
    sys.stderr.write(
        "Error: Can't find the file 'settings.py' in the directory containing "
        "%r. It appears you've customized things.\nYou'll have to run "
        "django-admin.py, passing it your settings module.\n(If the file "
        "settings.py does indeed exist, it's causing an ImportError "
        "somehow.)\n" % __file__)
    sys.exit(1)

site.addsitedir(settings.path('apps'))

if __name__ == "__main__":
    execute_manager(settings)
예제 #27
0
파일: scss.py 프로젝트: agentwx/snippets
    def sassRun(cls, dst_file):
        if dst_file in cls.watchers:
            return

        import os
        ofd = open(os.devnull, 'w')

        orig_file = dst_file.replace('.css', '.scss')
        pobj = subprocess.Popen(['sass', '--watch', '%s:%s' % (orig_file, dst_file)], stderr=ofd, cwd=path(*cls.CSS_DIR))
        time.sleep(0.1)     # There has to be something better than a sleep
        cls.watchers[dst_file] = pobj
예제 #28
0
파일: scss.py 프로젝트: agentwx/snippets
    def sassData(cls, dst_file):
        if dst_file in cls.depend and dst_file in cls.cache:
            data = cls.cache[dst_file]
            modified = 0
            for filename, lastmod in cls.depend[dst_file].items():
                modified = max(lastmod, modified)
                if os.stat(filename)[8] != lastmod:
                    data = None
                    break

            if data:
                return (data, modified)

        orig_file = dst_file.replace('.css', '.scss')
        p = subprocess.Popen(['sass', '-g', '%s' % (orig_file)], stdout=subprocess.PIPE, cwd=path(*cls.CSS_DIR))
        data = p.stdout.read()

        deps = {}
        for line in data.split("\n"):
            if line.startswith('@media -sass-debug-info{filename{'):
                m = cls.DEP_RE.search(line)
                if m:
                    filename = m.group('filename')
                    filename = filename.replace('\\', '')[7:]
                    if filename not in deps:
                        deps[filename] = os.stat(filename)[8]

        cls.depend[dst_file] = deps
        cls.cache[dst_file] = data

        modified = max(deps.values())

        return (data, modified)
예제 #29
0
"""Creates SZ maps with ORP."""

# https://app.flourish.studio/visualisation/7917801/
# https://app.flourish.studio/visualisation/7917809/

import datetime
# import numpy as np
import pandas as pd

# resolve path
import sys
sys.path.insert(0, 'orp/')
try:
    import settings
    path = settings.path() + "orp/"
except ImportError:
    path = "orp/"

# get data
data = pd.read_csv(path + "orps.csv")
source = pd.read_csv(
    "https://onemocneni-aktualne.mzcr.cz/api/v2/covid-19/orp.csv")

# reorder data
sincidence = pd.pivot_table(source,
                            index=['orp_kod'],
                            columns=['datum'],
                            values=['incidence_7']).reset_index()
sprevalence = pd.pivot_table(source,
                             index=['orp_kod'],
                             columns=['datum'],