Ejemplo n.º 1
0
def sendmail(msgbody, subject=f"[{AppName}] Alert!", forced=False):
    ini = Config.getboolean('notification', 'email', fallback=True)
    if not forced and not ini:
        return

    smtp_server = "smtp.gmail.com"
    port = 587  # For starttls
    context = ssl.create_default_context()

    password = Config['email']['password']
    sender = Config['email']['sender']
    tolist = Config['email']['to']
    cclist = Config.get('email', 'cc', fallback="")

    with smtplib.SMTP(smtp_server, port) as server:
        server.ehlo()  # Can be omitted
        server.starttls(context=context)
        server.ehlo()  # Can be omitted
        server.login(sender, password)

        rcpt = cclist.split(",") + [tolist]
        msg = MIMEMultipart('alternative')
        msg['Subject'] = subject
        msg['To'] = tolist
        msg['Cc'] = cclist
        msg.attach(MIMEText(msgbody))
        server.sendmail(sender, rcpt, msg.as_string())
        server.quit()
Ejemplo n.º 2
0
 def bounce_ball(self, ball):
     if self.collide_widget(ball):
         #self.pong_sound.play()
         randomness = random() * 0.4 + 0.8
         speedup = Config.get('speedup') * randomness
         offset = Config.get('offset') * \
             Vector(0, ball.center_y-self.center_y)
         ball.velocity =  speedup * \
             Vector(-ball.velocity_x, ball.velocity_y) + offset
Ejemplo n.º 3
0
    def __init__(self, bot):
        self.bot = bot
        self.session = {}

        conf = Config("config.ini")

        trans_conf = conf.get("Translation")
        i18n.set("locale", trans_conf['default_locale'])
        i18n.set("file_type", "json")
        i18n.load_path.append(trans_conf['path'])
Ejemplo n.º 4
0
async def data_handler(request):
    # get data from request
    data = request.json
    if data is None:
        return json({"status": 403, "message": "expected json"})

    token = tokens.get(data.get('via_instance'), '')
    # the session might be saved in the database
    if not token:
        potential_session = await database.get_session(data.get('via_instance'))
        if potential_session:
            # it is, we save it in the cache and set the token to the retrieved values
            tokens[potential_session["name"]] = Config(potential_session["token"], potential_session["url"])
            token = tokens.get(data.get('via_instance'))
    # `not token` to avoid `'' == ''`
    if not token or not (data.get("security_token", '') == token.token):
        # add custom 403 error code
        return json({"status": 403, "message": "token unauthorized"})

    # build into context
    result = Context.from_json(data)
    # verify context `required` attributes
    if not result.validated:
        # add custom 403 error code
        return json({"status": 403, "message": result.error})
    # Validated object
    ctx = result.object
    # Replace security token to the server's after validation
    ctx.replace_security_token()
    # process message
    handler.process(ctx)
    # return context
    return json(ctx.ok)
Ejemplo n.º 5
0
def set_time_interval(from_day: float, to_day: float):
    """
    Sets start time and stop time to param.in file.
    :param from_day:
    :param to_day:
    :return:
    """
    def _edit_file(filepath: str, callback: Callable[[Iterable[str], TextIO], None]):
        with open(filepath) as f:
            out_fname = filepath + ".tmp"
            out = open(out_fname, "w")
            callback(f, out)
            out.close()
            os.rename(out_fname, filepath)

    def _update_params(infile: Iterable[str], outfile: TextIO):
        startday_pattern = ' start time (days)= '
        stopday_pattern = ' stop time (days) = '
        for line in infile:
            if line.startswith(startday_pattern):
                line = '%s%f\n' % (startday_pattern, from_day)
            if line.startswith(stopday_pattern):
                line = '%s%f\n' % (stopday_pattern, to_day)
            outfile.write(line)

    integrator_path = opjoin(Config.get_project_dir(), CONFIG['integrator']['dir'])
    param_in_filepath = opjoin(integrator_path, CONFIG.INTEGRATOR_PARAM_FILENAME)

    _edit_file(param_in_filepath, _update_params)
Ejemplo n.º 6
0
        def twitch(*args, **kwargs):
            token = request.args.get("access_token")
            if token:
                resp = get("https://api.twitch.tv/kraken/user",
                           headers={
                               "Accept":
                               "application/vnd.twitchtv.v5+json",
                               "Client-ID":
                               Config().get("Cresentials")['twitch-cid'],
                               "Authorization":
                               f"OAuth {token}"
                           }).json()

                _name = resp['display_name']
                _uid = resp['name']
                _tid = resp['_id']
                _email = resp.get('email')

                _first_join, _uuid = self.db.add_user("twitch",
                                                      email=_email,
                                                      name=_name,
                                                      uid=_uid,
                                                      tid=_tid,
                                                      now=session.get("uuid"))
                session['uuid'] = _uuid

                if not isinstance(session.get('li_platform'), dict):
                    session['li_platform'] = {}
                session['li_platform']['twitch'] = {"name": _name}

                return render_template("ok.html")
            else:
                return render_template("index.html")
Ejemplo n.º 7
0
def refresh():
    
    lpath = Config.value(Config.LIBRARY) # book location

    MODEL.clear()
    MODEL.setHorizontalHeaderLabels(['Book/Language/Chapter', ''])

    bookfiles = glob.glob(lpath+"/*.json")
    for bookf in bookfiles:
        bi = model.BookInfo.fromJsonFile(bookf)
        book_node = QtGui.QStandardItem(res.book_icon, bi.bookid)
        book_node.setData(bi)
        MODEL.appendRow(book_node)

        for tr in bi.translations:
            # Create Language Node
            lang_node = QtGui.QStandardItem(res.lang_icon, tr.language)
            lang_node.setData(tr)
            book_node.appendRow(lang_node)
            for chapter in tr.chapters:
                # Create Chapter Node
                chnum = chapter.idx
                chapter_title = model.CHAPTER_CAPTION[tr.language] + ' %04d' % chnum
                ch_icon = res.play_icon if chapter.downloaded else res.dl_icon
                chapter_node = QtGui.QStandardItem(ch_icon, chapter_title) 
                chapter.treeNode = chapter_node
                chapter_node.setData(chapter)
                lang_node.appendRow(chapter_node)
    # adjust column sizes on the tree view
    TREE_VIEW.resizeColumnToContents(0)
    TREE_VIEW.resizeColumnToContents(1)
Ejemplo n.º 8
0
 def __init__(self, root):
     self.config = Config("tkc.ini")
     root.title("Tkinter Commander")
     root.protocol("WM_DELETE_WINDOW", self.on_delete)
     self.root = root
     root.geometry(self.config.get("fm_geometry"))
     root.grid_columnconfigure(0, weight=1)
     root.grid_rowconfigure(1, weight=1)
     pw = Panedwindow(root, orient="horizontal", takefocus=False)
     frame = Frame(pw)
     self.left = Panel(frame, Local_fs(), self.config)
     pw.add(frame)
     pw.pane(frame, weight=1)
     frame = Frame(pw)
     self.right = Panel(frame, Local_fs(), self.config)
     self.right.oposite = ref(self.left)
     self.left.oposite = ref(self.right)
     self.left.activate()
     pw.add(frame)
     pw.pane(frame, weight=1)
     pw.grid(column=0, row=1, columnspan=2, sticky="senw")
     self.add_menu()
     self.add_btns()
     root.tk.call(
         "wm", "iconphoto", root._w,
         PhotoImage(file=join(dirname(__file__), "data", "favicon.gif")))
Ejemplo n.º 9
0
def play_sound(times=1, forced=False):
    ini = Config.getboolean('notification', 'playsound', fallback=True)
    if not forced and not ini:
        return

    mp3_file = Config['media']['soundtrack']
    for i in range(times):
        playsound(mp3_file)
Ejemplo n.º 10
0
def push_bullet(message, title='Fishing', forced=False):
    ini = Config.getboolean('notification', 'pushbullet', fallback=True)
    if not forced and not ini:
        return

    api_key = Config['pushbullet']['key']
    pb = Pushbullet(api_key)
    pb.push_note(title, message)
Ejemplo n.º 11
0
 def __init__(self):
     #logging.basicConfig(filename='esmart3.log', level=logging.INFO)
     #self.logger = logging.getLogger('esmart3')
     #self.logger.setLevel(logging.DEBUG)
     #self.logger.info('Started')
     self.config = Config()
     self.ser = serial.Serial(self.config.dev, 9600, timeout=0.1)
     self.ser.port = self.config.dev
     self.varBatCap = 0
Ejemplo n.º 12
0
 def __init__(self, parent=None):
     super(ReaderWidget, self).__init__(parent)
     self._autoScroll = Config.value(Config.AUTO_SCROLL)
     self.readerPane = ReaderPane(parent=parent,
                                  autoScroll=self._autoScroll)
     self.readerPane.setReadOnly(True)
     readerPaneLayout = QtWidgets.QVBoxLayout()
     readerPaneLayout.addWidget(self.readerPane)
     self.setLayout(readerPaneLayout)
Ejemplo n.º 13
0
def create_app():
    app = Flask(__name__)
    environment_config = Config.for_actual_environment()

    app.config.from_object(environment_config)
    mongo.init_app(app)
    set_up_sentry(environment_config)
    register_endpoints(app)
    return app
Ejemplo n.º 14
0
async def main():
    conf = Config()

    logging.basicConfig(level=logging.DEBUG)
    logging.config.dictConfig(conf.DEFAULT_LOGGING)
    logger = logging.getLogger(__name__)

    db = ExtendedDBManager(init_db(conf))
    db.database.create_tables([Article], safe=True)

    executor = ThreadPoolExecutor(max_workers=10)
    loop.set_default_executor(executor)

    DATA_FOR_MATPLOTLIB = {}

    await truncate(db=db)
    await vacuum(db=db)
    await drop_index(db=db)

    for mode in ["noindex", 'index']:
        await truncate(db=db)
        await vacuum(db=db)
        if mode == 'index':
            await create_index(db=db)
        else:
            await drop_index(db=db)

        for i in range(1, 81):
            await buck_create_new(db=db, epoch_count=i, count=10**6, mode=mode)
            row1 = await db.get(Article.select().limit(1))
            row2 = await db.get(Article.select().order_by(
                Article.created_date.desc()).limit(1))

            if mode == 'noindex':
                arv_time__noindex1 = await call_avr_time(db=db, text=row1.name)
                arv_time__noindex2 = await call_avr_time(db=db, text=row2.name)
                arv_time__noindex = max(arv_time__noindex1, arv_time__noindex2)

                logger.info(f"Time NoIndex={arv_time__noindex}")
                DATA_FOR_MATPLOTLIB[str(i)] = {"noindex": arv_time__noindex}
            else:
                arv_time__index1 = await call_avr_time(db=db, text=row1.name)
                arv_time__index2 = await call_avr_time(db=db, text=row2.name)
                arv_time__index = max(arv_time__index1, arv_time__index2)

                logger.info(f"Time Index={arv_time__index}")
                DATA_FOR_MATPLOTLIB[str(i)].update({"index": arv_time__index})

            logger.info(f"")
            now_count = await db.count(Article.select())
            logger.info(f"Row in db count = {now_count}")
            logger.info(f"==  ==  " * 15)
            logger.info(f"==  ==  " * 15)

    FileReader.write_data(DATA_FOR_MATPLOTLIB)
    logger.info(f"Exit")
Ejemplo n.º 15
0
 def root(*_, **__):
     if not session.get("credentials") or not session.get(
             "credentials")['logged_in']:
         return sender.render_template(self,
                                       "index.html",
                                       navbar_active="login",
                                       oauth=Config().get("OAuth"),
                                       redirect_uri=request.args.get(
                                           "redirect_uri", "/"))
     return redirect(request.args.get("redirect_uri", "/"), 302)
Ejemplo n.º 16
0
    def __init__(self, name, *args, **kwargs):
        super().__init__("Discord")

        self.__name__ = name
        self.client = Client()
        self.token = kwargs.get("token", None)
        self._config = Config()

        self.groups = {}
        self.cases = {}

        self._run = self.run
Ejemplo n.º 17
0
 def __init__(self, *args, **kwargs):
     super().__init__(*args, **kwargs)
     player = Config.get('players')
     self.player_list = [None] * 2
     self.player1widget = self.ids.player_1
     self.player2widget = self.ids.player_2
     for i in range(2):
         widget = self.player1widget if i == 0 else self.player2widget
         if player[i] == "Human":
             self.player_list[i] = Human(widget)
         elif isinstance(player[i], list):
             if player[i][0] == "Heuristic":
                 self.player_list[i] = Heuristic(player[i][1], widget, self)
                 Clock.schedule_interval(self.player_list[i].play, \
                     1.0/float(Config.get('frame_limit')))
             else:
                 raise Exception("Config Error: Malformatted AI entry!")
                 exit(1)
         else:
             raise Exception("Config Error: AI Type not understood!")
             exit(1)
Ejemplo n.º 18
0
class Attendance:
    def __init__(self, bot):
        self.bot = bot
        self.session = {}

        conf = Config("config.ini")

        trans_conf = conf.get("Translation")
        i18n.set("locale", trans_conf['default_locale'])
        i18n.set("file_type", "json")
        i18n.load_path.append(trans_conf['path'])

    DB = PostgreSQL(**Config("config.ini").get("Database"))

    def __unload(self):
        self.DB.close()

    async def on_ready(self):
        print(" [ATd] Successfully loaded.")

    @checks.is_user(DB)
    @command("출석", pass_context=True)
    async def add_attendance(self, ctx):
        _, uuid = users.get_uuid(self.DB, ctx.message.author.id)

        if uuid is None:
            await ctx.bot.reply(t("messages.register_request"))
            return

        _, data = self.DB.rnf(
            f"SELECT date FROM attendance WHERE uuid='{uuid}' and date >= current_date;"
        )

        if data:
            await ctx.bot.reply(t("messages.attendance_already"))
            return

        _, data = self.DB.rnf(
            f"INSERT INTO attendance (uuid) VALUES ('{uuid}') RETURNING date;")

        if data:
            await ctx.bot.reply(
                t("messages.attendance_success").format(time=data[0][0]))
            return

        await ctx.bot.reply(t("messages.error_call_admin"))

    @add_attendance.error
    async def error_add_attendance(self, error, ctx):
        if isinstance(error, CheckFailure):
            await ctx.bot.reply(t("messages.register_request"))

        print(error)
Ejemplo n.º 19
0
def generate_data(settings, interval, full_reset):
    st.sidebar.markdown('### Generating Data')
    del os.environ['TZ']
    # os.environ['TZ'] = ORIGINAL_TIMEZONE
    GitHistoryConverter(
        settings,
        Config(interval, full_reset),
        update_progress=update_progress_bar,
        setup_progress=setup_progress_bar
    ).convert()
    os.environ['TZ'] = 'UTC'
    st.caching.clear_cache()
    st.balloons()
Ejemplo n.º 20
0
def configure_server(config: Optional[Config] = None) -> web.Application:
    if not config:
        config = Config()  # use default values
    app = web.Application()
    app['config'] = config
    app.on_startup.append(create_morpher)
    app.on_startup.append(load_charged_words)
    app.on_startup.append(init_cache)
    app.cleanup_ctx.append(create_aiohttp_session)
    app.add_routes([
        web.get('/', index, name='index'),
        web.get('/health', health, name='health'),
    ])
    return app
Ejemplo n.º 21
0
def notifyrun(msg, forced=False):
    ini = Config.getboolean('notification', 'notifyrun', fallback=True)
    if not forced and not ini:
        return

    # put the sending work in thread in case there's delay in
    # accessing notifyrun's server
    channel = Config['notifyrun']['channel']

    def send():
        notify = Notify(endpoint=f"https://notify.run/{channel}")
        notify.send(msg)

    threading.Thread(target=send, args=()).start()
Ejemplo n.º 22
0
 def __init__(self, book_info, lang, title, content_url):
     """Initialize information on a book"""
     cpath = Config.value(Config.CONTENT)  # book contents
     self.book = book_info  # identifier of the book
     self.book_path = os.path.join(cpath, book_info.bookid,
                                   lang)  # root path of the book
     self.book_file = os.path.join(self.book_path,
                                   BOOK_FILE)  # path to the local file
     self.language = lang  # Language
     self.title = title  # Title
     self.content_url = content_url  # URL of the content
     self.chapters = []  # List of chapters
     self.book.addTranslation(self)
     self.updateStatus()  # update download status
Ejemplo n.º 23
0
def showSearch(parent):
    dialog = SearchDialog(parent)
    result = dialog.exec_()
    if result == QtWidgets.QDialog.Accepted:
        for i in range(dialog.model.rowCount()):
            itm = dialog.model.item(i)
            if itm.checkState() == Qt.Checked:
                book_id = itm.text() # selected book identifier
                book_def = book_manager.getNetBook(book_id) # get the book configuration
                lpath = Config.value(Config.LIBRARY) # save location
                os.makedirs(lpath, exist_ok=True)
                fname = os.path.join(lpath, book_id + ".json")
                with open(fname, 'w') as f:
                    f.write(book_def)
                parent.updateLibrary()
Ejemplo n.º 24
0
    def decorated_view(*args, **kwargs):
        if request.method in EXEMPT_METHODS:
            return func(*args, **kwargs)

        environment_config = Config.for_actual_environment()
        if not environment_config.need_authorization():
            return func(*args, **kwargs)

        token = request.headers.get('Authorization')
        if token != environment_config.token():
            return json.dumps({
                "object": {},
                "errors": ["Ingreso no permitido"]
            }), 403

        return func(*args, **kwargs)
Ejemplo n.º 25
0
    def __init__(self):
        logging.basicConfig(filename='esmart3.log', level=logging.INFO)
        self.logger = logging.getLogger('esmart3')
        #self.logger.setLevel(logging.DEBUG)
        self.logger.info('Started')

        self.chgMode = ["IDLE", "CC", "CV", "FLOAT", "STARTING"]
        self.batType = ["User-defined", "Flooded", "Sealed", "Gel"]
        self.fault = [
            "Battery voltage over", "PV voltage over", "Charge current over",
            "Dis-charge over", "Battery temperature alarm",
            "Internal temperature alarm", "PV voltage low",
            "Battery voltage low", "Trip zero protection trigger",
            "In the control of manual switchgear"
        ]
        self.config = Config()
        self.ser = serial.Serial(self.config.dev, 9600, timeout=0.1)
        self.ser.port = self.config.dev
Ejemplo n.º 26
0
# encoding=utf8
import subprocess
from settings import Config

MEDIA_REMOTE_URL = Config.get_config()['media_remote_url']
APP_SOURCE_REMOTE_URL = Config.get_config()['app_source_remote_url']
MEDIA_DIR = Config.get_config()['media_dir']
APP_SOURCE_DIR = Config.get_config()['app_source_dir']
C_APP = 'APP'
C_MEDIA = 'MEDIA'


def git(repo_dir, *args):
    ret = subprocess.check_output(['git'] + list(args), cwd=repo_dir)
    print('git ' + str(list(args)))
    return ret


def pip(*args):
    ret = subprocess.check_output(['pip'] + list(args))
    return ret


def isUpToDate(repo_dir):
    # git fetch origin
    # "--git-dir=" + repo_dir + "/.git"
    git(repo_dir, "fetch", 'origin', 'master')
    sha1_rev_local = ''
    sha1_rev_remote = ''
    # local VS remote
    # git rev-parse @ VS git rev-parse @{u}
Ejemplo n.º 27
0
from math import radians

import pytest
from datamining import OrbitalElementSet
from datamining import OrbitalElementSetCollection
from datamining.orbitalelements.collection import AEIValueError
from os.path import join as opjoin
from settings import Config

PROJECT_DIR = Config.get_project_dir()
PARAMS = Config.get_params()
A1_AEI_FILE_LEN = 46


def test_orbital_elements():
    filepath = opjoin(PROJECT_DIR, PARAMS['integrator']['dir'], 'A1.aei')
    collection = OrbitalElementSetCollection(filepath)
    assert len(collection.orbital_elements) == A1_AEI_FILE_LEN
    assert len(collection) == A1_AEI_FILE_LEN
    orbitalelements = collection.orbital_elements[0]

    assert orbitalelements == collection[0]
    assert orbitalelements.time == 0.0000000
    assert orbitalelements.p_longitude == radians(1.541309E+02)
    assert orbitalelements.mean_anomaly == radians(3.172742E+02)
    assert orbitalelements.semi_axis == 2.76503
    assert orbitalelements.eccentricity == 0.077237
    assert orbitalelements.inclination == radians(int(10.6047))
    assert orbitalelements.node == radians(int(80.4757))

Ejemplo n.º 28
0
import redis

from sqlalchemy import create_engine, Integer, Column
from sqlalchemy.ext.declarative import as_declarative
from sqlalchemy.orm import Session
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import ClauseElement
from alembic.config import Config as AlembicConfig
import os
from settings import Config
from sqlalchemy import event
from sqlalchemy.engine import Engine
import time
import logging

CONFIG = Config.get_params()
_HOST = CONFIG['postgres']['host']
_USER = CONFIG['postgres']['user']
_PASSWORD = CONFIG['postgres']['password']
_DB = CONFIG['postgres']['db']

if CONFIG['debug']:
    logging.basicConfig()
    logger = logging.getLogger("myapp.sqltime")
    logger.setLevel(logging.DEBUG)

    @event.listens_for(Engine, "before_cursor_execute")
    def before_cursor_execute(conn, cursor, statement, parameters, context, executemany):
        conn.info.setdefault('query_start_time', []).append(time.time())
        logger.debug("Start Query: %s", statement % parameters)
Ejemplo n.º 29
0
    "[%(levelname)-8s] %(filename)s => %(asctime)s | %(message)s")

if not "logs" in os.listdir():
    os.mkdir("logs")

FileLogger = logging.FileHandler("./logs/lastest.log")
FileLogger.setFormatter(formatter)
FileLogger.setLevel(logging.DEBUG)
logger.addHandler(FileLogger)

StreamLogger = logging.StreamHandler()
StreamLogger.setFormatter(formatter)
StreamLogger.setLevel(logging.DEBUG)
logger.addHandler(StreamLogger)

HookConfig = Config().get("Hook")
DiscordLogger = DLogger(HookConfig)
DiscordLogger.setFormatter(formatter)
DiscordLogger.setLevel(logging.WARNING)
logger.addHandler(DiscordLogger)


class CrawlBot:
    def __init__(self):
        self.is_alive = True
        self.loop = asyncio.get_event_loop()

    async def teardown(self):
        logger.warn(" ! TEARDOWN ! Event loop was died")

    def run(self):
Ejemplo n.º 30
0
from os.path import join as opjoin
from shutil import copyfile
import os
from settings import Config

PROJECT_DIR = Config.get_project_dir()
INTEGRATOR_PATH = opjoin(PROJECT_DIR, Config.get_params()['integrator']['dir'])
PARAMS = Config.get_params()


def test_set_time_interval():
    from integrator import set_time_interval

    def _copyfile(name: str):
        path = opjoin(INTEGRATOR_PATH, name)
        target = opjoin(INTEGRATOR_PATH, name + '.backup')
        copyfile(path, target)
        return path

    param_in_filepath = _copyfile(PARAMS.INTEGRATOR_PARAM_FILENAME)

    set_time_interval(1, 2)

    startday_assert_flag = False
    stopday_assert_flag = False
    with open(param_in_filepath) as f:
        for line in f:
            startday_assert_flag = startday_assert_flag or (' start time (days)= 1' in line)
            stopday_assert_flag = stopday_assert_flag or (' stop time (days) = 2' in line)

    assert startday_assert_flag
Ejemplo n.º 31
0
from .facades import PhaseCountException
from .collection import OrbitalElementSet

from os.path import exists as opexists
from os.path import join as opjoin
from os.path import isabs
from os import makedirs
import glob
from tarfile import is_tarfile
from tarfile import open as taropen
import os
from settings import Config
import shutil
from os.path import basename

PROJECT_DIR = Config.get_project_dir()
CONFIG = Config.get_params()
_ex_folder = CONFIG['extract_dir']
EXTRACT_PATH = _ex_folder if isabs(_ex_folder) else opjoin(PROJECT_DIR, _ex_folder)

BUCKET = CONFIG['s3']['bucket']
_s3_folder = CONFIG['s3files_dir']
S3_FILES_DIR = _s3_folder if isabs(_s3_folder) else opjoin(PROJECT_DIR, _s3_folder)


class FilepathException(Exception):
    pass


class FilepathInvalidException(Exception):
    pass
  from email.mime.multipart import MIMEMultipart
  from email.mime.text import MIMEText
except:
  from email.MIMEMultipart import MIMEMultipart
  from email.MIMEText import MIMEText

from datetime import datetime,date,timedelta,time
from pytz import timezone,utc
from threading import Timer
import codecs

from models import Reservation, Flight, FlightLeg, FlightLegLocation

# Load settings
from settings import Config
config = Config()

from db import Database
from tasks import *

# ========================================================================

base_url = 'http://www.southwest.com'
checkin_url = urlparse.urljoin(base_url, '/flight/retrieveCheckinDoc.html')
retrieve_url = urlparse.urljoin(base_url, '/flight/lookup-air-reservation.html')

# Common US time zones
tz_alaska = timezone('US/Alaska')
tz_aleutian = timezone('US/Aleutian')
tz_arizona = timezone('US/Arizona')
tz_central = timezone('US/Central')
Ejemplo n.º 33
0
from settings import Config
from engine import FlaskEngine


config = Config()

engine = FlaskEngine(
    config.get("Web"),
    webpages=[
        "pages.root",
        "pages.login",
        "pages.sso",
        "pages.service",
        "pages.profile",
        "pages.rank"
    ]
)

engine.run()
Ejemplo n.º 34
0
 def __init__(self) -> None:
     self._config = Config()
     self._engine = None
Ejemplo n.º 35
0
from os import urandom
from flask import Flask, session
from pages import blueprints as bps
from settings import Config

conf = Config()
app_config = conf.get("Web")

_temp = app_config.get("secret_key")
if _temp:
    _secret_key = app_config.get("secret_key")
    del app_config["secret_key"]
else:
    _secret_key = urandom(32)

app = Flask(__name__)
app.secret_key = _secret_key


@app.before_request
def make_empty_session(*_, **__):
    if not session.get("credentials"):
        session['credentials'] = {
            "logged_in": False,
            "display_name": "placeholder"
        }


for module in bps:
    if not hasattr(module, "setup"):
        raise Exception("An improper blueprint module was passed")
Ejemplo n.º 36
0
from celery import Celery
from celery.task import task, periodic_task
from settings import Config
def make_celery(app):
    celery = Celery(app.import_name, broker=Config.BROKER_URL)
    celery.conf.update(app.config)
    TaskBase = celery.Task
    class ContextTask(TaskBase):
        abstract = True
        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)
    celery.Task = ContextTask
    return celery

from app import create_app
app = create_app(Config())
celery = make_celery(app)


@task
def test():
    print session
Ejemplo n.º 37
0
class Face:
    def __init__(self, root):
        self.config = Config("tkc.ini")
        root.title("Tkinter Commander")
        root.protocol("WM_DELETE_WINDOW", self.on_delete)
        self.root = root
        root.geometry(self.config.get("fm_geometry"))
        root.grid_columnconfigure(0, weight=1)
        root.grid_rowconfigure(1, weight=1)
        pw = Panedwindow(root, orient="horizontal", takefocus=False)
        frame = Frame(pw)
        self.left = Panel(frame, Local_fs(), self.config)
        pw.add(frame)
        pw.pane(frame, weight=1)
        frame = Frame(pw)
        self.right = Panel(frame, Local_fs(), self.config)
        self.right.oposite = ref(self.left)
        self.left.oposite = ref(self.right)
        self.left.activate()
        pw.add(frame)
        pw.pane(frame, weight=1)
        pw.grid(column=0, row=1, columnspan=2, sticky="senw")
        self.add_menu()
        self.add_btns()
        root.tk.call(
            "wm", "iconphoto", root._w,
            PhotoImage(file=join(dirname(__file__), "data", "favicon.gif")))

    def add_menu(self):
        top = self.root
        top["menu"] = menubar = Menu(top)
        menu_file = Menu(menubar)
        menu_settings = Menu(menubar)
        menu_help = Menu(menubar)
        menubar.add_cascade(menu=menu_file, label=_("File"))
        menubar.add_cascade(menu=menu_settings, label=_("Settings"))
        menubar.add_cascade(menu=menu_help, label=_("Help"))
        menu_settings.add_command(label=_("Pannel Settings"),
                                  command=self.dlg_panset)

    def add_btns(self):
        root = self.root
        frame = Frame(root)
        for key, text, command in (
                (3, _("F3 View"), self.on_F3),
                (4, _("F4 Edit"), self.on_F4), (5, _("F5 Copy"), self.on_F5),
                (6, _("F6 Move"),  self.on_F6),
                (7, _("F7 Make Directory"), self.on_F7),
                (8, _("F8 Remove"), self.on_F8),
                (10, _("F10 Exit"), self.on_F10)):
            btn = Button(frame, text=text, command=command, takefocus=False)
            btn.pack(side="left", fill="x", expand=True)
            root.bind_all("<F%d>" % key, func=command)
        sz = Sizegrip(frame)
        sz.pack(side="right", anchor="se")
        frame.grid(column=0, row=2, columnspan=2, sticky="we")

    def get_panels(self):
        "returns (active, passive) panels"
        if self.left.is_active:
            return self.left, self.right
        return self.right, self.left

    def on_delete(self):
        self.config["fm_geometry"] = self.root.geometry()
        self.config.save()
        self.root.destroy()

    def on_F3(self, evt=None):
        print("F3")

    def on_F4(self, evt=None):
        print("F4")

    def on_F5(self, evt=None):
        buttons.copy_button(self)

    def on_F6(self, evt=None):
        print("F6")

    def on_F7(self, evt=None):
        print("F7")

    def on_F8(self, evt=None):
        print("F8")

    def on_F10(self, evt=None):
        self.on_delete()

    def dlg_panset(self):
        from dialogs import Dlg_panset
        Dlg_panset(self.root, self.config)
Ejemplo n.º 38
0
from override import CrescBot
from settings import Config

cogs = [
    "cogs.test", "cogs.vip", "cogs.members", "cogs.attendance", "cogs.admin"
]

_conf = Config("config.ini")
_token = _conf.get("Credential.token")

bot = CrescBot(command_prefix="크센아 ")

for cog in cogs:
    bot.load_extension(cog)

bot.run(_token)
Ejemplo n.º 39
0
from math import radians
from math import sqrt
from typing import List, Tuple

from settings import Config

SMALL_BODY = 'small_body'
CONFIG = Config.get_params()
OUTPUT_ANGLE = CONFIG['output']['angle']
BODIES_COUNTER = CONFIG['integrator']['number_of_bodies']
SMALL_BODIES_FILENAME = CONFIG['integrator']['files']['small_bodies']
HEADER_LINE_COUNT = 4


class AEIValueError(ValueError):
    pass


class OrbitalElementSet:
    _TIME = 0
    _PERIHELLION_LONGITUDE = 1
    _MEAN_ANOMALY = 2
    _SEMIMAJOR_AXIS = 3
    _ECCENTRICITY = 4
    _INCLINATION = 5
    _NODE = 7

    def __init__(self, data_string: str):
        """Data string must be formated as data in aei file, that generates by element6.
        :param data_string:
        :except ValueError: if data from data_string has incorrect values.