def __init__(self):
        QFrame.__init__(self)
        SingleLinkableSetting.__init__(self, "api_key")

        self.library = Library(get_setting("cache_dir"))

        self.loadables_combobox = QComboBox(self)
        self.loadables_combobox.setInsertPolicy(QComboBox.NoInsert)
        for loadable in MainTab.LOADABLES_COMBOBOX_REGISTRY:
            self.loadables_combobox.addItem(loadable, loadable)
        self.loadables_combobox.activated.connect(self.add_loadable)

        self.checks_combobox = QComboBox(self)
        self.checks_combobox.setInsertPolicy(QComboBox.NoInsert)
        for check in MainTab.CHECKS_COMBOBOX_REGISTRY:
            self.checks_combobox.addItem(check, check)
        self.checks_combobox.activated.connect(self.add_check)

        self.loadables_scrollarea = QScrollArea(self)
        self.loadables_scrollarea.setWidget(ScrollableLoadablesWidget())
        self.loadables_scrollarea.setWidgetResizable(True)

        self.checks_scrollarea = QScrollArea(self)
        self.checks_scrollarea.setWidget(ScrollableChecksWidget())
        self.checks_scrollarea.setWidgetResizable(True)

        self.loadables = [] # for deleting later
        self.checks = [] # for deleting later

        self.print_results_signal.connect(self.print_results)
        self.write_to_terminal_signal.connect(self.write)

        self.q = Queue()
        self.cg_q = Queue()
        self.helper_thread_running = False
        self.runs = [] # Run objects for canceling runs
        self.run_id = 0
        self.visualizer = None

        terminal = QTextEdit(self)
        terminal.setFocusPolicy(Qt.ClickFocus)
        terminal.setReadOnly(True)
        terminal.ensureCursorVisible()
        self.terminal = terminal

        self.run_button = QPushButton()
        self.run_button.setText("Run")
        self.run_button.clicked.connect(self.add_circleguard_run)
        # disable button if no api_key is stored
        self.on_setting_changed("api_key", get_setting("api_key"))

        layout = QGridLayout()
        layout.addWidget(self.loadables_combobox, 0, 0, 1, 4)
        layout.addWidget(self.checks_combobox, 0, 8, 1, 4)
        layout.addWidget(self.loadables_scrollarea, 1, 0, 4, 8)
        layout.addWidget(self.checks_scrollarea, 1, 8, 4, 8)
        layout.addWidget(self.terminal, 5, 0, 2, 16)
        layout.addWidget(self.run_button, 7, 0, 1, 16)

        self.setLayout(layout)
Beispiel #2
0
def logout(session_id):
    url = settings.get_setting('BASE_URL') \
    + settings.get_setting('LOGOUT_URL')
    try:
        requestOp(op="post", url=url, headers=get_session_hdr(session_id))
    except:
        return
Beispiel #3
0
    def __init__(self):
        super().__init__()
        self.result_frame = ResultsTab()
        self.result_frame.results.info_label.hide()
        self.map_id = None
        self.q = Queue()
        self.replays = []
        cache_path = get_setting("cache_dir") + "circleguard.db"
        self.cg = Circleguard(get_setting("api_key"), cache_path)
        self.info = QLabel(self)
        self.info.setText(
            "Visualizes Replays. Has theoretically support for an arbitrary amount of replays."
        )
        self.label_map_id = QLabel(self)
        self.update_map_id_label()
        self.file_chooser = FolderChooser("Add Replays",
                                          folder_mode=False,
                                          multiple_files=True,
                                          file_ending="osu! Replayfile (*osr)",
                                          display_path=False)
        self.file_chooser.path_signal.connect(self.add_files)
        self.folder_chooser = FolderChooser("Add Folder", display_path=False)
        self.folder_chooser.path_signal.connect(self.add_folder)
        layout = QGridLayout()
        layout.addWidget(self.info)
        layout.addWidget(self.file_chooser)
        layout.addWidget(self.folder_chooser)
        layout.addWidget(self.label_map_id)
        layout.addWidget(self.result_frame)

        self.setLayout(layout)
 def __init__(self, beatmap_info, replays=[], events=[], library=None):
     speeds = get_setting("speed_options")
     start_speed = get_setting("default_speed")
     paint_info = get_setting("visualizer_info")
     super().__init__(beatmap_info, replays, events, library, speeds,
                      start_speed, paint_info)
     self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))
Beispiel #5
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # INIT WIDGET
        self.doubleSpinBoxFreq.setValue(
            float(settings.get_setting(path_settings, 'Settings', 'freq')))
        self.doubleSpinBoxPow.setValue(
            float(settings.get_setting(path_settings, 'Settings', 'power')))
        self.lineEditRds.setText(
            settings.get_setting(path_settings, 'Settings', 'rds'))

        # SLOTS
        commun.signalT.connect(self.temperature)
        self.doubleSpinBoxFreq.valueChanged.connect(self.freq)
        self.doubleSpinBoxPow.valueChanged.connect(self.power)
        self.pushButtonRds.clicked.connect(self.rds)
        self.pushButtonTerminal.clicked.connect(self.terminal)

        # QN8027
        qn8027.init()
        self.freq()
        self.power()
        self.rds()

        #OVERHEAT
        self.overheat = False
Beispiel #6
0
    def setupUi(self, main_window):
        super(Ui_MainWindow, self).setupUi(main_window)
        self.main_window = main_window
        self.init_combo_version()
        self.wait_overlay = wait_overlay_widget.WaitOverlay(main_window,
                                                            opacity=50,
                                                            circle_size=15,
                                                            nb_dots=9,
                                                            dot_size=8,
                                                            color=QtGui.QColor(
                                                                98, 74, 91))
        self.wait_overlay.hide()

        self.text_log = QtWidgets.QTextEdit(self.verticalWidget)
        palette = QtGui.QPalette()
        brush = QtGui.QBrush(QtGui.QColor(98, 73, 91))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(98, 73, 91))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
        brush = QtGui.QBrush(QtGui.QColor(178, 146, 169))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
        self.text_log.setPalette(palette)
        self.text_log.setObjectName("text_log")
        self.horizontal_layout_log.addWidget(self.text_log)
        self.text_log.hide()

        self.checkbox_enterprise.stateChanged.connect(
            self.onchange_checkbox_enterprise)
        self.checkbox_enterprise.setChecked(
            bool(settings.get_setting('USE_ENTERPRISE')))
        self.onchange_checkbox_enterprise()

        self.tool_menu = QtWidgets.QMenu(self.main_window)
        self.action_select_database = QtWidgets.QAction(
            _translate('MainWindow', 'Select database'))
        self.tool_menu.addAction(self.action_select_database)
        self.action_config_database = QtWidgets.QAction(
            _translate('MainWindow', 'Database configuration'))
        self.tool_menu.addAction(self.action_config_database)
        self.push_tools.setMenu(self.tool_menu)

        self.line_edit_enterprise_path.setText(
            settings.get_setting('ENTERPRISE_PATH'))

        self.push_button_start.setIcon(
            svg_icon.get_svg_icon("/ui/img/play.svg"))
        self.push_addons.setIcon(svg_icon.get_svg_icon("/ui/img/store.svg"))
        self.push_update_all.setIcon(
            svg_icon.get_svg_icon("/ui/img/refresh.svg"))
        self.push_tools.setIcon(svg_icon.get_svg_icon("/ui/img/tools.svg"))
        self.push_logs.setIcon(svg_icon.get_svg_icon("/ui/img/bug.svg"))
        self.push_openugrade.setIcon(
            svg_icon.get_svg_icon("/ui/img/upgrade.svg"))

        self.push_logs.clicked.connect(self.show_logs)
        self.push_addons.clicked.connect(self.show_dialog_addons)
 def __init__(self, redirect_uri='', approval_prompt='auto', scope=''):
     self.flow = OAuth2WebServerFlow(
         client_id=get_setting('OAUTH2_CLIENT_ID'),
         client_secret=get_setting(
             'OAUTH2_CLIENT_SECRET'),
         scope=scope,
         redirect_uri=redirect_uri,
         approval_prompt=approval_prompt)
Beispiel #8
0
def summary(results):
    from settings import get_file
    from settings import get_setting
    data = get_setting('SUMMARY')
    file_path = get_file('SUMMARY_FILE')
    pipeline = get_setting('PIPELINE')
    with open(file_path,'w') as f:
        for number, key in data:
            f.write('\n==== step %d - %s (module %s)  ====\n' % (number, key, pipeline[number][0]))
            f.write(format(results[number][key]))
Beispiel #9
0
 def cg(self):
     # if the user has changed their api key since we last retrieved our
     # circleguard instance, recreate circleguard with the new key.
     new_api_key = get_setting('api_key')
     if new_api_key != self.old_api_key or not self._cg:
         from circleguard import Circleguard
         cache_path = get_setting("cache_dir") + "circleguard.db"
         self._cg = Circleguard(new_api_key, cache_path)
         self.old_api_key = new_api_key
     return self._cg
Beispiel #10
0
    def save_config(self):
        """Apply and save new settings."""
        settings.set_settings("sound", round(self.sound, 1))
        settings.set_settings("music", round(self.music, 1))
        settings.set_settings("classic", self.classic)
        settings.save_config()

        # Set volumes
        resources.set_volume(settings.get_setting("sound"))
        pygame.mixer.music.set_volume(settings.get_setting("music"))
Beispiel #11
0
    def __init__(self):
        super().__init__()
        self.index = 0
        self.sound = settings.get_setting("sound")
        self.music = settings.get_setting("music")
        self.classic = settings.get_setting("classic")
        self.options = [
            "Sound Effects", "Music", "Graphics", "Change Controls",
            "Save and Return to Main Menu"
        ]

        # Create sliders
        self.sound_slider = Slider(self.sound, 250)
        self.music_slider = Slider(self.music, 250)
Beispiel #12
0
        def __init__(self, beatmap_info, replays=[], events=[], library=None):
            speeds = get_setting("speed_options")
            start_speed = get_setting("default_speed")
            snaps_args = {
                "only_on_hitobjs": get_setting("ignore_snaps_off_hitobjs")
            }

            super().__init__(beatmap_info,
                             replays,
                             events,
                             library,
                             speeds,
                             start_speed,
                             snaps_args=snaps_args)
            self.setWindowIcon(QIcon(resource_path("logo/logo.ico")))
Beispiel #13
0
    def run(self):
        exe = get_setting('CLUSTALW_PATH')
        tree_file = get_file('CLUSTALW_NEWTREE', None)
        if tree_file is None:
            tree_file = create_tmp()
        cline = ClustalwCommandline(exe, infile=self.input, newtree=tree_file)
        build_tree_out, build_tree_err = cline()
        result = {
            'tree': Bio.Phylo.read(tree_file, 'newick'),
            'tree_out': build_tree_out,
            'tree_err': build_tree_err,
        }
        if self.only_tree:
            return result

        outfile = get_file('CLUSTALW_OUTFILE', None)
        if outfile is None:
            outfile = create_tmp()
        cline = ClustalwCommandline(exe, infile=self.input, outfile=outfile)
        ###Fix "p.checker_function = lambda x: os.path.exists"
        param = [i for i,p in enumerate(cline.parameters) 
            if 'usetree' in p.names]
        cline.parameters[param[0]].checker_function = os.path.exists
        ###
        setattr(cline, 'usetree', tree_file)
        align_out, align_err = cline()
        result.update({
            'align_out': align_out,
            'align_err': align_err,
            'alignment': inout.AlignFileInput(file=outfile, format='clustal').read(),
        })
        return result
Beispiel #14
0
def song_search(bot, update, groups, lang):
    switch_pm = (_('Searching only songs'), 'help_inline')
    originals_only = get_setting('originals', bot, update)
    return voca_db.songs(groups[0],
                         lang,
                         max_results=MAX_INLINE_RESULTS,
                         originals_only=originals_only), switch_pm
Beispiel #15
0
 def _ratelimited(length):
     message = get_setting("message_ratelimited")
     ts = datetime.now()
     self.write_to_terminal_signal.emit(
         message.format(s=length, ts=ts))
     self.update_label_signal.emit("Ratelimited")
     self.update_run_status_signal.emit(run.run_id, "Ratelimited")
 def emit(self, record):
     message = self.format(record)
     # replace api keys with asterisks if they get into the logs from eg a
     # stacktrace
     api_key = get_setting("api_key")
     message = message.replace(api_key, "*" * len(api_key))
     self.new_message.emit(message)
Beispiel #17
0
def format(value):
    from settings import get_setting
    summary_type = get_setting('SUMMARY_TYPE')
    if summary_type == "HUMAN_READABLE":
        return human_readable(value)
    else:
        return str(value)
    def log(self, message):
        """
        Message is the string message sent to the io stream
        """

        # TERMINAL / BOTH
        if get_setting("log_output") in [1, 3]:
            self.main_window.main_tab.write(message)

        # NEW WINDOW / BOTH
        if get_setting("log_output") in [2, 3]:
            if self.debug_window and self.debug_window.isVisible():
                self.debug_window.write(message)
            else:
                self.debug_window = DebugWindow()
                self.debug_window.show()
                self.debug_window.write(message)
Beispiel #19
0
def validate_email(property, value):
    value = value if value else None
    if value is None:
        return value
    elif value[0] == u'\ufffd':
        return value[1:].lower()
    elif not re.match(get_setting('EMAIL_REGEXP'), value):
        raise BadValueError
    return value.lower()
 def run_update_check(self):
     last_check = datetime.strptime(get_setting("last_update_check"), get_setting("timestamp_format"))
     next_check = last_check + timedelta(hours=1)
     if next_check > datetime.now():
         self.update_label(self.get_version_update_str())
         return
     try:
         import requests
         from requests import RequestException
         # check for new version
         git_request = requests.get("https://api.github.com/repos/circleguard/circleguard/releases/latest").json()
         git_version = version.parse(git_request["name"])
         set_setting("latest_version", git_version)
         set_setting("last_update_check", datetime.now().strftime(get_setting("timestamp_format")))
     except RequestException:
         # user is probably offline
         pass
     self.update_label(self.get_version_update_str())
def start_ui(live_capture=False):
    if live_capture:
        # start up background thread to periodically update ui state.
        ui_state_thread = threading.Thread(target=updater)
        ui_state_thread.start()
    else:
        update_ui_state()

    app.run_server(debug=get_setting('app', 'EnableDebugMode'))
Beispiel #22
0
def login(user='******', silent=False):
    url = settings.get_setting('BASE_URL') \
    + settings.get_setting('LOGIN_URL')
    try:
        data = json.dumps({
            "name": settings.get_setting(user),
            "password": settings.get_setting('BDS_PASSWORD')
        })
        resp = requestOp(op="post", url=url, data=data)
        if resp is None:
            return ''
        if resp.status_code == 201:
            if not silent:
                print "Logged in Session ID: %s" % (resp.headers["location"])
            return resp.headers['location']
        else:
            return ''
    except:
        return ''
Beispiel #23
0
 def _upload(self, file_path, metadata):
     if self.uploader is None:
         self.uploader = YouTubeUploader(get_setting('username'))
     if self.uploader.username == "":
         raise Exception("No user selected to upload to")
     thread = UploadThread(self.uploader, file_path, metadata, self.on_done_uploading)
     self.threads.append(thread)
     if not self.uploading:
         self.uploading = True
         thread.start()
def _init_p0f(flag, value):
    """
    Helper function for the init methods: performs most
    of the work for setting up background process and
    API socket database hook.
    """
    global p0f_db, background_proc
    if p0f_db:
        raise RuntimeError("Attempted to double initialize p0f proxy.")

    database_path = get_setting('p0f', 'DatabaseFilePath')
    socket_path = get_setting('p0f', 'APISocketFilePath')

    sys.stdout.flush()
    background_proc = subprocess.Popen(
        ["p0f", "-f", database_path, "-s", socket_path, flag, value],
        stdout=open(os.devnull, 'w'),
        stderr=subprocess.STDOUT,
        close_fds=True)
    p0f_db = P0f(socket_path)
Beispiel #25
0
 def __init__(self, input=None, sequences=None, only_tree=False, *args, **kwargs):
     super(Alignment, self).__init__(*args, **kwargs)
     from settings import get_setting
     if sequences is not None:
         input = create_tmp()
         inout.FileOutput(input).write(sequences)
     if input is None:
         self.input = get_setting('INPUT_FILE')
     else:
         self.input = input
     self.only_tree = only_tree
    def url_scheme_called(self, url):
        from circleguard import ReplayMap, Circleguard, Mod
        # url is bytes, so decode back to str
        url = url.decode()
        # windows appends an extra slash even if the original url didn't have
        # it, so remove it
        url = url.strip("/")
        # all urls can have any of the following parameters:
        # * m - the map id
        # * u - the first user's id
        # * u2 - the second user's id
        # * t - the timestamp to start at
        # * m1 - the mods the first replay was played with
        # * m2 - the mods the second replay was played with
        # For example, a url might look like
        # circleguard://m=221777&u=2757689&m1=HDHRu2=3219026&m2=HDHR
        map_id = int(re.compile(r"m=(.*?)(&|$)").search(url).group(1))
        user_id = int(re.compile(r"u=(.*?)(&|$)").search(url).group(1))
        timestamp_match = re.compile(r"t=(.*?)(&|$)").search(url)
        # start at the beginning if timestamp isn't specified
        timestamp = int(timestamp_match.group(1)) if timestamp_match else 0

        # mods is optional, will take the user's highest play on the map if not
        # specified
        mods1_match = re.compile(r"m1=(.*?)(&|$)").search(url)
        mods1 = None
        if mods1_match:
            mods1 = mods1_match.group(1)

        user_id_2_match = re.compile(r"u2=(.*?)(&|$)").search(url)
        user_id_2 = None
        if user_id_2_match:
            user_id_2 = int(user_id_2_match.group(1))

        mods2_match = re.compile(r"m2=(.*?)(&|$)").search(url)
        mods2 = None
        if mods2_match:
            mods2 = mods2_match.group(1)

        # convert the string into an actual mods object if we received it
        mods1 = Mod(mods1) if mods1 else None
        r = ReplayMap(map_id, user_id, mods1)
        cg = Circleguard(get_setting("api_key"))
        cg.load(r)
        replays = [r]

        if user_id_2:
            mods2 = Mod(mods2) if mods2 else None
            r2 = ReplayMap(map_id, user_id_2, mods2)
            cg.load(r2)
            replays.append(r2)
        # open visualizer for the given map and user, and jump to the timestamp
        result = URLAnalysisResult(replays, timestamp)
        self.cg_classic.main_tab.url_analysis_q.put(result)
def start_oauth2_dance():
    login_hint = ""
    scope = ""
    client = Client.get_by_id(1)
    if not client:
        # If client does not exist then create an empty one
        client = Client(id=1)
        client.put()
    # Get the login hint from configuration

    # approval_prompt = 'auto' if client.reseller_refresh_token else 'force'
    # Always force to be sure to get valid refresh token
    approval_prompt = "force"
    login_hint = get_setting("OAUTH2_RESELLER_DOMAIN_USER")
    scope = get_setting("OAUTH2_SCOPE")
    redirect_uri = helpers.url_for("oauth_callback", _external=True)
    oauth_helper = OAuthDanceHelper(scope=scope, redirect_uri=redirect_uri, approval_prompt=approval_prompt)
    url = oauth_helper.step1_get_authorize_url()
    # TODO: Add a random token to avoid forgery
    return redirect("%s&login_hint=%s" % (url, login_hint))
Beispiel #28
0
def make_django_green(monkey_patch_done=False):
    if not monkey_patch_done:
        # Make python sockets green
        from gevent import monkey
        monkey.patch_all()
    
    # Make other stuff green
    for setting in get_setting('DJANGO_GEVENT_MAKE_GREEN'):
        module_name = '.'.join(setting.split('.')[:-1])
        function_name = setting.split('.')[-1]
        make_green_function = getattr(import_module(module_name), function_name)
        make_green_function()
Beispiel #29
0
def main(argv):
    if len(argv) < 1 or len(argv) > 2:
        usage()
        sys.exit(2)
    dataconn_path = argv[0]
    obj_id = dataconn_path[len(settings.get_setting('DATACONN_URL')):]
    rem_obj = "/" in obj_id
    if len(argv) == 2:
        if rem_obj:
            usage()
            sys.exit(2)
        query = '?query=' + argv[1]
    else:
        if rem_obj:
            query = ''
        else:
            query = '?query='
    session_id = session.login()
    print
    url = settings.get_setting('BASE_URL') + dataconn_path + query
    response = requests.get(url, headers=session.get_session_hdr(session_id))
    if response.status_code == 404:
        print "object not found"
    else:
        if rem_obj:
            print_objinfo([response.json()])
        else:
            query_results = response.json()["_embedded"]["query_results"]
            if "matching_objects" in query_results:
                print_objinfo(query_results["matching_objects"])
            else:
                print "errors:"
                for error in query_results["access_errors"]:
                    print "  %s" % (error)
    if json_debug:
        print "debug:"
        print "  %s" % (response.json())
    session.logout(session_id)
Beispiel #30
0
def search(bot, update, args, lang, songs=False, artists=False, albums=False, state=None):
    query = args if type(args) == str else ' '.join(args)
    if songs and artists and albums:
        entries = voca_db.entries(query, lang)
    elif songs:
        originals_only = get_setting('originals', bot, update)
        entries = voca_db.songs(query, lang, originals_only=originals_only)
    elif artists:
        entries = voca_db.artists(query, lang)
    elif albums:
        entries = voca_db.albums(query, lang)
    else:
        return None, None
    return entries, state
 def visualize(self, replays, beatmap_id, result):
     # only run one instance at a time
     if self.visualizer is not None:
         self.visualizer.close()
     snaps = []
     if isinstance(result, CorrectionResult):
         snaps = [snap.time for snap in result.snaps]
     beatmap_info = BeatmapInfo(map_id=beatmap_id)
     if not get_setting("render_beatmap"):
         # don't give the visualizer any beatmap info if the user doesn't
         # want it rendered
         beatmap_info = BeatmapInfo()
     self.visualizer = CGVisualizer(beatmap_info, replays, snaps, self.library)
     self.visualizer.show()
Beispiel #32
0
    def __init__(self):
        super().__init__()
        self._cg = None
        self.visualizer = None
        self.old_api_key = get_setting("api_key")
        self.loadables_q = Queue()
        # this thread continually checks for new loadables to load
        self.cg_load_thread = threading.Thread(target=self._load_loadables)
        # we never kill this thread, so allow the application to quit while it's
        # still alive
        self.cg_load_thread.daemon = True
        self.cg_load_thread.start()
        self.loadable_loaded = threading.Event()
        self.show_visualizer_window.connect(self.show_visualizer)
        self.show_exception_signal.connect(self.show_exception)

        expanding = QSizePolicy()
        expanding.setHorizontalPolicy(QSizePolicy.Expanding)
        expanding.setVerticalPolicy(QSizePolicy.Expanding)

        self.drop_area = ReplayDropArea()
        self.drop_area.setSizePolicy(expanding)
        da_scroll_area = QScrollArea(self)
        da_scroll_area.setWidget(self.drop_area)
        da_scroll_area.setWidgetResizable(True)
        da_scroll_area.setFrameShape(QFrame.NoFrame)

        self.replay_map_creation = ReplayMapCreation()
        self.replay_map_creation.setSizePolicy(expanding)
        rmc_scroll_area = QScrollArea(self)
        rmc_scroll_area.setWidget(self.replay_map_creation)
        rmc_scroll_area.setWidgetResizable(True)
        rmc_scroll_area.setFrameShape(QFrame.NoFrame)

        visualize_button = PushButton("Visualize")
        visualize_button.setObjectName("bigButton")
        visualize_button.clicked.connect(self.visualize)
        font = visualize_button.font()
        font.setPointSize(30)
        visualize_button.setFont(font)
        expanding = QSizePolicy()
        expanding.setHorizontalPolicy(QSizePolicy.Expanding)
        expanding.setVerticalPolicy(QSizePolicy.Expanding)
        visualize_button.setSizePolicy(expanding)

        layout = QGridLayout()
        layout.addWidget(da_scroll_area, 0, 0, 6, 1)
        layout.addWidget(rmc_scroll_area, 0, 1, 6, 1)
        layout.addWidget(visualize_button, 6, 0, 2, 2)
        self.setLayout(layout)
 def set_camera(self, camera):
     self.camera = camera
     self.camera.PixelFormat = "BGR8"
     self.input_res = settings.get_setting(
         "input_resolution",
         [self.camera.Width.Value, self.camera.Height.Value])
     self.output_res = settings.get_setting(
         "output_resolution",
         [self.camera.Width.Value, self.camera.Height.Value])
     self.fps = settings.get_setting("fps", 30)
     self.camera.Width = self.input_res[0]
     self.camera.Height = self.input_res[1]
     self.camera.AcquisitionFrameRate = self.fps
     self.camera.AcquisitionFrameRateEnable = True
     self.camera.AutoExposureTimeUpperLimit = settings.get_setting(
         "max_exposure_time", 15000)
     self.virt_cam = pyvirtualcam.Camera(width=self.output_res[0],
                                         height=self.output_res[1],
                                         fps=self.fps,
                                         print_fps=False,
                                         fmt=pyvirtualcam.PixelFormat.BGR)
     self.frame = np.full(
         (self.camera.Height.Value, self.camera.Width.Value, 3), 255,
         np.uint8)
Beispiel #34
0
def init_module():
    """
    Initializes the geoip database reader.
    """
    global geoip_db_reader
    if geoip_db_reader:
        raise RuntimeError("Attempted to double initialize geoip module")

    database_path = get_setting('geoip', 'DatabaseFilePath')
    geoip_db_reader = geoip2.database.Reader(database_path)

    # Ensure the reader is properly initialized
    try:
        geoip_db_reader.country('127.0.0.1')
    except geoip2.errors.AddressNotFoundError:
        pass
    def log(self, message):
        """
        Message is the string message sent to the io stream
        """

        log_output = get_setting("_log_output")
        if log_output in ["terminal", "both"]:
            self.cg_classic.main_tab.write(message)

        if log_output in ["new_window", "both"]:
            if self.debug_window and self.debug_window.isVisible():
                self.debug_window.write(message)
            else:
                self.debug_window = DebugWindow()
                self.debug_window.show()
                self.debug_window.write(message)
Beispiel #36
0
    def render(self, screen):
        width, height = pygame.display.get_surface().get_size()
        if not self.is_paused and (not self.has_crashed or
                                   (self.has_crashed
                                    and not self.event_painted)):
            # Draw background
            if not settings.get_setting("classic"):
                screen.blit(self.background, (0, 0))
            else:
                # Classic look
                screen.fill(BGCOLOR)

            # Draw snake, apple, grid
            self.sneik.draw(screen)
            self.apple.draw(screen)
            if self.show_grid:
                self.draw_grid(screen)

            if self.has_crashed:
                self.event_painted = True

        elif self.has_crashed:
            # Add snake blood
            self.sneik.draw_blood(screen)

        # Paint pause screen once
        elif not self.event_painted:
            # Darken the screen
            surf = get_surface((width, height), BLACK, 160)
            screen.blit(surf, (0, 0))

            # Show pause message
            font = resources.get_font("title100")
            text_surf, text_rect = render_text("Paused", font, WHITE)
            text_rect.center = width // 2, 250
            screen.blit(text_surf, text_rect)

            font = resources.get_font("round30")
            text_surf, text_rect = render_text(
                f"Score: {len(self.sneik.body) - 2}", font, WHITE)
            text_rect.center = width // 2, 330
            screen.blit(text_surf, text_rect)
            self.event_painted = True
Beispiel #37
0
 def run(self):
     try:
         self.uploader = YouTubeUploader(
             self.username,
             self.jobs,
             get_setting("headlessBrowser") ==
             SETTINGS_VALUES.CheckBox.CHECKED,
         )
         self.uploader.upload_finished.connect(
             lambda file_path, success: self.upload_finished.emit(
                 file_path, success))
         self.uploader.log_message.connect(
             lambda message, level: self.log_message.emit(message, level))
         self.uploader.on_progress.connect(
             lambda job_name, progress: self.on_progress.emit(
                 job_name, progress))
         self.uploader.upload_all()
     except Exception:
         self.log_message.emit(traceback.format_exc(), logging.ERROR)
     finally:
         self.finished.emit()
Beispiel #38
0
def create_token(login, login_type):
    if login_type == "jid":
        login = resolve_alias(login)

    tmp = tempfile.mktemp(suffix="", prefix="", dir="")
    token = Token(token=tmp, login=login, login_type=login_type, active=1)
    token.put(force_insert=True)

    base_url = get_setting("web_api_root", "http://localhost:8080").rstrip("/")
    url = "%s/api/auth?token=%s" % (base_url, tmp)
    message = "A third-party application is requesting access to your account. If that was you, follow this link:\n%s\n" % url

    if login_type == "jid":
        msg = Message(re=login, message=message)
        msg.put()
    else:
        run(["mail", "-s", "Your token", login], stdin_data=message)

    commit()

    return url
Beispiel #39
0
def search(bot,
           update,
           args,
           lang,
           songs=False,
           artists=False,
           albums=False,
           state=None):
    query = args if type(args) == str else ' '.join(args)
    if songs and artists and albums:
        entries = voca_db.entries(query, lang)
    elif songs:
        originals_only = get_setting('originals', bot, update)
        entries = voca_db.songs(query, lang, originals_only=originals_only)
    elif artists:
        entries = voca_db.artists(query, lang)
    elif albums:
        entries = voca_db.albums(query, lang)
    else:
        return None, None
    return entries, state
Beispiel #40
0
def become_site_admin(session_id, session_header):
    site_admin_role_url = None
    url = settings.get_setting('BASE_URL') \
    + settings.get_setting('ROLE_URL')
    response = requestOp(op="get", url=url, headers=session_header)
    if response is None:
        print "Failed to perform requests.get"
        sys.exit(2)
    role_list = response.json()["_embedded"]["roles"]
    for role in role_list:
        if role["label"]["name"] == settings.get_setting(
                'BDS_SITE_ADMIN_ROLE'):
            site_admin_role_url = role["_links"]["self"]["href"]
    if site_admin_role_url is None:
        print "site admin role not found!"
        sys.exit(2)
    admin_tenant_url = None
    url = settings.get_setting('BASE_URL') \
    + settings.get_setting('TENANT_URL')
    response = requestOp(op="get", url=url, headers=session_header)
    if response is None:
        print "Failed to perform requests.get"
        sys.exit(2)
    tenant_list = response.json()["_embedded"]["tenants"]
    for tenant in tenant_list:
        if tenant["label"]["name"] == settings.get_setting('BDS_ADMIN_TENANT'):
            admin_tenant_url = tenant["_links"]["self"]["href"]
    if admin_tenant_url is None:
        print "admin tenant not found!"
        sys.exit(2)
    url = settings.get_setting('BASE_URL') + session_id + '?tenant'
    role_data = {"role": site_admin_role_url, "tenant": admin_tenant_url}
    role_spec = json.dumps(role_data)
    response = requestOp(op="put",
                         url=url,
                         data=role_spec,
                         headers=session_header)
    if response is None:
        print "Failed to perform requests.put"
        sys.exit(2)
    if response.status_code != 204:
        print "taking site admin role failed!"
        sys.exit(2)
Beispiel #41
0
 def __init__(self, config_file=None):
     settings.init(config_file)
     self.host = settings.get_setting('ftp').get('host')
     self.username = settings.get_setting('ftp').get('username')
     self.password = settings.get_setting('ftp').get('password')
     self.connection = None
Beispiel #42
0
def song_search(bot, update, groups, lang):
    switch_pm = (_('Searching only songs'), 'help_inline')
    originals_only = get_setting('originals', bot, update)
    return voca_db.songs(groups[0], lang, max_results=MAX_INLINE_RESULTS, originals_only=originals_only), switch_pm
Beispiel #43
0
 def getDirname(self):
     assert self.type == "po"
     # @TODO unix folder limits
     return os.path.join(get_setting("STORE_PATH"), str(self.id))