Esempio n. 1
0
    def test_easysettings(self):
        """ easysettings is available """
        try:
            # Configuration lib.
            from easysettings import EasySettings  # noqa
        except ImportError as ex:
            errmsg = import_failmsg('easysettings',
                                    subpkgs=['EasySettings'],
                                    exc=ex)
            self.fail(errmsg)
        else:
            # easysettings installed, check version.
            if hasattr(EasySettings, '__version__'):
                curver = getattr(EasySettings, '__version__')
            elif hasattr(EasySettings, 'es_version'):
                es = EasySettings()
                curver = getattr(es, 'es_version')()
            else:
                self.fail('Unable to determine EasySettings version!')

            reqver = VERSIONS['easysettings']
            if check_versions(curver, reqver) < 0:

                errmsg = import_failmsg('easysettings',
                                        subpkgs=['EasySettings'],
                                        curver=curver)
                self.fail(errmsg)
def main(call_api):
    try:
        # start logging
        logging.basicConfig(filename='SprinklrClient.log',
                            level=logging.NOTSET)
        logging.debug("Starting " + sys.argv[0] + " with " +
                      str(len(sys.argv) - 1) + " actual parameters")

        #load settings
        settings = EasySettings("Sprinklr.conf")
        key = settings.get('key')
        path = settings.get('path')
        access_token = settings.get('access_token')

        if len(path) == 0:
            path = None

        # If using a differnent enviornment other that Prod, set path to that value (like 'prod2')
        client = sc.SprinklrClient(key=key,
                                   access_token=access_token,
                                   path=path)

        # make API Call - use process_response (defined in resultprocessor) to display results
        call_api(client)

    except Exception as ex:
        print("Error:" + str(ex))
Esempio n. 3
0
 def check_for_mouseclick(self):
     self.config = EasySettings('config.conf')
     self.key_click_delay = self.config.get("key_click_delay")
     self.single_click_delay = self.config.get("single_click_delay")
     state_left = win32api.GetKeyState(
         0x01)  # Left button down = 0 or 1. Button up = -127 or -128
     print(state_left)
     if state_left != self.old_state_left:
         self.old_state_left = state_left
         time.sleep(self.single_click_delay
                    )  # delay to avoid double click on single click
         state_left = -1  # empty value to avoid unintentional click
     if state_left == -128 or state_left == -127:
         # print(shoot_shortcut_key_for_Simulator)
         try:
             keyboardSimulator.press(shoot_shortcut_key_for_Simulator)
             time.sleep(self.key_click_delay)
             keyboardSimulator.release(shoot_shortcut_key_for_Simulator)
             time.sleep(self.key_click_delay)
         except Exception as e:
             updateMessageBox("Key Not Supported!")
             print("Key Not Supported " + " ERROR --------->" + str(e))
def main():
    print("Number of args:", len(sys.argv))
    if len(sys.argv) > 6 or len(sys.argv) < 5:
        print(
            "Usage: FetchAccessToken {apikey} {secret} {code} {redirect URI} [path]"
        )
    else:
        path = None
        key = sys.argv[1]
        secret = sys.argv[2]
        code = sys.argv[3]
        redirect = sys.argv[4]

        if len(sys.argv) == 6:
            path = sys.argv[5]

        settings = EasySettings("Sprinklr.conf")
        client = sc.SprinklrClient(key, path)

        success = client.fetch_access_token(secret=secret,
                                            code=code,
                                            redirect_uri=redirect)

        if success:
            settings.set('access_token', client.access_token)
            settings.set('refresh_token', client.refresh_token)
            settings.set('redirect_uri', redirect)
            settings.set('key', key)
            settings.set('secret', secret)
            settings.set('path', path),
            settings.save()
            print(
                "Successfully retrieved and stored access tokens to Sprinklr.conf"
            )
        else:
            print("Access Token NOT retrieved or stored. API call result:")
            print(client.result)
Esempio n. 5
0
from natsort import os_sorted
from pathlib2 import Path

# MPV
os.environ["PATH"] = os.path.dirname(
    __file__) + os.pathsep + os.environ["PATH"]
import mpv

directory = ""
currentFile = ""
cwd = ""
previousFile = ""
previousDirectory = ""
myappid = u'hotornot'  # arbitrary string
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)
settings = EasySettings("hotornot.conf")
m = magic.Magic()


def resource_path(relative_path):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath('.'), relative_path)


class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        global previousFile
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1600, 900)
        MainWindow.setMinimumSize(QtCore.QSize(1600, 900))
Esempio n. 6
0
import locale
from easysettings import EasySettings

settings = EasySettings("../resources/settings.conf")
if not settings.has_option('Language'):
    if locale.getdefaultlocale() == "fa_IR":
        settings.set("Language", "Persian")
    else:
        settings.set("Language", "English")
    settings.save()
if settings.get('Language') == 'Persian':
    nameOfProgram = "Movie Sorter"
    chooseFileName = "انتخاب فایل"
    quitText = 'خروج'
    startText = 'شروع دسته بندی'
    folderForEpisodes = 'فولدر سازی برای قسمت ها'
    putYearInBrackets = 'قرار دادن سال ساخت داخل پرانتز'
    moviesText = 'فیلم ها'
    seriesText = 'سریال ها'
    unfolderString = 'درووردن فایل ها از فولدر ها'
    infoText = 'درباره ما'
    nameFormat = ':فرمت اسم فایل'
    settingsText = ':تنظیمات'
    formatsText = ':فرمت ها'
    getAncher = 'e'
    first = 'right'
    last = 'left'
    chooseDirText = 'انتخاب فولدر مورد نظر'
    completeMessage = "دسته بندی انجام شد"
    nameChange = "هم اسم کردن فیلم و زیرنویس"
    changeLanguage = "English"
Esempio n. 7
0
#create the app
app = Flask('flamo')
app.config['SECRET_KEY'] = os.environ.get('FLAMO_SECRET_KEY', 'flamo')
proxied = FlaskReverseProxied(app)

#login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'

#socket io server
socketio = SocketIO(app)

#settings
settings = EasySettings('flamo.conf')
'''
Implementation
'''


class FlashForgeIO(Thread):
    _instance = None

    def __init__(self, reconnect_timeout=5, vendorid=0x2b71, deviceid=0x0001):
        Thread.__init__(self)
        self.queue = Queue()

    def run(self):
        app.logger.info('[FlashforgeIO] started')
        ff = FlashForge()
Esempio n. 8
0
if (sys.version_info.major < 3) and (sys.version_info.minor < 5):
    print('CEdit is designed to run on Python 3.5+ only.', file=sys.stderr)
    sys.exit(1)

NAME = 'CEdit'
__version__ = '3.1.2'
VERSIONSTR = '{} v. {}'.format(NAME, __version__)
SCRIPT = os.path.split(os.path.abspath(sys.argv[0]))[1]
SCRIPTDIR = os.path.abspath(sys.path[0])
OPTIONS = {
    'editor': 'editor to open files.',
    'elevcmd': 'elevation command for when root is needed.',
    'rooteditor': 'editor to use when elevation command is used.',
}
CONFIGFILE = os.path.join(SCRIPTDIR, 'cedit.conf')
settings = EasySettings(CONFIGFILE)
settings.name = NAME
settings.version = __version__

USAGESTR = """{ver}

    Opens files with your favorite editor,
    and uses an elevation command automatically when needed for
    write access.

    Usage:
        {script} -h | -l | -v
        {script} -s option...
        {script} PATH... [-- EDITOR_ARGS...]

    Options:
Esempio n. 9
0
from twisted.internet import defer, endpoints, protocol, reactor, task
from twisted.python import failure, log  # noqa
from twisted.words.protocols import irc

# Local stuff (Command Handler)
from pyval_commands import AdminHandler, CommandHandler
from pyval_util import NAME, VERSION, VERSIONSTR

SCRIPT = os.path.split(sys.argv[0])[1]

BANFILE = '{}_banned.lst'.format(NAME.lower().replace(' ', '-'))
DEFAULT_CONFIGFILE = '{}.conf'.format(NAME.lower().replace(' ', '_'))
DEFAULT_CONFIGFILE = os.path.join(sys.path[0], DEFAULT_CONFIGFILE)
# Config file is loaded after checking args in main().
# Alternate config may be used...
CONFIG = EasySettings()
CONFIG.name = NAME
CONFIG.version = VERSION
USAGESTR = """{versionstr}

    Usage:
        {script} -h | -v
        {script} [options]

    Options:
        -a,--autosave              : Automatically save new command-line
                                     options to config file.
                                     (passwords are stored in plain text!)
        -b,--noheartbeat           : Don't log the heartbeat pongs.
        -c chans,--channels chans  : Comma-separated list of channels to join.
        -C chr,--commandchar chr   : Character that marks a msg as a command.
Esempio n. 10
0
 def __init__(self, server, user, token):
     self.matrix_server = server
     self.matrix_user = user
     self.access_token = token
     self.quit = False
     self.settings = EasySettings("matrixtool.conf")
Esempio n. 11
0
def main():
    global settings
    global client

    try:
        logging.basicConfig(filename='SprinklrClient.log', level=logging.DEBUG)
        logging.debug("Starting SprinklrClientTest with " +
                      str(len(sys.argv) - 1) + " actual parameters")

        settings = EasySettings("Sprinklr.conf")
        key = settings.get('key')
        path = settings.get('path')
        access_token = settings.get('access_token')

        if len(path) == 0:
            path = None

        # If using a differnent enviornment other that Prod, set path to that value (like 'prod2')
        client = sc.SprinklrClient(key=key,
                                   access_token=access_token,
                                   path=path)

        if len(sys.argv) > 1:
            command = str(sys.argv[1]).upper()

            if command == 'ADDCOMMENTTOCASE':
                add_comment_to_case(sys.argv[2], sys.argv[3])
            elif command == 'AUTHORIZE':
                if len(sys.argv) > 5:
                    print(
                        "Invalid command line - Usage: SprinklrClientTest Authorize {apikey} {redirect_uri} [environment]"
                    )
                else:
                    key = sys.argv[2]
                    redirect_uri = sys.argv[3]
                    if len(sys.argv) == 5:
                        path = sys.argv[4]
                    else:
                        path = None
                    client = sc.SprinklrClient(key)
                    authorize(key, redirect_uri, path)
            elif command == "CUSTOMFIELDADDOPTION":
                custom_field_add_option(sys.argv[2], sys.argv[3])
            elif command == "CUSTOMFIELDDELETEOPTION":
                custom_field_delete_option(sys.argv[2], sys.argv[3])
            elif command == 'FETCHALLDASHBOARDS':
                fetch_all_dashboards()
            elif command == 'FETCHACCESSTOKEN':
                if len(sys.argv) != 6:
                    print(
                        "Invalid command line - Usage: SprinklrClientTest GetAccessToken {path} {apikey} {secret} "
                        "{code} {redirect URI}")
                else:
                    path = sys.argv[2]
                    key = sys.argv[3]
                    secret = sys.argv[4]
                    code = sys.argv[5]
                    redirect = sys.argv[6]

                    client = sc.SprinklrClient(key, path)
                    success = client.fetch_access_token(secret=secret,
                                                        code=code,
                                                        redirect_uri=redirect)

                    if success:
                        settings.set('access_token', client.access_token)
                        settings.set('refresh_token', client.refresh_token)
                        settings.set('redirect_uri', redirect)
                        settings.set('key', key)
                        settings.set('secret', secret)
                        settings.set('path', path),
                        settings.save()
                        print("Success")
                    else:
                        print(client.result)

                    key = settings.get('key')
                    access_token = settings.get('access_token')
                    client = sc.SprinklrClient(key=key,
                                               access_token=access_token)
            elif command == 'FETCHACCESSIBLEUSERS':
                fetch_accessible_users()
            elif command == 'FETCHACCOUNT':
                fetch_account(sys.argv[2], sys.argv[3])
            elif command == 'FETCHACCOUNTCUSTOMFIELDS':
                fetch_account_custom_fields()
            elif command == 'FETCHARCHIVEDCASES':
                fetch_archived_cases()
            elif command == "FETCHCASEBYNUMBER":
                fetch_case_by_number(sys.argv[2])
            elif command == "FETCHCASECOMMENT":
                fetch_case_comment(sys.argv[2], sys.argv[3])
            elif command == "FETCHCASECOMMENTS":
                fetch_case_comments(sys.argv[2])
            elif command == "FETCHCASEMESSAGESBYID":
                fetch_case_messages(sys.argv[2])
            elif command == "FETCHCLIENTS":
                fetch_clients()
            elif command == 'FETCHCLIENTPROFILELISTS':
                fetch_client_profile_lists()
            elif command == "FETCHCLIENTURLSHORTNERS":
                fetch_client_url_shortners()
            elif command == 'FETCHCLIENTQUEUES':
                fetch_client_queues()
            elif command == 'FETCHCLIENTUSERS':
                fetch_client_users()
            elif command == 'FETCHDASHBOARDBYNAME':
                if len(sys.argv) != 3:
                    print(
                        "Invalid command line - Usage: SprinklrClientTest GetDashboardByName {name}"
                    )
                else:
                    fetch_dashboard_by_name(sys.argv[2])
            elif command == 'FETCHDASHBOARDSTREAM':
                fetch_dashboard_stream(sys.argv[2], sys.argv[3], sys.argv[4])
            elif command == 'FETCHINBOUNDCUSTOMFIELDS':
                fetch_inbound_custom_fields()
            elif command == 'FETCHLISTENINGTOPICS':
                fetch_listening_topics()
            elif command == 'FETCHLISTENINGSTREAM':
                if len(sys.argv) == 5:
                    fetch_listening_stream(sys.argv[2], sys.argv[3],
                                           sys.argv[4])
                elif len(sys.argv) == 6:
                    fetch_listening_stream(sys.argv[2],
                                           sys.argv[3],
                                           sys.argv[4],
                                           echo_request=sys.argv[5])
            elif command == 'FETCHMACROS':
                fetch_macros()
            elif command == 'FETCHMEDIAASSETCUSTOMFIELDS':
                fetch_media_asset_custom_fields()
            elif command == 'FETCHMESSAGEBYUMID':
                fetch_message_by_umid(sys.argv[2])
            elif command == 'FETCHOUTBOUNDCUSTOMFIELDS':
                fetch_outbound_custom_fields()
            elif command == 'FETCHPARTNERACCOUNTGROUPS':
                fetch_partner_account_groups()
            elif command == 'FETCHPARTNERACCOUNTS':
                fetch_partner_accounts()
            elif command == 'FETCHPARTNERCAMPAIGNS':
                fetch_partner_campaigns()
            elif command == 'FETCHPARTNERQUEUES':
                fetch_partner_queues()
            elif command == 'FETCHPARTNERUSERS':
                fetch_partner_users()
            elif command == 'FETCHPERMISSIONS':
                fetch_permissions()
            elif command == 'FETCHPROFILECUSTOMFIELDS':
                fetch_profile_custom_fields()
            elif command == "FETCHREPORTBYFILE":
                fetch_report_by_file(sys.argv[2])
            elif command == 'FETCHRESOURCES':
                fetch_resources(sys.argv[2])
            elif command == 'FETCHUSER':
                fetch_user()
            elif command == 'FETCHUSERBYID':
                fetch_user_by_id(sys.argv[2])
            elif command == 'FETCHUMPRIORITIES':
                fetch_um_priorities()
            elif command == 'FETCHUMSTATUSES':
                fetch_um_statuses()
            elif command == "FETCHUSERGROUPS":
                fetch_user_groups()
            elif command == "FETCHWEBHOOKTYPES":
                fetch_webhook_types()
            elif command == "REFRESHACCESSTOKEN":
                key = settings.get('key')
                secret = settings.get('secret')
                redirect = settings.get('redirect_uri')
                refresh_access_token = settings.get('refresh_token')
                path = settings.get('path')

                client = sc.SprinklrClient(key)

                success = client.refresh_access_token(secret, redirect,
                                                      refresh_access_token)

                if success:
                    settings.set('access_token', client.access_token)
                    settings.set('refresh_token', client.refresh_token)
                    settings.set('redirect_uri', redirect)
                    settings.set('key', key)
                    settings.set('secret', secret)
                    settings.save()
                    print("Success")
                else:
                    print(client.result)
            elif command == "SENDEMAIL":
                send_email(sys.argv[2], sys.argv[3], sys.argv[4], sys.argv[5])
            else:
                print_usage()
        else:
            print_usage()
    except Exception as ex:
        print("Error:" + str(ex))
        print_usage()
Esempio n. 12
0
from easysettings import EasySettings

settings = EasySettings("config.conf")


def set_timeout(timeout=15):
    settings.setsave("timeout", timeout)


def set_blink_monitoring(is_enabled=False):
    settings.setsave("blink-monitoring", is_enabled)


def set_screen_rest_monitoring(is_enabled=True):
    settings.setsave("rest-monitoring", is_enabled)


def set_notification_enabled(is_enabled=True):
    settings.setsave("notification-enabled", is_enabled)


def set_smart_notification_enabled(is_enabled=True):
    settings.setsave("smart_notification-enabled", is_enabled)


def get_timeout():
    return settings.get("timeout")


def get_blink_monitoring():
    return settings.get("blink-monitoring")
Esempio n. 13
0
import tkinter as tk
from tkinter import *
from easysettings import EasySettings
import threading
import time

sem = threading.Semaphore()
settings = EasySettings("myconfigfile.conf")

####### GUI ##############
master = tk.Tk()
master.geometry("1200x400")
master.title("Tizen Network Image Updater")
tk.Label(master, text="Target IP Address", anchor="e",
         justify=tk.LEFT).grid(row=0)
tk.Label(master, text="Serial Port", anchor="e", justify=tk.LEFT).grid(row=1)
tk.Label(master, text="Image Url", anchor="e", justify=tk.LEFT).grid(row=2)

e1 = tk.Entry(master, width=20, justify=tk.LEFT)
e2 = tk.Entry(master, width=20, justify=tk.LEFT)
e3 = tk.Entry(master, width=100, justify=tk.LEFT)
progressText = tk.StringVar()
#####################################


def show_entry_fields():
    global sem
    print("First Name: %s\nLast Name: %s" % (e1.get(), e2.get()))
    settings.set('TARGET_IP', e1.get())
    settings.set('PORT', e2.get())
    settings.set('URL', e3.get())
Esempio n. 14
0
def set(name, object=None):
    global settings
    settings.set(name, object)
    settings.save()


def get(name):
    global settings
    global defaults
    s = settings.get(name)
    if s == '' and name in defaults:
        return defaults[name]
    return s


settings = EasySettings("settings.conf")

defaults = {'recents': [], 'update_branch': 'master'}


def checkDefaults():
    global settings
    global defaults
    for i in defaults:
        s = settings.get(i)
        if s == '':
            settings.set(i, defaults[i])

    settings.save()

Esempio n. 15
0
def get(name, values):
    """The showrunner, where all the magic happens

    This function (this whole module really) is designed to do one thing:
    abstract away all the noise and complexity of configuration management.
    Rather than handle user input and figuring out where and how to store that
    input and wrestling with file permission (or lack thereof), just let this
    module take care of it for you!

    When you run this function for the first time, here's what happens:
        - a config file is created in a folder named after your app,
          in ~/.config (linux XDG standard location for user-specific
          config files)
        - the user gets prompted to answer a set of questions defined by you
        - the answers to those questions are stored in the config file
        - If any of those questions are marked optional, the following happens:
            after the user is prompted to answer the question, they will be
            asked to save their response. If they answer yes, the value will be
            saved as normal. If they answer no, the value will not be saved,
            and they will be prompted to answer the question again the next
            time this function is called.
        - The user will be notified that a config file has been created for
          them, and reminded to set appropriate permissions for this file if it
          contains any sensitive info.
        - if we can't save the config file (due to permission errors or
          something else), we warn the user of the issue, and treat all values
          gathered as optional. The next time this function runs, the user will
          be prompted for those values again just as if this function had never
          been called before. This behaviour will continue until the problem
          preventing config file saving is resolved.
        - this function returns an object containing all the values that were
          gathered from the user

    Any time this function is called afterwards:
        - all the values specified are retrieved from the config file that was
          created the first time around.
        - any value marked as optional which wasn't saved last time will be
          prompted for again, and the user will once again be given the option
          to save it
        - this function returns an object containing all the values that were
          gathered from the user

    Args:
        name (str): The name of the application to store / retrieve config for
        values (Sequence[Dict[str, str]]):
            The values to get / set in our config file, in the form of:
            [
                {
                    value (str): The value to get / set
                    prompt (str):
                        If the value hasn't been set yet, and user input is
                        required, what question or prompt should be displayed
                        for the user to respond to?
                    optional (bool):
                        if True, prompt if user wants to save the value in
                        config file, or prompt for it every time (ie. passwords)
                    sensitive (bool):
                        if True, getpass will be used to record the answer to
                        this question (meaning that any text typed in as
                        response to this question will not be printed onto the
                        screen
                },
                ...
            ]

    Returns:
        Dict[str, str]: a dictionary of all the values that were gathered from
            either the user or the config file

    Raises:
        #TODO: flesh this out

    Examples:
        >>>values = [
        ...             {
        ...                 'value': 'url',
        ...                 'prompt': "Please enter the full URL of your "
        ...                     "phpIPAM installation including the API app_id "
        ...                     "\\nex. https://phpipam.mycompanyserver.com"
        ...                     "/api/app_id/ \\nURL> ",
        ...                 'optional': False,
        ...                 'sensitive': False
        ...             },
        ...             {
        ...                 'value': 'username',
        ...                 'prompt': "Please enter your phpIPAM username: "******"\\nUsername> ",
        ...                 'optional': True,
        ...                 'sensitive': False
        ...             },
        ...             {
        ...                 'value': 'password',
        ...                 'prompt': "Please enter your phpIPAM password: "******"\\nPassword> ",
        ...                 'optional': True,
        ...                 'sensitive': True
        ...             },
        ...         ]
        >>>get('phpipam', values)  # Called for the first time
        Please enter the full URL of your phpIPAM
        installation including the API app_id
        ex. https://phpipam.mycompanyserver.com/api/app_id/
        URL> >? https://my.domain.com/phpipam/api/my_app_id/
        Please enter your phpIPAM username:
        Username> >? mytestuser
        Would you like to save this for later use? (yes/no)> >? yes
        Warning: Password input may be echoed.
        Please enter your phpIPAM password:
        Password> >? mysupersecretpassword
        Would you like to save this for later use? (yes/no)> >? no
        {'password': '******', 'username': '******',
         'url': 'https://my.domain.com/phpipam/api/my_app_id/'}
        >>>get('phpipam', values)  # Called again
        {'password': '******', 'username': '******',
         'url': 'https://my.domain.com/phpipam/api/my_app_id/'}

    """
    settings_file = os.path.expanduser(SETTINGS_FILE_ROOT + name + '/config')
    if not os.path.exists(settings_file):
        os.makedirs(os.path.dirname(settings_file), mode=0o700)
    settings = EasySettings(settings_file)

    result = dict()

    for item in values:
        key_name = item['value']
        result[key_name] = settings.get(item['value'], default=None)
        if not result[key_name]:
            sensitive = item['sensitive']  # bool
            result[key_name] = get_user_input(item['prompt'], sensitive)
            if item['optional']:
                choice = get_user_input("Would you like to save this for later "
                                        "use? \n(yes/no)> ", sensitive=False)
                if choice[0] == 'y' or choice[0] == 'Y':
                    settings.setsave(key_name, result[key_name])
            else:
                settings.setsave(key_name, result[key_name])

    return result
Esempio n. 16
0
    def __init__(self, queue, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setWindowTitle(appname)
        self.shortcutName = appname
        self.appIcon = QtGui.QIcon(os.path.join(working_directory, 'icon.ico'))
        self.setWindowIcon(self.appIcon)
        self.setFixedSize(550, 300)
        self.center()
        self.queue = queue

        self.config = EasySettings('config.conf')

        self.layout = QVBoxLayout()
        self.layout.setContentsMargins(0, 0, 0, 0)

        self.titleLayout = QHBoxLayout()
        self.titleLayout.setContentsMargins(0, 0, 0, 0)

        self.title = QLabel(appname)
        self.title.setFixedSize(200, 20)
        self.title.setAlignment(QtCore.Qt.AlignCenter)
        self.title.setObjectName("windowTitle")

        self.btn_close = QPushButton("x")
        self.btn_close.clicked.connect(self.close_window)
        self.btn_close.setFixedSize(25, 20)
        self.btn_close.setObjectName("closeBtn")
        self.btn_close.setFocusPolicy(QtCore.Qt.NoFocus)
        self.btn_closeLay = QVBoxLayout()
        self.btn_closeLay.addWidget(self.btn_close)
        self.btn_closeLay.addStretch(1)

        self.btn_minimise = QPushButton("-")
        self.btn_minimise.clicked.connect(self.btn_minimise_clicked)
        self.btn_minimise.setFixedSize(25, 20)
        self.btn_minimise.setObjectName("minimiseBtn")
        self.btn_minimise.setFocusPolicy(QtCore.Qt.NoFocus)
        self.btn_minimiseLay = QVBoxLayout()
        self.btn_minimiseLay.addWidget(self.btn_minimise)
        self.btn_minimiseLay.addStretch(1)

        self.infoBtn = QPushButton('?')
        self.infoBtn.setObjectName('infoBtn')
        self.infoBtn.setFocusPolicy(QtCore.Qt.NoFocus)
        self.infoBtn.clicked.connect(self.openInfoWebpage)
        self.infoBtnLay = QVBoxLayout()
        self.infoBtnLay.addWidget(self.infoBtn)

        self.titleLayout.addLayout(self.btn_closeLay)
        self.titleLayout.addStretch(1)
        self.titleLayout.addWidget(self.title)
        self.titleLayout.addSpacing(-43)
        self.titleLayout.addLayout(self.infoBtnLay)
        self.titleLayout.addSpacing(43)
        self.titleLayout.addStretch(1)
        self.titleLayout.addLayout(self.btn_minimiseLay)

        # --------------------------------------------------------------------------------------------------------------
        global onoffLabel
        onoffLabel = QLabel("OFF")
        onoffLabel.setObjectName("onoffLabel")
        onoffLabel.setFixedWidth(65)
        onoffLabel.setAlignment(QtCore.Qt.AlignCenter)

        self.currentOnOffShortcutLabel = QLabel("On/Off Keyboard Shortcut")
        self.currentOnOffShortcutLabel.setObjectName("currentShortcutLabel")
        self.currentOnOffShortcutLabel.setFixedWidth(200)
        self.currentOnOffShortcutLabel.setToolTip(
            "Note: The shortcut does not support combinations!")
        self.currentOnOffShortcutLabel.setToolTipDuration(4000)

        global currentOnOffShortcutKeyLabel
        with open(
                os.path.join(working_directory, 'shortcutRegisters',
                             'OnOff_Shortcut_Key.txt'), 'r') as file:
            on_off_shortcut_key_name = file.readlines()[1]
        currentOnOffShortcutKeyLabel = QLabel(on_off_shortcut_key_name)
        currentOnOffShortcutKeyLabel.setObjectName("currentShortcutKeyLabel")
        currentOnOffShortcutKeyLabel.setAlignment(QtCore.Qt.AlignCenter)
        currentOnOffShortcutKeyLabel.setFixedWidth(140)

        global recordOnOffShortcut
        recordOnOffShortcut = QPushButton("Record New")
        recordOnOffShortcut.setObjectName("recordOnOffshortcutButton")
        recordOnOffShortcut.pressed.connect(self.disableBotWhileRecording)
        recordOnOffShortcut.released.connect(self.set_OnOff_shortcut_key)
        recordOnOffShortcut.setFixedSize(80, 26)
        recordOnOffShortcut.setStyleSheet(
            "QPushButton#recordOnOffshortcutButton{color: white; border: 1px solid grey;}QPushButton#recordOnOffshortcutButton:hover{border: 1px solid khaki;color: grey;}"
        )
        recordOnOffShortcut.setFocusPolicy(QtCore.Qt.NoFocus)

        self.onoffLay = QHBoxLayout()
        self.onoffLay.addSpacing(10)
        self.onoffLay.addWidget(onoffLabel)
        self.onoffLay.addSpacing(5)
        self.onoffLay.addWidget(self.currentOnOffShortcutLabel)
        self.onoffLay.addWidget(currentOnOffShortcutKeyLabel)
        self.onoffLay.addStretch(1)
        self.onoffLay.addWidget(recordOnOffShortcut)
        self.onoffLay.addSpacing(30)
        # --------------------------------------------------------------------------------------------------------------

        # --------------------------------------------------------------------------------------------------------------
        global onoffButton
        onoffButton = OnOffslideButton(self, 0)
        onoffButton.setObjectName("onoffSlideButton")

        self.currentShootShortcutLabel = QLabel("Game Shoot Keybind")
        self.currentShootShortcutLabel.setObjectName("currentShortcutLabel")
        self.currentShootShortcutLabel.setFixedWidth(200)
        self.currentShootShortcutLabel.setAlignment(QtCore.Qt.AlignCenter)

        global currentShootShortcutKeyLabel
        with open(
                os.path.join(working_directory, 'shortcutRegisters',
                             'Game_Shoot_Shortcut_Key.txt'), 'r') as file:
            shoot_shortcut_key_name = file.readlines()[1]
        currentShootShortcutKeyLabel = QLabel(shoot_shortcut_key_name)
        currentShootShortcutKeyLabel.setObjectName("currentShortcutKeyLabel")
        currentShootShortcutKeyLabel.setAlignment(QtCore.Qt.AlignCenter)
        currentShootShortcutKeyLabel.setFixedWidth(140)

        global recordShootShortcut
        recordShootShortcut = QPushButton("Record New")
        recordShootShortcut.setObjectName("recordShootshortcutButton")
        recordShootShortcut.pressed.connect(self.disableBotWhileRecording)
        recordShootShortcut.released.connect(self.set_Shoot_shortcut_key)
        recordShootShortcut.setFixedSize(80, 26)
        recordShootShortcut.setStyleSheet(
            "QPushButton#recordShootshortcutButton{color: white; border: 1px solid grey;}QPushButton#recordShootshortcutButton:hover{border: 1px solid khaki;color: grey;}"
        )
        recordShootShortcut.setFocusPolicy(QtCore.Qt.NoFocus)

        self.keybindLay = QHBoxLayout()
        self.keybindLay.addSpacing(10)
        self.keybindLay.addWidget(onoffButton)
        self.keybindLay.addSpacing(50)
        self.keybindLay.addWidget(self.currentShootShortcutLabel)
        self.keybindLay.addWidget(currentShootShortcutKeyLabel)
        self.keybindLay.addStretch(1)
        self.keybindLay.addWidget(recordShootShortcut)
        self.keybindLay.addSpacing(30)
        # --------------------------------------------------------------------------------------------------------------
        global messageBox
        messageBox = QLabel()
        messageBox.setObjectName('messageBoxLabel')
        self.messageBoxLay = QHBoxLayout()
        self.messageBoxLay.addSpacing(20)
        self.messageBoxLay.addWidget(messageBox)
        # --------------------------------------------------------------------------------------------------------------
        self.startOnStartupCheckBox = QCheckBox("Start On Boot")
        self.startOnStartupCheckBox.clicked.connect(self.setStartOnStartup)
        self.startOnStartupCheckBox.setObjectName("checkboxes")
        self.startOnStartupCheckBox.setChecked(self.config.get('startOnBoot'))
        self.startOnStartupCheckBox.setFocusPolicy(QtCore.Qt.NoFocus)

        self.startActiveCheckBox = QCheckBox("Start Active")
        self.startActiveCheckBox.clicked.connect(self.setStartActive)
        self.startActiveCheckBox.setObjectName("checkboxes")
        self.startActiveCheckBox.setChecked(self.config.get('startActive'))
        self.startActiveCheckBox.setFocusPolicy(QtCore.Qt.NoFocus)

        self.overlayCheckBox = QCheckBox("Show Overlay")
        self.overlayCheckBox.clicked.connect(self.setShowOverlay)
        self.overlayCheckBox.setObjectName("checkboxes")
        self.overlayCheckBox.setChecked(self.config.get('showOverlay'))
        self.overlayCheckBox.setFocusPolicy(QtCore.Qt.NoFocus)

        self.gamesOnlyCheckBox = QCheckBox("Active InGame Only")
        self.gamesOnlyCheckBox.clicked.connect(self.setGamesOnly)
        self.gamesOnlyCheckBox.setToolTip(
            "If checked, bot works only in games (when the mouse icon is hidden)."
        )
        self.gamesOnlyCheckBox.setToolTipDuration(4000)
        self.gamesOnlyCheckBox.setObjectName("checkboxes")
        self.gamesOnlyCheckBox.setChecked(self.config.get('gamesOnly'))
        self.gamesOnlyCheckBox.setFocusPolicy(QtCore.Qt.NoFocus)

        self.checkBoxLay = QHBoxLayout()

        self.checkBoxLay.addSpacing(10)
        self.checkBoxLay.addStretch(1)
        self.checkBoxLay.addWidget(self.overlayCheckBox)
        self.checkBoxLay.addSpacing(5)
        self.checkBoxLay.addWidget(self.startOnStartupCheckBox)
        self.checkBoxLay.addSpacing(5)
        self.checkBoxLay.addWidget(self.startActiveCheckBox)
        self.checkBoxLay.addSpacing(5)
        self.checkBoxLay.addWidget(self.gamesOnlyCheckBox)
        self.checkBoxLay.addStretch(1)
        self.checkBoxLay.addSpacing(10)
        # --------------------------------------------------------------------------------------------------------------

        self.layout.addLayout(self.titleLayout)
        self.layout.addSpacing(20)
        self.layout.addLayout(self.onoffLay)
        self.layout.addSpacing(5)
        self.layout.addLayout(self.keybindLay)
        self.layout.addSpacing(20)
        self.layout.addLayout(self.messageBoxLay)
        self.layout.addStretch(1)
        self.layout.addLayout(self.checkBoxLay)
        self.layout.addSpacing(10)

        self.setLayout(self.layout)
        self.oldPos = self.pos()

        menu = QMenu()
        menu.setStyleSheet(
            open(
                os.path.join(working_directory, 'systemTray',
                             'system_tray_menu_stylesheet.css')).read())

        showAction = menu.addAction("Show")
        showAction.triggered.connect(self.show_window)
        try:
            showAction.setIcon(
                QtGui.QIcon(
                    os.path.join(working_directory, 'systemTray',
                                 'tray_menu_show_app_icon.png')))
        except Exception as e:
            print("Error: " + e)

        exitAction = menu.addAction("Exit")
        exitAction.triggered.connect(self.close_window)
        try:
            exitAction.setIcon(
                QtGui.QIcon(
                    os.path.join(working_directory, 'systemTray',
                                 'tray_menu_exit_app_icon.png')))
        except Exception as e:
            print("Error:" + e)

        self.tray = QSystemTrayIcon()
        self.tray_icon = QtGui.QIcon(
            os.path.join(working_directory, 'systemTray', 'tray_icon.png'))
        self.tray.setIcon(self.tray_icon)
        self.tray.setToolTip(appname)
        self.tray.setVisible(1)
        self.tray.setContextMenu(menu)
        self.tray.activated.connect(
            self.system_tray_icon_clicked_or_doubleclicked)

        global overlayStatus
        overlayStatus = self.config.get("showOverlay")
        global work_on_games_with_hidden_mouse_only
        work_on_games_with_hidden_mouse_only = self.config.get('gamesOnly')
        if self.config.get("startActive"):
            onoffButton.click()
            if not onoffButton.isChecked():
                self.turnBotOn()
            else:
                self.turnBotOff()
Esempio n. 17
0
    def __init__(self):
        location = Path(os.getcwd()).parent
        filepath = path.join(location, "settings.conf")

        self._settings = EasySettings(filepath)
Esempio n. 18
0
    def __init__(self):
        filepath = file_utils.settings_path

        self._settings = EasySettings(filepath)
Esempio n. 19
0
from telethon import TelegramClient, events
#from telethon import sync
from telethon.tl.functions.channels import CreateChannelRequest, CheckUsernameRequest, UpdateUsernameRequest
from telethon.tl.functions.messages import ExportChatInviteRequest
from config import API_HASH, API_ID
from easysettings import EasySettings
import logging


logging.basicConfig(format='[%(levelname) 5s/%(asctime)s] %(name)s: %(message)s', level=logging.WARNING)
settings = EasySettings("configuration.conf")
config_channel = None
source_channel = None
recepients = settings.get("recepients")
wait_for_source_forward = False


if not recepients:
    recepients = []

async def init_config_channel():
    try:
        invite = settings.get("config_channel")
        config_channel = await client.get_entity(invite)
        if config_channel:
            return config_channel
    except:
        pass

    print("Config channel not found creating new one")
    channel = await client(CreateChannelRequest("config_channel", "Message retranslation control room", megagroup=False))
Esempio n. 20
0
import sys, os, subprocess
from pathlib import Path
from PIL import Image


def resource_path(relative_path):
    """used by pyinstaller to see the relative path"""
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath('.'), relative_path)


guifile = resource_path("./gui/main.ui")
logo = resource_path("./gui/logo.png")
userfold = str(pathlib.Path.home())
config = EasySettings(userfold + "/imageconverter.conf")
configGui = resource_path("./gui/config.ui")

try:
    saveLocation = config.get("saveLocation")
    saveAs = config.get("saveFormat")
    if saveLocation or saveAs == "":
        saveLocation = userfold + '/Pictures/'
        config.set("saveLocation", str(saveLocation))
        config.set("saveFormat", 'jpeg')
        config.save()
except FileNotFoundError:
    pass


class GUI(QMainWindow):
Esempio n. 21
0
CROP_HEADER = r'{}\img\crop_header.png'.format(abs_path)
EXTRACT_HEADER = r'{}\img\extract_header.png'.format(abs_path)
CONVERT_HEADER = r'{}\img\to_pdf_header.tif'.format(abs_path)

P_COLOR = "#1481CE"
S_COLOR = "#F67E6A"
STOP = False
CANVAS_W = 147
CANVAS_H = 200
FONT = "Calibre"
FONT_SM = ('Segoe UI', 9, 'normal')
FONT_MD = ("Calibre", 9, 'normal')

SIDBAR_BG = "#F2F2F2"

settings = EasySettings('config.conf')
DIR = settings.get('DIR')

if not DIR:
    #for direction left to right
    lang, _ = locale.getdefaultlocale()
    if lang.startswith('ar_'): DIR = 'rtl'
    else: DIR = 'ltr'

if DIR == 'rtl':
    START_DIR = 'right'
    END_DIR = 'left'
    NW = 'se'
    TK_E = 'nw'
    END_PADDING_10 = (10, 0)
    START_PADDING_24 = (12, 24)
Esempio n. 22
0
from docopt import docopt
from easysettings import EasySettings
if sys.version_info.major < 3:
    input = raw_input

NAME = 'CEdit'
__version__ = '2.0.1'
VERSIONSTR = '{} v. {}'.format(NAME, __version__)
SCRIPT = os.path.split(os.path.abspath(sys.argv[0]))[1]
SCRIPTDIR = os.path.abspath(sys.path[0])
OPTIONS = {
    'editor': 'editor to open files.',
    'elevcmd': 'elevation command for when root is needed.'
}
settings = EasySettings(os.path.join(SCRIPTDIR, 'cedit.conf'))

USAGESTR = """{ver}

    Opens files with your favorite editor,
    and uses an elevation command automatically when needed for
    write access.

    Usage:
        {script} -h | -l | -v
        {script} -s option...
        {script} FILENAME

    Options:
        FILENAME                : File name to open or create.
        -h,--help               : shows this message
Esempio n. 23
0
# 181028

import json
import os
import chronologicon.input
from easysettings import EasySettings
from chronologicon.strings import *

LOGS_FILENAME = 'logs.json'
STATS_FILENAME = 'stat.json'
PRESAVE_FILENAME = 'temp.json'

LOGS_DEFAULT = []

CUR_FILEPATH = os.path.dirname(__file__)
PREFS = EasySettings(os.path.join(CUR_FILEPATH, 'prefs.conf'))

# Logs version check
try:
    LOGS = ''
    with open(os.path.join(PREFS.get('SAVE_DIR'), LOGS_FILENAME),
              "r") as LOGS_FILE:
        LOGS = json.load(LOGS_FILE)

    if type(LOGS[0]['TIME_START']) is int:
        Message('initLogsOutdated')
        input.MigrateLogs()
except Exception as e:
    Message('initVersionCheckFailed', e)

Esempio n. 24
0
###
# A simple GUI for choosing a file to process with the process_log logic
###

import tkinter
from tkinter import filedialog
import os

from process_log import process_file

from easysettings import EasySettings

settings = EasySettings("process_log.conf")

top = tkinter.Tk()
top.title("Process a log file")
file_names = []


###
# Load a file and save the path for future use (to open the dialog in the same place next time)
###
def saveCallback():
    global file_names

    # use stored initial path if set
    if settings.has_option('initialdir') and settings.get(
            "initialdir") is not None:
        initialdir = settings.get("initialdir")
    else:
        initialdir = "/"