def test_load_file_env(self):
        self.assertRaises(AssertionError, lambda: config.DB_CONNECTION)

        with mock.patch("os.getenv", return_value=self.fname):
            cfg.load_config()

        self.assertIsNotNone(config.DB_CONNECTION)
Ejemplo n.º 2
0
def login(website, username, password):
    """auto login and return cookie if success

    return Error code if fails:
    '1': failed to load config
    '2': timeout
    '3': cookie not found in headers or response
    """
    cfg_data = load_config(website)
    if cfg_data is None:  # error
        return '1'

    method = 'POST'
    headers = cfg_data['headers']
    # body
    login_data = cfg_data.get('login_data', dict())
    login_data[cfg_data['field_user']] = username
    login_data[cfg_data['field_password']] = password
    authcode_name = cfg_data['field_authcode']
    if authcode_name:
        headers['Cookie'], login_data[authcode_name] = get_authcode(cfg_data['url_authcode'])
    body = urllib.urlencode(login_data)

    h = Http(timeout=T_TIMEOUT)
    try:
        rsp, content = h.request(cfg_data['url_login'], method, headers=headers, body=body)  # response 302
    except socket.timeout:
        return '2'

    # parse cookie
    clean_cookie_meth = getattr(clean_cookie, website, clean_cookie.raw)
    return clean_cookie_meth(rsp, content) or headers.get('Cookie', '3')
Ejemplo n.º 3
0
def configure_app(app):
    """Apply the configuration data from the config module to the flask application.

    :type app: flask.Flask
    :param app: The Application to configure.
    """
    if not cfg.config.loaded():
        try:
            cfg.load_config()
        except AssertionError:
            cfg.load_config(EXAMPLE_CONFIG)

    app.config.update(cfg.config.data)

    event_date = parse_cfg_date(app.config["EVENT_DATE"])
    app.config["EVENT_DATE"] = event_date
    app.config["EVENT_DATE_PRETTY"] = pretty_date(event_date, month_name=True)
    app.config["EVENT_DATE_PRETTY_LONG"] = pretty_date(event_date,
                                                       month_name=True,
                                                       show_year=True,
                                                       with_weekday=True)
    app.config["REGISTER_END"] = parse_cfg_date(app.config["REGISTER_END"])
Ejemplo n.º 4
0
 def __call__(self, parser, namespace, values, option_string=None):
     values = resolve(values)
     scfg = cfg.load_config(values)
     if 'target' in scfg:
         if not hasattr(namespace, 'target'):
             setattr(namespace, 'target', wrt(values, scfg['target']))
     if 'source' in scfg:
         if not hasattr(namespace, 'source'):
             setattr(namespace, 'source', wrt(values, scfg['source']))
     if 'align' in scfg:
         if not hasattr(namespace, 'align'):
             setattr(namespace, 'align', wrt(values, scfg['align']))
     if 'subcorpora' in scfg:
         setattr(namespace, 'subcorpora', scfg['subcorpora'])
Ejemplo n.º 5
0
 def __call__(self,parser, namespace, values, option_string=None):
     values = resolve(values)
     scfg = cfg.load_config(values)
     if 'target' in scfg:
         if not hasattr(namespace,'target'):
             setattr(namespace,'target',wrt(values,scfg['target']))
     if 'source' in scfg:
         if not hasattr(namespace,'source'):
             setattr(namespace,'source',wrt(values,scfg['source']))
     if 'align' in scfg:
         if not hasattr(namespace,'align'):
             setattr(namespace,'align',wrt(values,scfg['align']))
     if 'subcorpora' in scfg:
         setattr(namespace,'subcorpora',scfg['subcorpora'])
Ejemplo n.º 6
0
def main(args):
    print("Number of available GPUs: {}".format(torch.cuda.device_count()))

    device = torch.device('cpu')
    print("device", device)

    # config
    config = cfg.load_config(args.config)
    config.opt.n_iters_per_epoch = config.opt.n_objects_per_epoch // config.opt.batch_size

    model = {
        "alg": algebrictriangulation,
        "vol": volumetrictriangulation
    }[config.model.name](config, device=device).to(device)

    if config.model.name == "vol":
        criterion = L1loss
    else:
        criterion = MSEloss
import database as db
from cfg import config
from database.model import Team
from geotools import simple_distance
from geotools.routing import MapPoint

arguments = argparse.ArgumentParser()
arguments.add_argument("-c", "--config", help="set the configfile",
                       default="config.yaml")

arguments.add_argument("max_teams", help="Max. number of teams to export")

args = arguments.parse_args()

print "load config..."
cfg.load_config(args.config)

MAX_TEAMS = args.max_teams

print "init db..."
db.init_session(connection_string=config.DB_CONNECTION)

print "fetch teams..."

teams = db.session.query(Team).filter_by(deleted=False).filter_by(confirmed=True, backup=False).order_by(Team.id).limit(
    MAX_TEAMS).all()
data = []
round_teams = defaultdict(list)

max_working = len(teams) - (len(teams) % 3)
divider = max_working / 3.0
        help=
        "A file with a list of space, comma or semicolon separated recipients")
    spam.set_defaults(func=cmd_send_spam)

    return args.parse_args()


def cmd_send_informal(args):
    informal_to_teams(args.templatename, args.subject, not args.nodebug)


def cmd_send_planmails(args):
    results = read_plan_file(args)
    plans_to_teams(results, not args.nodebug, args.group, args.separate,
                   args.exclude)


def cmd_send_emergency_routes(args):
    results = read_plan_file(args)
    emergency_plan_routes(results, not args.nodebug)


def cmd_send_spam(args):
    send_spam(args.addresses, not args.nodebug)


if __name__ == "__main__":
    args = parse_args()
    cfg.load_config(args.config)
    args.func(args)
Ejemplo n.º 9
0
def main():
    # load config
    config = load_config()
    _consumer_key = ""
    _consumer_secret = ""
    
    if config.has_section('client'):
        _consumer_key = config.get('client', '_consumer_key')
        _consumer_secret = config.get('client', '_consumer_secret')

    # init client
    client = Client(_consumer_key, _consumer_secret)
    
    # auth before use
    auth(client, config)

    if client.is_authed():
        global local_path
        global g_ind
        if config.has_section('sync'):
            local_path = config.get('sync', 'local_path')
        if not local_path:
            home_dir = os.path.expanduser('~')
            default_dir = os.path.join(home_dir, "kuaipan")
            is_create_default = False
            if not os.path.exists(default_dir):
                is_create_default = True
                os.mkdir(default_dir)
            
            dialog = gtk.FileChooserDialog(title="请选择快盘文件同步到本地存放的文件夹", parent=None,
                action=gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
                buttons=(gtk.STOCK_CANCEL,gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,gtk.RESPONSE_OK))
            dialog.set_current_folder(default_dir)

            filter = gtk.FileFilter()
            filter.set_name("所有文件夹")
            filter.add_pattern("*")
            dialog.add_filter(filter)            
                
            response = dialog.run()
            if response == gtk.RESPONSE_OK:
                print dialog.get_filename(), 'selected'
                local_path = dialog.get_filename()
                if is_create_default and local_path != default_dir:
                    os.rmdir(default_dir)
                config.add_section('sync')
                config.set('sync', 'local_path', local_path)
                fp = open(get_cfg_path(), 'w')
                config.write(fp)                    
            else:
                print 'Closed, no files selected'
            dialog.destroy()

        if not local_path:
            return

        ac_info = client.get_account_info()
        print('is authed')
        print(ac_info)
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        g_ind = init_indicator(ac_info, client)

        # start sync thread
        start_sync(client, local_path, g_ind)
        
        # start monitor thread
        start_monitor(client, local_path, g_ind)
        
        # start run application
        gtk.main()
    else:
        print('not authed')
    def test_load_file_arg(self):
        self.assertRaises(AssertionError, lambda: config.DB_CONNECTION)
        self.assertRaises(AssertionError, cfg.load_config)
        cfg.load_config(self.fname)

        self.assertIsNotNone(config.DB_CONNECTION)
Ejemplo n.º 11
0
from fabric.api import *
from fabric.utils import *
from fabric.contrib.files import *
from server_util import *
import cfg

site_map = cfg.load_config()
env.user = '******'
env.roledefs = site_map


env.key_filename = 'aws_key.pem'

@task
def update_hosts(hostname, ip):
    host_util = hosts(get_lines("/etc/hosts"))
    text = host_util.update(ip, hostname)
    put(tmp(text), '/etc/hosts', use_sudo=True)
    sudo('chown root:root /etc/hosts')

@task
def config_hostname(hostname):
    sed('/etc/sysconfig/network', 'HOSTNAME=.*', 'HOSTNAME=%s' % hostname, use_sudo=True)
    sudo('hostname %s' % hostname)
    pass

@task
def base_install():
    sudo('yum install -y telnet wget nfs-utils')

    sudo('chkconfig rpcbind on')
Ejemplo n.º 12
0
#
# Update
# @Ekira, 2017/7/27
# Fix "out of range" bug.
# Add function: cycling showing images from a directory.
# Add function: get/set wallpaper from bing's index image everyday.
# TODO: modebingindex.py, unsupport loopping everyday now.

import sys, os

from cfg import gen_config, load_config
from modesingle import single
from modecycle import cycle
from modebingindex import bingindex

if __name__ == '__main__':
    CONFIG_PATH = "./whitodo.cfg"
    if not os.path.exists(CONFIG_PATH):
        gen_config(CONFIG_PATH)
        sys.exit()
    imgcfg = load_config(CONFIG_PATH)
    print imgcfg
    if imgcfg["mode"] == "mode-single":
        single(imgcfg)
    elif imgcfg["mode"] == "mode-cycle":
        cycle(imgcfg)
    elif imgcfg["mode"] == "mode-bingindex":
        bingindex(imgcfg)
    else:
        sys.exit()