Exemplo n.º 1
0
    def test_init(self):
        settings.update(load_settings("tests", "minimal_with"))
        settings["optimization"]["optimize"] = True
        settings["optimization"]["constrained"] = False
        model = Model()

        self.assertEqual(model.n_const, 0)

        self.assertFalse(model.trained)
        self.assertEqual(model.no_samples, 0)
        self.assertEqual(model.sampling_iterations, 0)

        self.assertFalse(model.optimization_converged)
Exemplo n.º 2
0
def settings_update(user, beans, form):
    newSetting = {}
    newSetting['OPEN_REGISTRY'] = form.get('OPEN_REGISTRY','')
    newSetting['APPROVAL_RBT'] = form.get('APPROVAL_RBT','')
    newSetting['ADMIN_EMAIL_ADDRESS'] = form.get('ADMIN_EMAIL_ADDRESS', '')
    newSetting['EMAIL_FROM_ADDRESS'] = form.get('EMAIL_FROM_ADDRESS', '')
    return json.dumps(settings.update(user_group = 'admin', newSetting = newSetting))
Exemplo n.º 3
0
def make_app():
    try:
        import local_settings
        settings.update(local_settings.settings)
    except Exception as e:
        logging.error("read local_settings fail")
        pass

    init_calibre()

    import handlers
    from calibre.db.legacy import LibraryDatabase

    auth_db_path = settings['user_database']
    logging.info("Init library with [%s]" % options.with_library)
    logging.info("Init AuthDB  with [%s]" % auth_db_path)
    logging.info("Init Static  with [%s]" % settings['static_path'])
    logging.info("Init LANG    with [%s]" % P('localization/locales.zip'))
    book_db = LibraryDatabase(os.path.expanduser(options.with_library))
    cache = book_db.new_api

    Base = declarative_base()
    engine = create_engine(auth_db_path, echo=False)
    session = scoped_session(
        sessionmaker(bind=engine, autoflush=True, autocommit=False))
    init_social(Base, session, settings)
    models.bind_session(session)

    load_calibre_translations()

    if options.syncdb:
        models.user_syncdb(engine)
        sys.exit(0)

    if options.test:
        from test import email
        email.do_send_mail()
        sys.exit(0)

    settings.update({
        "legacy": book_db,
        "cache": cache,
        "session": session,
    })

    return web.Application(SOCIAL_AUTH_ROUTES + handlers.routes(), **settings)
Exemplo n.º 4
0
def settings_update(user, beans, form):
    newSetting = {}
    newSetting['OPEN_REGISTRY'] = form.get('OPEN_REGISTRY', '')
    newSetting['APPROVAL_RBT'] = form.get('APPROVAL_RBT', '')
    newSetting['ADMIN_EMAIL_ADDRESS'] = form.get('ADMIN_EMAIL_ADDRESS', '')
    newSetting['EMAIL_FROM_ADDRESS'] = form.get('EMAIL_FROM_ADDRESS', '')
    return json.dumps(
        settings.update(user_group='admin', newSetting=newSetting))
Exemplo n.º 5
0
 def __init__(self,jsonfile):
     # open json input file
     self.jsonfile = open(jsonfile,'r')
     # load json data
     self.data = json.load(self.jsonfile)
     # update default settings
     self.settings = settings.update(self.data['settings'])
     # create models
     self.model = model(self.settings)
Exemplo n.º 6
0
    def __init__(self):
        self.database = MongoClient(
            host=settings['database']['host'],
            port=settings['database']['port']
        ).get_database(name=settings['database']['name'])

        session_settings = dict(
            driver="redis",
            driver_settings=dict(
                host='localhost',
                port=6379,
                db=0,
                max_connections=1024,
            )
        )
        settings.update(session=session_settings)

        tornado.web.Application.__init__(self, url_patterns, **settings)
Exemplo n.º 7
0
 def __init__(self, jsonfile):
     # open json input file
     self.jsonfile = open(jsonfile, 'r')
     # load json data
     self.data = json.load(self.jsonfile)
     # update default settings
     self.settings = settings.update(self.data['settings'])
     # create models
     self.model = model(self.settings)
    def do_send_mail(self, book, mail_to, fmt, fpath):
        try:
            import local_settings
            settings.update(local_settings.settings)
        except Exception as e:
            logging.error("read local_settings fail")
            pass
        # read meta info
        author = authors_to_string(
            book['authors'] if book['authors'] else [_(u'佚名')])
        title = book['title'] if book['title'] else _(u"无名书籍")
        fname = u'%s - %s.%s' % (title, author, fmt)
        fdata = open(fpath).read()

        mail_from = settings['smtp_username']
        mail_subject = _('奇异书屋:推送给您一本书《%(title)s》') % vars()
        mail_body = _(
            u'为您奉上一本《%(title)s》, 欢迎常来访问奇异书屋!http://www.talebook.org' % vars())
        status = msg = ""
        try:
            logging.info('send %(title)s to %(mail_to)s' % vars())
            mail = self.create_mail(mail_from, mail_to, mail_subject,
                                    mail_body, fdata, fname)
            sendmail(mail,
                     from_=mail_from,
                     to=[mail_to],
                     timeout=30,
                     relay=settings['smtp_server'],
                     username=settings['smtp_username'],
                     password=settings['smtp_password'])
            status = "success"
            msg = _('[%(title)s] 已成功发送至Kindle邮箱 [%(mail_to)s] !!') % vars()
            logging.info(msg)
        except:
            import traceback
            logging.error('Failed to send to kindle:')
            logging.error(traceback.format_exc())
            status = "danger"
            msg = traceback.format_exc()
        self.add_msg(status, msg)
        return
Exemplo n.º 9
0
    def test_init_raise(self):
        settings.update(load_settings("tests", "minimal"))
        settings["data"]["evaluator"] = "nonsense"

        self.assertRaises(ValueError, Model)
Exemplo n.º 10
0
def make_app():
    try:
        import local_settings
        settings.update(local_settings.settings)
        logging.info("loading local_settings.py")
    except Exception as e:
        pass

    init_calibre()

    import handlers
    from calibre.db.legacy import LibraryDatabase

    auth_db_path = settings['user_database']
    logging.info("Init library with [%s]" % options.with_library)
    logging.info("Init AuthDB  with [%s]" % auth_db_path )
    logging.info("Init Static  with [%s]" % settings['static_path'] )
    logging.info("Init LANG    with [%s]" % P('localization/locales.zip') )
    book_db = LibraryDatabase(os.path.expanduser(options.with_library))
    cache = book_db.new_api

    # hook 1: 按字母作为第一级目录,解决书库子目录太多的问题
    old_construct_path_name = cache.backend.construct_path_name
    def new_construct_path_name(*args, **kwargs):
        s = old_construct_path_name(*args, **kwargs)
        ns = s[0] + "/" + s
        logging.debug("new str = %s" % ns)
        return ns
    cache.backend.construct_path_name = new_construct_path_name

    # hook 2: don't force GUI
    from calibre import gui2
    old_must_use_qt = gui2.must_use_qt
    def new_must_use_qt(headless=True):
        try:
            old_must_use_qt(headless)
        except:
            pass
    gui2.must_use_qt = new_must_use_qt

    Base = declarative_base()
    engine = create_engine(auth_db_path, echo=False)
    session = scoped_session(sessionmaker(bind=engine, autoflush=True, autocommit=False))
    init_social(Base, session, settings)
    models.bind_session(session)

    load_calibre_translations()

    if options.syncdb:
        models.user_syncdb(engine)
        sys.exit(0)

    if options.testmail:
        from test import email
        email.do_send_mail()
        sys.exit(0)

    settings.update({
        "legacy": book_db,
        "cache": cache,
        "session": session,
        })

    return web.Application(
            SOCIAL_AUTH_ROUTES + handlers.routes(),
            **settings)
Exemplo n.º 11
0
import tornado.websocket
from sqlalchemy.orm import scoped_session, sessionmaker
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop

from settings import settings
from toolz.bd_toolz import get_engine

try:
    from settings import tornado_settings
except ImportError:
    from settings_local import tornado_settings

import urls

settings.update(tornado_settings)

application = tornado.web.Application(urls.urls, **settings)
application.webSocketsPool = []
application.db = scoped_session(sessionmaker(bind=get_engine()))


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='its ech.su!')
    parser.add_argument('-p', '--port', type=int, dest='port', help='port')
    args = parser.parse_args()

    server = HTTPServer(application)
    server.bind(args.port if args.port else 8888)
    server.start(0)  # Forks multiple sub-processes
    IOLoop.current().start()
Exemplo n.º 12
0
def settings_update(user, beans, form):
    user_group = post_to_user('/user/selfQuery/', {'token': request.form.get("token", None)}).get('data', None).get('group', None)
    newSetting = {}
    newSetting['ADMIN_EMAIL_ADDRESS'] = form.get('ADMIN_EMAIL_ADDRESS', '')
    newSetting['EMAIL_FROM_ADDRESS'] = form.get('EMAIL_FROM_ADDRESS', '')
    return json.dumps(settings.update(user_group = user_group, newSetting = newSetting))
Exemplo n.º 13
0
if r.status_code - 200 > 100:
    print({
        404: 'Не удалось достучаться до сайта',
        500: 'Ошибка на удаленном сервере'
    }.get(r.status_code, 'Сервер вернул неизвестный код'))
    sys.exit()

data: dict = r.json()
if 'error' in data:
    if data['error'] == 0:
        print('Указан неверный токен')
        sys.exit()

config.access_key = data['settings'].pop('key')
config.self_id = data.pop('self_id')
config.sync()

settings.update(data.pop('settings'))

log('Данные получены, запускаю прослушку...')

while True:
    try:
        asyncio.get_event_loop().run_until_complete(listen_longpoll(data))
    except Exception:
        log(f'Произошла ошибка!\n{traceback.format_exc()}')
        time.sleep(5)
    except KeyboardInterrupt:
        log('Клавиатурное прерывание, сдыхаю...')
        break