def run(self, incoming, internal, outgoing):
        g.PHASE = self.phase
        g.SERVER_SEQ = self.server_seq

        config.load()
        logger.init('play')
        master_data.load()

        # test
        g.MST[1] = 2

        while self.is_running:
            time.sleep(0.001)

            self.curr_time = time.time()
            self.delta_time = (self.curr_time - self.last_time) * 1000

            i = 0
            while i < self.get_max and not incoming.empty():
                i += 1

                print('incoming_get')
                (conn_id, req_msg_type, req_msg_body) = incoming.get()
                print(conn_id)
                print(req_msg_type)
                print(req_msg_body)
                if req_msg_type == e.PLAYER_CREATE:
                    print('add_player')
                    area_id = 0
                    self.players[conn_id] = Player(area_id)
                    self.areas[area_id].player_conn_ids.append(conn_id)

                elif req_msg_type == e.PLAYER_DELETE:
                    print('remove_player')
                    area_id = self.players[conn_id].area_id
                    self.areas[area_id].player_conn_ids.remove(conn_id)
                    del self.players[conn_id]

                elif req_msg_type in g.PLAY_HANDLERS:
                    (conn_id, ack_msg_type, ack_msg_body, rcpt) = \
                        g.PLAY_HANDLERS[req_msg_type](conn_id, req_msg_body)

                    if rcpt == e.TO_ME:
                        outgoing.put([conn_id, ack_msg_type, ack_msg_body])

                    if rcpt == e.TO_ALL:
                        area_id = self.players[conn_id].area_id
                        for player_conn_id in self.areas[area_id].player_conn_ids:
                            outgoing.put([player_conn_id, ack_msg_type, ack_msg_body])

                    elif rcpt == e.TO_DATA:
                        internal.put([player_conn_id, ack_msg_type, ack_msg_body])

            for player in self.players.values():
                player.run(self.delta_time)

            for area in self.areas.values():
                area.run(self.delta_time)

            self.last_time = self.curr_time
Esempio n. 2
0
def create_app(config=None):
    """
    Create and initialise the application.
    """
    app = Flask(__name__)
    app.config.from_pyfile('%s/config/default.py' % app.root_path)

    if config:
        app.config.from_pyfile(config)
    elif os.getenv('FLASK_CONFIG'):
        app.config.from_envvar('FLASK_CONFIG')

    logger.init(app)
    jinja.init(app)
    assets.init(app)

    app.register_blueprint(views.blueprint)

    @app.errorhandler(404)
    def not_found(error):
        return render_template('errors/404.html'), 404

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html'), 403

    @app.errorhandler(500)
    def server_error(error):
        return render_template('errors/default.html'), 500

    return app
 def __init__(self):
     self.ci_users = {}
     self.cfg = config.Config()
     self.db = db_helper.DBHelper(self.cfg).get()
     logger.init(self.cfg)
     self.log = logger.get('scoreboard-gerrit-listener')
     self.g = None
def main():
    server_type = 'play'

    if len(sys.argv) < 3:
        print('Usage: sudo python3 ./PlayServer.py develop 00')
        sys.exit()

    g.PHASE = sys.argv[1]
    g.SERVER_SEQ = sys.argv[2]

    config.load()
    logger.init(server_type)
    master_data.load()

    # test
    g.MST[1] = 2

    pool_size = g.CFG[server_type + '_thread_pool_size']
    port = g.CFG[server_type + g.SERVER_SEQ]

    # queue
    g.INCOMING = multiprocessing.Queue()
    g.INTERNAL = multiprocessing.Queue()
    g.OUTGOING = multiprocessing.Queue()

    # play
    play_loop = PlayLoop(g.PHASE, g.SERVER_SEQ)
    g.PROCESS = multiprocessing.Process(target=play_loop.run, args=(g.INCOMING, g.INTERNAL, g.OUTGOING))
    g.PROCESS.start()

    # play_server
    g.LOOP = asyncio.get_event_loop()

    # pool
    g.REDIS_POOL = yield from asyncio_redis.Pool.create(host='127.0.0.1', port=6379, poolsize=10)
    g.THREAD_POOL = concurrent.futures.ThreadPoolExecutor(pool_size)

    try:
        g.LOOP.add_signal_handler(signal.SIGINT, shutdown)
        g.LOOP.add_signal_handler(signal.SIGTERM, shutdown)

    except NotImplementedError:
        pass

    g.TASK_INTERNAL = g.LOOP.create_task(handle_internal())
    g.TASK_OUTGOING = g.LOOP.create_task(handle_outgoing())

    coro = g.LOOP.create_server(PlayConnection, port=port)
    g.SERVER = g.LOOP.run_until_complete(coro)

    for sock in g.SERVER.sockets:
        print('{}_server_{} starting.. {}'.format(server_type, g.SERVER_SEQ, sock.getsockname()))

    try:
        g.LOG.info('%s_server_%s starting.. port %s', server_type, g.SERVER_SEQ, port)
        g.LOOP.run_forever()

    except KeyboardInterrupt:
        shutdown()
Esempio n. 5
0
def main():

    # Initialize the logger.
    logger.init(logger.DEBUG)

    # Add a callback handler.
    h = logger.add_callback_handler(log_callback)

    # Log an info message.
    logger.info("Testing 1 2 3")
Esempio n. 6
0
def initialize(context):
    import roles_editor, orgs_editor, pwreset_tool, users_admin, \
        api_tool, dashboard
    import nfp_nrc, logger
    import countries

    countries.load_countries()
    logger.init()

    context.registerClass(roles_editor.RolesEditor, constructors=(
        ('manage_add_roles_editor_html',
         roles_editor.manage_add_roles_editor_html),
        ('manage_add_roles_editor', roles_editor.manage_add_roles_editor),
    ))

    context.registerClass(orgs_editor.OrganisationsEditor, constructors=(
        ('manage_add_orgs_editor_html',
         orgs_editor.manage_add_orgs_editor_html),
        ('manage_add_orgs_editor', orgs_editor.manage_add_orgs_editor),
    ))

    context.registerClass(pwreset_tool.PasswordResetTool, constructors=(
        ('manage_add_pwreset_tool_html',
         pwreset_tool.manage_add_pwreset_tool_html),
        ('manage_add_pwreset_tool', pwreset_tool.manage_add_pwreset_tool),
    ))

    context.registerClass(users_admin.UsersAdmin, constructors=(
        ('manage_add_users_admin_html',
         users_admin.manage_add_users_admin_html),
        ('manage_add_users_admin', users_admin.manage_add_users_admin),
    ))

    context.registerClass(nfp_nrc.NfpNrc, constructors=(
        ('manage_add_nfp_nrc_html',
         nfp_nrc.manage_add_nfp_nrc_html),
        ('manage_add_nfp_nrc', nfp_nrc.manage_add_nfp_nrc),
    ))

    context.registerClass(api_tool.ApiTool, constructors=(
        ('manage_add_api_tool', api_tool.manage_add_api_tool),
    ))

    context.registerClass(dashboard.Dashboard, constructors=(
        ('manage_add_ldap_admin_html',
         dashboard.manage_add_ldap_admin_html),
        ('manage_add_ldap_admin', dashboard.manage_add_ldap_admin),
    ))
Esempio n. 7
0
def main():
 
      options, args = parser.parse_args()
      
      socket.setdefaulttimeout(30)
      
      Storage.init_db(options.db_file)
      storage = Storage(options.db_file)
      
      logger.init(options.log_level, options.log_file)
      
      worker_manager = managers.NormalManager(options.num_of_threads, max_wait_time=400)
      spider = Spider(options.url, worker_manager, storage, 
                    keyword=options.keyword, max_level = options.max_level)
      worker_manager.put_job(spider)
      worker_manager.start()
Esempio n. 8
0
 def __init__( self, serial_setup = ( "/dev/ttyUSB0", 115200, 8, 'N', 1, 1), 
               network_setup = ( None, "eth0" ), login = ( "root", "" ),
               boot_prompt = "HidaV boot on", serial_skip_pw = True,
               hw_reset = True ):
     """ Initialize a new connection instance.
         @param serial_setup:  Set of init options for the serial backend:
           ( "port", baudrate, data bits, parity, stop bits, timeout_sec )
         @param network_setup: Set of init options for network connections:
             ( "ip or hostname", "network dev ON THE DEVICE") 
         @param login:         Tuple of ( username, pass ) for the device.
         @param boot_prompt:   String to recognize the boot loader prompt
                                 with.
         @param serial_skip_pw: True if the serial login does not prompt
                                for a password.
         @param hw_reset: 	   True if the device requires a HW reset to reboot.
                                Will be passed to serial connection."""
     self._logger = logger.init()
     self._login = login
     self._target_if = network_setup[1]
     self._hw_reset = hw_reset
     self._serial = self._serial_setup( *serial_setup, 
                         skip_pass = serial_skip_pw, 
                         boot_prompt = boot_prompt )
     if network_setup[0]:
         self.host = network_setup[0]
Esempio n. 9
0
def create_app(config=None):
    """
    Create and initialise the application.
    """
    app = Flask(__name__)
    app.config.from_pyfile('%s/config/default.py' % app.root_path)

    if config:
        app.config.from_pyfile(config)
    elif os.getenv('FLASK_CONFIG'):
        app.config.from_envvar('FLASK_CONFIG')

    logger.init(app)
    jinja.init(app)
    uploads.init(app)
    assets.init(app)

    # Add request hook to change x-sendfile to x-accel-redirect (for nginx)
    @request_finished.connect_via(app)
    def nginx_sendfile_patch(sender, response):
        if 'X-Sendfile' in response.headers:
            filepath = '/' + relpath(response.headers['X-Sendfile'],
                                     abspath(app.config['UPLOADS_DEFAULT_DEST']))
            response.headers['X-Accel-Redirect'] = filepath
            del response.headers['X-Sendfile']

    app.register_blueprint(views.blueprint)
    app.register_blueprint(api.blueprint)

    @app.errorhandler(404)
    def not_found(error):
        return render_template('errors/404.html'), 404

    @app.errorhandler(403)
    def forbidden(error):
        return render_template('errors/403.html'), 403

    @app.errorhandler(500)
    def server_error(error):
        return render_template('errors/default.html'), 500

    return app
Esempio n. 10
0
    def __init__( self, devtype = "HidaV" ):
        """ Initialise a device instance.
            @param devtype: Device type, either "hidav" or "hipox" """
        try:
            self._setup = Device.DEVICE_TYPES[ devtype.lower() ]
        except KeyError:
            raise Exception("Unknown device type %s." % devtype)

        self.conn = connection.Connection( 
            network_setup = self._setup["network_setup"], 
            login = self._setup["login"],
            serial_skip_pw = self._setup["serial_skip_pw"] )
        self._logger = logger.init()
Esempio n. 11
0
File: kiwi.py Progetto: k0da/kiwi-1
def main():
    """
        kiwi - main entry
    """
    logger.init()
    try:
        App()
    except KiwiError as e:
        # known exception, log information and exit
        logger.log.error('%s: %s', type(e).__name__, format(e))
        sys.exit(1)
    except KeyboardInterrupt:
        logger.log.error('kiwi aborted by keyboard interrupt')
        sys.exit(1)
    except docopt.DocoptExit:
        # exception caught by docopt, results in usage message
        raise
    except SystemExit:
        # user exception, program aborted by user
        sys.exit(1)
    except Exception:
        # exception we did no expect, show python backtrace
        logger.log.error('Unexpected error:')
        raise
Esempio n. 12
0
def main():
    """
    Main function
    
    1) parse program options
    2) init logger module
    3) parse students list
    4) parse tasks
    5) send data to print or web interface module
    """
    # parse program params and XML configuration file
    (state, configuration) = parse_options()
    # print help
    if state == 1:
        print_help()
        return common.EXIT_OK
    # something got wrong
    elif state != 0 or configuration == None:
        return common.EXIT_ERROR_OPTIONS
    # config ok
    else:
        common.set_config(configuration)
    # init logger module
    state = logger.init()
    # something got wrong
    if state != 0:
        return common.EXIT_ERROR_LOGGER
    logger.print_msg("isjtests started")
    # parse students list
    students = read_students_list()
    # something got wrong
    if students == None or len(students) == 0:
        return common.EXIT_ERROR_STUDENTS
    # parse tasks
    tasks = taskparser.parse_all_tasks()
    # something got wrong
    if tasks == None or len(tasks) == 0:
        return common.EXIT_ERROR_TASKS
    # send data to interface module, wait for finish
    if configuration.get_mode() == "print":
        status = printface.serve(students, tasks)
    elif configuration.get_mode() == "web":
        status = webface.serve(students, tasks)
    # something got wrong
    if status != 0:
        return common.EXIT_ERROR_INTERFACE
    # everything ok
    return 0
Esempio n. 13
0
DEFAULT_DOCKER_CONFIG = {
    "client": {"base_url": "unix://var/run/docker.sock", "version": "1.14", "timeout": 10},
    "build": {
        "quiet": False,
        "fileobj": None,
        "nocache": False,
        "rm": True,
        "stream": False,
        "timeout": None,
        "custom_context": False,
        "encoding": None,
    },
}

jocker_lgr = logger.init()
verbose_output = False


def _set_global_verbosity_level(is_verbose_output=False):
    """sets the global verbosity level for console and the jocker_lgr logger.

    :param bool is_verbose_output: should be output be verbose
    """
    global verbose_output
    # TODO: (IMPRV) only raise exceptions in verbose mode
    verbose_output = is_verbose_output
    if verbose_output:
        jocker_lgr.setLevel(logging.DEBUG)
    else:
        jocker_lgr.setLevel(logging.INFO)
Esempio n. 14
0
def main(client):
    from docopt import docopt
    arguments = docopt(__doc__)
    path = arguments['<path>']
    type_ = arguments['--type']
    if arguments['--debug']:
        logfile = '/tmp/mpdscript.log'  # LogFile.strip()
        logger.init(logfile)
    logging.info('add %s:%s' % (type_, path))

    if type_ in ('directory', 'playlist'):
        item = {type_: path}
    else:
        l = client.find('filename', path)
        if len(l) > 0:
            item = l[0]
        else:
            item = {'directory': path}

    _list = database.add2(item, client)
    if len(_list) < 0:
        return

    """
    playlist不可以拆散后加入,必须要通过client.load才能加载到必要的信息.
    所以如果playlist中有dislike的项目,那么只能加入后再删除了.

    因此,只能第一次add全部加入,然后再读取playlist,删掉dislike的部分.
    """
    if arguments['--clear']:
        client.clear()
    for item in _list:
        if 'file' in item:
            client.add(item['file'])
        elif 'playlist' in item:
            try:
                client.load(item['playlist'])
            except mpd.CommandError as e:
                pass
            else:
                pass

    if arguments['--clear']:
        client.next()
    client.play()

    # 添加完毕后再消除.
    # 逐个删除操作消耗很大,相比之下添加几乎一瞬间就完成了.不过似乎不存在批量删除的api
    # 不过这点消耗在容忍范围内
    # 所以播放可以提前到前面.小概率事件播放中的曲目可能会被下面代码删除掉.完善的做法是后面加一个播放中检查.
    l = client.playlistinfo()
    from favfilter import dislike
    for item in l:
        if dislike(item):
            #会有删除失败的情形
            try:
                client.deleteid(item['id'])
            except:
                pass

    # 检查下是否播放停了.
    song = client.currentsong()
    if None == song:
        client.next()
    client.play()
Esempio n. 15
0
    # garbagePositioner.requirements.load(os.path.join(general.config.generalConfigFolder, general.config.requirementsFolder, general.config.currentRequirementsFile+general.config.requirementsFileExtension))

    # general.config.currentProjectFolder = 'Blackbird'
    # general.config.positionerFolderSuffix = ''
    # general.config.currentTestBenchFile = '04_XY_7bench_1.json'
    # general.config.currentPositionerFile = 'SDSSV.json'
    # general.config.currentRequirementsFile = 'SDSSV.json'
    # general.config.currentFastCalibrationFile = 'fastCalib.json'
    # general.config.currentCalibrationFile = 'MPS_calib.json'
    # general.config.currentTestsFile = ''
    # general.config.save()
    # general.testBench.save(os.path.join(general.config.generalConfigFolder, general.config.testBenchFolder),general.config.currentTestBenchFile)
    # general.fastCalibrationPar.save(os.path.join(general.config.generalConfigFolder, general.config.calibrationsFolder,general.config.currentFastCalibrationFile))
    # general.calibration.save(os.path.join(general.config.generalConfigFolder, general.config.calibrationsFolder),general.config.currentCalibrationFile)
    # garbagePositioner = pos.Positioner()
    # garbagePositioner.physics.save(os.path.join(general.config.generalConfigFolder, general.config.positionersFolder),general.config.currentPositionerFile)
    # garbagePositioner.requirements.save(os.path.join(general.config.generalConfigFolder, general.config.requirementsFolder),general.config.currentRequirementsFile)
    # garbagePositioner.model.save('python_garbage', 'model-test.json')

    # general.config.load(general.config.get_config_fileName())


if __name__ == '__main__':
    #Allow multiprocessing
    import multiprocessing as mp
    mp.freeze_support()
    np.warnings.filterwarnings('ignore')
    log.init()
    main()
    log.stop()
Esempio n. 16
0
import config, logger, daemons, time, irc.channel
from tests import pyircbot

config.init()
logger.init()

daemon = daemons.NodeDaemon("0.0.0.0", 6667)
daemon.start()

"""
settings = {
    'host': "127.0.0.1",
    'port': 6667,
    'nick': 'pyircbot',
    'ident': 'pyircbot',
    'realname': 'TheLeagueSpecialist',
    'debug': False
}
bot = pyircbot.create(settings)
standard = pyircbot.StandardBotRoutines(bot, settings)
standard.queueJoinChannels(["#Pie-Studios"])

bot.connect()
"""


 
while True:
    time.sleep(1)
Esempio n. 17
0
File: nice.py Progetto: mcanini/nice
config.set("runtime.graph", options.graph)
config.set("runtime.replay", options.replay)
if options.debug_rep and options.replay:
    config.set("runtime.replay_debug", options.debug_rep)
else:
    config.set("runtime.replay_debug", False)
if options.debug_mc:
    config.set("runtime.log_level", logging.DEBUG)
if options.quiet:
    config.set("runtime.log_level", logging.CRITICAL)
if config.get("runtime.progress"):
    config.set("runtime.log_level", logging.CRITICAL)

config.convertTypes()

logger.init(config.get("runtime.logfile"), config.get("runtime.log_level"))
log = logging.getLogger("nice")

try:
    os.mkdir("se_normalized")
except:
    pass

def run():
    stats.pushProfile("NICE execution")

    # Nox app states from the modelchecker to the symolic engine
    # Input packets from the symbolic engine to the model checker
    queue_inputs = multiprocessing.JoinableQueue()
    queue_states = multiprocessing.JoinableQueue()
Esempio n. 18
0
 def show_console(self):
     print 'console'
     log_form, log_window = logger.init(self.main, self.log)
     log_window.show()
Esempio n. 19
0
parser.add_option("-q", "--quiet", dest="quiet", action="store_true", help="Do not print statistics at the end of execution")
parser.add_option("-s", "--single-step", dest="single_step", action="store", help="Run only one iteration and save the pickled inputs in the specified file")

(options, args) = parser.parse_args()

if len(args) == 0 or not os.path.exists(args[0]):
    parser.error("Missing app to execute")

nox_app_dir = os.path.abspath(args[0])
if not os.path.isdir(nox_app_dir):
    print "Please provide a directory name on the command line."
    sys.exit(1)

app_args = args[1:]

logger.init(options.logfile, logging.DEBUG)
log = logging.getLogger("se")

stats = getStats()
stats.pushProfile("se total")

se_dir = os.path.abspath(os.path.dirname(__file__))
nox_app_dir = os.path.abspath(nox_app_dir)

os.chdir(nox_app_dir)

se_instr_dir = os.path.abspath("se_normalized")

if options.force_normalize and os.path.exists(se_instr_dir):
    shutil.rmtree(se_instr_dir)
Esempio n. 20
0
File: var.py Progetto: alyx/labere
def setup_logger():
    logger.init()
Esempio n. 21
0
import utils
import logger

import re
import urllib2
import os
import sh

lgr = logger.init()


class Handler(utils.Handler):
    def dpkg_name(self, dir):
        """renames deb files to conventional names

        :param string dir: dir to review
        """

        lgr.debug('Renaming deb files...')
        return sh.dpkg_name('{0}/*.deb'.format(dir))

    def check_if_package_is_installed(self, package):
        """checks if a package is installed

        :param string package: package name to check
        :rtype: `bool` representing whether package is installed or not
        """
        lgr.debug('Checking if {0} is installed'.format(package))
        o = sh.dpkg('-s', package)

        if not o.exit_code:
Esempio n. 22
0
    parser.add_argument("-v", "--visualize",
                        help="create visualizations",
                        action="store_true")
    parser.add_argument("-e", "--extract",
                        help="extract results",
                        action="store_true")
    parser.add_argument("-t", "--test",
                        help="run test",
                        action="store_true")
    args = parser.parse_args()

    if (args.skip_tests and not args.build):
        raise ValueError("skip-tests provided without build argument")

    util.set_working_directory()
    logger.init()
    loader = Loader()
    config = loader.load()

    # if there are no args, execute a full sequence
    # with the test and the visualization/reporting
    no_args = all(val==False for val in vars(args).values())
    if no_args:
        args.test = True
        args.visualize = True
        args.extract = True

    if args.build:
        build(config, args.skip_tests)
    if args.generate:
        generate(config)
Esempio n. 23
0
from bson import json_util
from flask import Flask, request, render_template, send_from_directory
import pymongo

import config
import db_helper
import logger


cfg = config.Config()

app = Flask(__name__)
app.debug = True

logger.init(cfg)

db = db_helper.DBHelper(cfg).get()


@app.route('/')
def index():
    return render_template('index.html', host=request.host)


@app.route('/static/<path:path>')
def send_js(path):
    # TODO: We should probably use a real webserver for this..
    return send_from_directory('static', path)

Esempio n. 24
0
import datetime

from bson import json_util
from flask import Flask, request, render_template, send_from_directory
import pymongo

import config
import db_helper
import logger

cfg = config.Config()

app = Flask(__name__)
app.debug = True

logger.init(cfg)

db = db_helper.DBHelper(cfg).get()


@app.route('/')
def index():
    return render_template('index.html', host=request.host)


@app.route('/static/<path:path>')
def send_js(path):
    # TODO: We should probably use a real webserver for this..
    return send_from_directory('static', path)