Exemplo n.º 1
0
#encoding:utf-8
import urllib2
from bs4 import BeautifulSoup
import re
import threading
from fiction.models import *
import string
from debug import Debug
from models import *
from utils.hashs import create_nid
#for the thread to crawler all the fiction information from qidian.com
from crawler_config import ALL_PATTERN

DG = Debug()
DG.debug = True


def get_book_infor(host, name, url, type_lock=False):
    DG.trace('yes now')
    """get book information(avatar, introduction, click times, type, completed words number,
    and all the chapter in website:host

    Args:
        host: fiction website
        book_url: book url located in host
        content_tag: div area contains the fiction's information that we want
        content_class: indetification flags
        avatar_tag: the fictions' avatar
        avatar_class: indetification
        intro_tag, intro_class
    Return:
Exemplo n.º 2
0
        numLabels = len(labels)
        wordRect = pygame.Surface((maxWidth, (maxHeight * numLabels) - 4))

        i = 0
        for l in labels:
            h = l.get_height()
            w = l.get_width()
            offset = (wordRect.get_width() - w) / 2
            wordRect.blit(l, (offset, i * h))
            i += 1
        sx = (self.screen.get_width() - wordRect.get_width()) / 2
        sy = (self.screen.get_height() - wordRect.get_height()) / 2
        self.screen.blit(wordRect, (sx, sy))
        pygame.display.flip()


if __name__ == '__main__':
    os.environ['DISPLAY'] = ":0.0"
    os.chdir(os.path.dirname(sys.argv[0]))
    os.chdir("..")  # sigh: get to default app path
    Debug(["__main__"])
    Specs("%s/%s" % ("speclib", "poem.json"))
    pygame.init()
    Display().image(sys.argv[1])
    time.sleep(5)
    Display().text(["foo", "bar"])
    time.sleep(5)
    Display().text("what a friend we have in bezos. The Bastard")
    time.sleep(5)
Exemplo n.º 3
0
        print("%s at %s" % (pname, datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d %H:%M:%S')))
        pygame.mixer.pre_init(frequency=44100,
                              size=-16,
                              channels=2,
                              buffer=4096)
        pygame.init()
        parser = argparse.ArgumentParser()
        parser.add_argument('-c',
                            '--config',
                            nargs=1,
                            type=str,
                            default=[defaultSpecPath],
                            help='specify different config file')
        args = parser.parse_args()
        Debug(['specs', "__main__"])
        Debug().p("config path %s" % args.config[0])
        specs = Specs(args.config[0]).s
        Debug().enable(specs['debug'])
        while True:
            Poem().show()
            time.sleep(Specs().s['nextTime'])

    except ServiceExit:
        print("%s got signal" % pname)
        gardenExit = 5
    except Exception as e:
        print("%s" % e)
        traceback.print_exc()
        gardenExit = 5
Exemplo n.º 4
0
parser.add_argument('value',
                    metavar='value',
                    type=float,
                    help='value in currency1')
parser.add_argument("to",
                    metavar=("to"),
                    type=lambda f: str(f).upper(),
                    help="Currency to which convert to",
                    choices=provider.symbols)

parser.add_argument(
    "-v",
    "--verbose",
    action='store_const',
    const=1,
    default=0,
    help="if true, print a descriptive message of what is happening")

args = parser.parse_args()
log = Debug(args.verbose)
provider.loadvalues()

log(f"Converting {provider._name(args.fro)} to {provider._name(args.to)}")

result = provider.data[args.fro] / provider.data[args.to] * args.value

log(f"{args.value} {provider._name(args.fro)} equals {result} {provider._name(args.fro)}"
    )

print(result)
Exemplo n.º 5
0
 def register(self, cmds):
     Debug().p("%s: registering command %s" % (self.name, cmds))
     for k in cmds.keys():
         self.commandTable[k] = cmds[k]
Exemplo n.º 6
0
    file = []

    # we append the headers
    file.extend(writeheaders(datamodel))

    # we write the data model
    file.extend(writemodel(datamodel))

    # we extract and process relations
    relations = process_relations(datamodel)
    file.extend(writerelations(relations))

    #we end the file
    file.extend(closefile(datamodel))

    #we write the file
    writeplantuml(file)


if __name__ == "__main__":
    # Initialize debuger
    dbg = Debug(os.path.basename(__file__), level=1)
    dbg.msg('Version', 'sys.version', 'sys.version', 1, sys.version)
    main()
    # Use
    # https://plantuml-editor.kkeisuke.com/
    # to visualize
    # TODO abrir branch nuevo
    # TODO make two outputs with and without relations
    # TODO black list for relationships
Exemplo n.º 7
0
 def startRecog(self,cmd):
   Debug().p("starting recog")
   self.queue.put("__start__")
   return Hosts.jsonStatus("ok")
Exemplo n.º 8
0
    def getUrls(self, qs):
        images = []
        index = 0
        while len(images) < 15:
            # Build a service object for interacting with the API. Visit
            # the Google APIs Console <http://code.google.com/apis/console>
            # to get an API key for your own application.
            try:
                service = build("customsearch",
                                "v1",
                                developerKey=self.creds['key'])
                query = qs[0] + " " + qs[1]
                startReq = index * 10

                Debug().p("query: %s index: %s" % (query, startReq))
                res = None
                start_time = time.time()
                if index == 0:
                    res = service.cse().list(
                        q=query,
                        cx=self.creds['cx'],
                        searchType='image',
                        safe='off',
                    ).execute()
                else:
                    res = service.cse().list(
                        q=query,
                        cx=self.creds['cx'],
                        searchType='image',
                        start=int(startReq),
                        safe='off',
                    ).execute()
                elapsed_time = time.time() - start_time
                if 'error' in res:
                    print "google responded with error message: ", pprint.pformat(
                        res)
                    time.sleep(60)
                    return []
                tst = 'items' in res
                if tst == False or len(res['items']) < 10:
                    Debug().p("rejecting too few items")
                    return []

                #Debug().p "res:",res
                for l in res['items']:
                    Debug().p("link %s" % l['link'])
                    relem = {}
                    relem['full'] = l['link']
                    relem['thumb'] = l['image']['thumbnailLink']
                    images.append(relem)

                index += 1

                Debug().p(res)

            except apiclient.errors.HttpError, e:
                print("google cse status:" + str(e.resp.status))
                if e.resp.status == 403:
                    print("Google Quota Exceeded")
                return None

            except:
 def __init__(self):
     self.debug = Debug()
     self.startLogo()
     self.startWarning()
     self.debug.letWait()
Exemplo n.º 10
0
 def __init__(self):
     self._db = Debug("country", False)
Exemplo n.º 11
0
            except apiclient.errors.HttpError, e:
                print("google cse status:" + str(e.resp.status))
                if e.resp.status == 403:
                    print("Google Quota Exceeded")
                return None

            except:
                print("google cse:" + str(sys.exc_info()[0]))
                return None

        return images


if __name__ == '__main__':
    from words import Words
    os.environ['DISPLAY'] = ":0.0"
    os.chdir(os.path.dirname(sys.argv[0]))
    os.chdir("..")  # sigh: get to default app path
    Debug(["__main__", "words"])
    Specs("%s/%s" % ("speclib", "commontest.json"))
    urls = Search().getUrls(Words().getWords())
    if urls == None:
        print "Google Error"
        exit(1)
    if len(urls) == 0:
        print "no urls!"
    for i in urls:
        print "full:", i['full']
        print "thumb:", i['thumb']
Exemplo n.º 12
0
def main():
    """Main program."""

    global dbg, cleanup_objects
    sensors = []
    itimer_next = {}

    # Initialize debugging
    dbg = Debug(level=DEBUG_LVL)
    cleanup_objects['debug'] = dbg

    # Initialize sensors
    for sensor in W1ThermSensor.get_available_sensors():
        sensors.append({
            'obj': sensor,
            'id_short': sensor.id[-4:],
            'value': None,
            'read_success': 0,
            'read_crc': 0,
            'read_nan': 0,
            'e_rate': 0
        })
    if len(sensors) == 0:
        sys.stderr.write('\nERROR: No sensors found\n')
        cleanup()
        exit(0)
    else:
        sys.stderr.write('\nINFO: Found {} sensors\n'.format(len(sensors)))
        active_sensor_idx = 0

    # Initialize LCD
    lcd = disp_init()
    cleanup_objects['lcd'] = lcd

    # Very first run
    for sensor in sensors:
        read_sensor(sensor)
    disp_clock(lcd)
    disp_sensor(lcd, sensors[active_sensor_idx])

    # Initialize signal file descriptor
    # We must set write end of pipe to non blocking mode
    # Also we don't want to block while read signal numbers from read end
    pipe_r, pipe_w = os.pipe()
    cleanup_objects['pipe_r'] = pipe_r
    cleanup_objects['pipe_w'] = pipe_w
    flags = fcntl.fcntl(pipe_w, fcntl.F_GETFL, 0)
    fcntl.fcntl(pipe_w, fcntl.F_SETFL, flags | os.O_NONBLOCK)
    signal.set_wakeup_fd(pipe_w)
    flags = fcntl.fcntl(pipe_r, fcntl.F_GETFL, 0)
    fcntl.fcntl(pipe_r, fcntl.F_SETFL, flags | os.O_NONBLOCK)

    # Redefine signal handlers
    cleanup_objects['sigalrm'] = signal.signal(signal.SIGALRM, signal_handler)
    cleanup_objects['sigint'] = signal.signal(signal.SIGINT, signal_handler)
    cleanup_objects['sighup'] = signal.signal(signal.SIGHUP, signal_handler)
    cleanup_objects['sigterm'] = signal.signal(signal.SIGTERM, signal_handler)

    # Create poller and register file descriptors
    poller = select.epoll()
    cleanup_objects['poller'] = poller
    poller.register(pipe_r, select.EPOLLIN)

    # Calculate interval timer value
    itimer_value = gcd(gcd(SENSOR_READ_INTERVAL, SENSOR_DISP_INTERVAL),
                       CLOCK_DISP_INTERVAL)
    dbg.dbg(
        'Calculated itimer interval value is {} seconds'.format(itimer_value))

    # Set interval timer
    # Initial value of timer bounded to measurement itimer_value
    t = time()
    t_rest = itimer_value - t % itimer_value
    #    if t_rest < 0:
    #        t_rest += itimer_value
    t_start = t_rest + ITIMER_START_SHIFT
    signal.setitimer(signal.ITIMER_REAL, t_start, itimer_value)
    cleanup_objects['itimer'] = True
    dbg.dbg('ITIMER_REAL will fire at {} and each {} seconds'.format(
        itimer_conv(t + t_start), itimer_value))

    # Set fire times
    t_base = t + t_rest
    dbg.dbg('  Base time is {}'.format(itimer_conv(t_base)))
    f = lambda x, y: x - x % y + y * ceil((x % y) / y)
    itimer_next['sensor_read_interval'] = f(t_base, SENSOR_READ_INTERVAL)
    dbg.dbg('  Wake up time for SENSOR_READ set to {}'.format(
        itimer_conv(itimer_next['sensor_read_interval'])))
    itimer_next['sensor_disp_interval'] = f(t_base, SENSOR_DISP_INTERVAL)
    dbg.dbg('  Wake up time for SENSOR_DISP set to {}'.format(
        itimer_conv(itimer_next['sensor_disp_interval'])))
    itimer_next['clock_disp_interval'] = f(t_base, CLOCK_DISP_INTERVAL)
    dbg.dbg('  Wake up time for CLOCK_DISP set to {}'.format(
        itimer_conv(itimer_next['clock_disp_interval'])))

    # Main loop
    sys.stderr.write('INFO: Entering main loop\n')
    while True:

        # Wait for events and process its
        try:
            events = poller.poll()
        except InterruptedError:
            continue
        for fd, flags in events:
            dbg.dbg('Start processing event, fd={}, flags={}'.format(
                fd, flags))

            # Signal received, extract signal numbers from wakeup fd
            if fd == pipe_r and flags & select.EPOLLIN:
                dbg.dbg(
                    'Signal received from wakeup fd, unpacking signal numbers')
                data = os.read(pipe_r, SIG_WAKEUP_FD_RLEN)
                signums = struct.unpack('{}B'.format(len(data)), data)
                dbg.dbg('Signal numbers unpacked: {}'.format(signums))

                # Make signal list have unique numbers only
                signums = set(signums)

                # Process signals
                for signum in signums:
                    if signum == signal.SIGALRM:
                        t = time()
                        dbg.dbg('Got SIGALRM, dispatch itimer based tasks')

                        # Display clock
                        if itimer_next['clock_disp_interval'] <= time():
                            dbg.dbg('Start CLOCK_DISP task')
                            disp_clock(lcd)
                            while itimer_next['clock_disp_interval'] <= time():
                                itimer_next[
                                    'clock_disp_interval'] += CLOCK_DISP_INTERVAL
                            dbg.dbg(
                                '  Wake up time for CLOCK_DISP set to {}'.
                                format(
                                    itimer_conv(
                                        itimer_next['clock_disp_interval'])))

                        # Read sensors
                        if itimer_next['sensor_read_interval'] <= t:
                            dbg.dbg('Start SENSOR_READ task')
                            for sensor in sensors:
                                read_sensor(sensor)
                            while itimer_next['sensor_read_interval'] <= time(
                            ):
                                itimer_next[
                                    'sensor_read_interval'] += SENSOR_READ_INTERVAL
                            dbg.dbg(
                                '  Wake up time for SENSOR_READ set to {}'.
                                format(
                                    itimer_conv(
                                        itimer_next['sensor_read_interval'])))

                        # Display sensor
                        if itimer_next['sensor_disp_interval'] <= t:
                            active_sensor = sensors[active_sensor_idx]
                            dbg.dbg(
                                'Start SENSOR_DISP task, sensor number {} id {}'
                                .format(active_sensor_idx,
                                        active_sensor['id_short']))
                            disp_sensor(lcd, active_sensor)
                            active_sensor_idx += 1
                            if active_sensor_idx >= len(sensors):
                                active_sensor_idx = 0
                            while itimer_next['sensor_disp_interval'] <= time(
                            ):
                                itimer_next[
                                    'sensor_disp_interval'] += SENSOR_DISP_INTERVAL
                            dbg.dbg(
                                '  Wake up time for SENSOR_DISP set to {}'.
                                format(
                                    itimer_conv(
                                        itimer_next['sensor_disp_interval'])))

                    elif signum == signal.SIGINT:
                        dbg.dbg('Got SIGINT, terminating')
                        sys.stderr.write('\nINFO: SIGINT received\n')
                        cleanup()
                        sys.exit(0)
                    elif signum == signal.SIGTERM:
                        dbg.dbg('Got SIGTERM, terminating')
                        sys.stderr.write('\nINFO: SIGTERM received\n')
                        cleanup()
                        sys.exit(0)
                    elif signum == signal.SIGHUP:
                        dbg.dbg('Got SIGHUP, ignoring')
                        sys.stderr.write('INFO: SIGHUP received\n')
                    else:
                        dbg.dbg(
                            'Got uncaught signal {}, ignoring'.format(signum))
                        sys.stderr.write(
                            'WARNING: Unexpected signal received: {}\n'.format(
                                signum))

            # Unexpected event
            else:
                dbg.dbg('Unexpected event on fd {}, flags {}'.format(
                    fd, flags))
                sys.stderr.write(
                    'ERROR: Unexpected event on fd {}, flags {}\n'.format(
                        fd, flags))
Exemplo n.º 13
0
 def nop(self,msg):
   Debug().p("%s: ignoring %s"%(self.name,msg))
Exemplo n.º 14
0
    print("max volume: %s" % hw['max'])
    volRat = float(hw['max']) / 100.0
    print("max volume: %s vol: %f volRat: %f" % (hw['max'], vol, volRat))
    cmdHdr = ["amixer", "-c", hw['Speaker'], "cget", "numid=3"]
    try:
        cmd = cmdHdr[:]
        output = check_output(cmd)
        lines = output.split("\n")
        for l in lines:
            if l.find(": values=") != -1:
                var = l.split("=")
                var = var[1].split(",")
                vol = int(round(float(var[0]) / volRat))

    except CalledProcessError as e:
        traceback.print_exc()
        print(e.output)

    return vol


if __name__ == '__main__':
    try:
        os.chdir(os.path.dirname(sys.argv[0]))
        Debug(['__main__'])
        makeRc()
        #setVolume(sys.argv[1])
        #print getVolume()
    except Exception, e:
        traceback.print_exc()
Exemplo n.º 15
0
from datetime import date
from json import dumps, loads
from requests import get as fetch
from debug import Debug
log = Debug()
'''
    class Symbols:
        functions:
            1. to provide symbols of all possible currencies as : symbol.symbols
            2. to provide rate data of all possible currencies : as symbol.data
            3. to privide full name of the currency: as symbol.name
            4. caching of datewise exchange values
'''


class CurrencyProvider:
    data = {}
    symbols = []
    names = {}

    def __init__(self):
        try:
            with open("currency.json") as file:
                self.names = {
                    key: value['name']
                    for (key, value) in loads(file.read()).items()
                }
        except:
            self.names = {}
        self.symbols = list(self.names.keys())
Exemplo n.º 16
0
    def initGUI(self):

        self.setAutoFillBackground(True)
        self.arguments = Arg_Class()
        p = self.palette()
        p.setColor(self.backgroundRole(), Qt.black)
        p.setColor(self.foregroundRole(), Qt.white)

        self.setPalette(p)
        ######################################################
        ###state machine starts here

        ## call function that sets the text of each of the startup screens based on what gpio signals are high

        ## once startup is complete call these to setup dash in race mode
        self.rpmGauge = Rpm(self)
        self.rpmGauge.move(0, 16.0)
        self.rpmGauge.resize(DASH_WIDTH, RPM_HEIGHT)

        #self.rpmGauge.hide()

        self.socGauge = Soc(self)
        self.socGauge.move(500, GAUGE_VPOS - 150.0)
        self.socGauge.resize(GAUGE_WIDTH, GAUGE_HEIGHT * 3.0)

        self.tempGauge = Temp(self)
        self.tempGauge.move(660, GAUGE_VPOS - 180.0)
        self.tempGauge.resize(GAUGE_WIDTH, GAUGE_HEIGHT * 2.5)
        self.tempGauge.show()

        self.debug = Debug(self)
        self.debugGps = DebugGPS(self)
        self.debug.hide()
        self.debugGps.hide()

        self.errorGauge = Error(self)
        self.errorGauge.move(20, 340)
        self.errorGauge.resize(GAUGE_WIDTH * 2.5, GAUGE_HEIGHT)
        self.errorGauge.show()

        if self.arguments.Args.debug:
            self.debug.show()

        #### if an error is thrown enter error state machine defined here

        ######################################################
        #### if possible move this so its always visiable, even during startup
        #### It would be a good idea to setup a menu option to skip the startup screens
        self.mainMenu = self.menuBar()
        self.mainMenu.setStyleSheet(
            "QMenuBar::item { color: rgb(255,0,0);}")  #sets text color
        self.mainMenu.setStyleSheet(
            "QMenuBar::item { background-color: rgb(255,255,255);}"
        )  # sets button color

        self.fileMenu = self.mainMenu.addMenu('Debug')
        self.openDebug = QAction("Open Debug Window", self)
        self.fileMenu.addAction(self.openDebug)
        self.openDebug.triggered.connect(self.debug.debug_open)

        self.openGPS = QAction("Open GPS Window", self)
        self.fileMenu.addAction(self.openGPS)
        self.openGPS.triggered.connect(self.debugGps.debug_open)

        #### Option to display graphs of data, not implemented yet
        self.analyzeMenu = self.mainMenu.addMenu('Analyze')
        self.graphRpm = QAction("Graph RPM", self)
        self.graphSoc = QAction("Graph SOC", self)
        self.analyzeMenu.addAction(self.graphRpm)
        self.analyzeMenu.addAction(self.graphSoc)

        self.tempMenu = self.mainMenu.addMenu('Temp')
        self.settingMenu = self.mainMenu.addMenu('Settings')
        ### Open temp dispaly
        self.tempOn = QAction("Open Temp Display:", self)
        self.settingMenu.addAction(self.tempOn)
        self.tempOn.triggered.connect(self.temp_open)
        ### Close temp display
        self.tempOff = QAction("Close Temp Display:", self)
        self.settingMenu.addAction(self.tempOff)
        self.tempOff.triggered.connect(self.temp_close)

        if self.arguments.Args.debug:
            #self.debug.show()
            self.debugGps.show()
Exemplo n.º 17
0
 def add(self, t):
     Debug().p("%s adding %s" % (self.name, t.name))
     self.feed(t)
Exemplo n.º 18
0
# Written by aquova, 2020
# https://github.com/aquova/governor

import discord
import db, commands, events, games, utils, xp
from config import CMD_PREFIX, DISCORD_KEY, GAME_ANNOUNCEMENT_CHANNEL, XP_OFF
from debug import Debug
from slowmode import Thermometer
from tracker import Tracker

client = discord.Client()

db.initialize()
tr = Tracker()
cc = commands.CustomCommands()
dbg = Debug()
game_timer = games.GameTimer()
thermo = Thermometer()

# Dictionary of function pointers
# Maps commands to functions that are called by them
FUNC_DICT = {
    "addgame": games.add_game,
    "addxp": tr.add_xp,
    "cleargames": games.clear_games,
    "custom": commands.print_help,
    "define": cc.define_cmd,
    "edit": commands.edit,
    "getgames": games.get_games,
    "help": commands.print_help,
    "lb": commands.show_lb,
Exemplo n.º 19
0
from protocol import Protocol
from utils import singleton
from settings import DEBUG_MODE
from abstract import AGame

@singleton
class Gomoku(AGame):
  def __init__(self):
    self.is_running = False
    self.board = Board()
    self.brain = Brain(self.board)
    self.protocol = Protocol(self)
    self.informations = dict()

  def start(self):
    self.is_running = True

    while self.is_running:
      self.protocol.launch_next_command()

  def stop(self):
    self.is_running = False

if __name__ == '__main__':
    if DEBUG_MODE:
      from debug import Debug
      threading.Thread(target=Gomoku.start).start()
      Debug(Gomoku).start()
    else:
      Gomoku.start()
Exemplo n.º 20
0
from default import Default
from database import Database
from waterlevel import Waterlevel
from light import Light
from curtain import Curtain
from pressure import Pressure
from temperature import Temperature
from redox import Redox
from ph import PH
from robot import Robot
from pump import Pump
from panel import Panel
from statistic import Statistic

from debug import Debug
debug = Debug(Debug.DEBUG)  # ERROR DEBUG DUMP


class Manager:
    AUTO_START_GPIO_PIN = 16
    ONCE_BY_HOUR_TICK = 360  # 1h

    def __init__(self, refPath, dataPath, dbFilename):
        GPIO.cleanup()
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(self.AUTO_START_GPIO_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP)
        self.__i2c = I2C(2)
        self.__analog = Analog(sel.__i2c.getLock(), 0x49)
        self.default = Default()
        self.database = Database(dataPath, dbFilename)
        self.waterlevel = Waterlevel(debug, self.database)
Exemplo n.º 21
0
 def haltRecog(self,cmd):
   Debug().p("halting recog")
   self.queue.put("__halt__")
   return Hosts.jsonStatus("ok")
Exemplo n.º 22
0
 def __init__(self, data=None, size=2**10):
     self.data = data if data else [' '] * size
     self.size = len(self.data)
     self.debug = Debug()
Exemplo n.º 23
0
def enable(val):
  global enabled
  playerMutex.acquire()
  enabled = val
  playerMutex.release()
  Debug().p("player enabled:"+str(enabled))
Exemplo n.º 24
0
 def __init__(self, data=None, size=2**10):
     self.data = data if data else [0] * (size >> 2)
     self.size = (len(self.data) << 2)
     self.debug = Debug()
Exemplo n.º 25
0
    def __init__(self, settings):
        # GLOBAL VARIABLES
        self.settings = settings


        #application paths
        self.apps = {'fop':'fop/fop/fop',
                     'saxon': 'tools/saxon-he/saxon9he.jar',
                     'ah':'/usr/AHFormatterV61_64/run.sh',
                     'xep':'/usr/local/xep/bin/xep/xep'

                     }


        # projects
        self.PROJECT_INPUT_FILE_JSON_IS_NOT_VALID = 'project input file json is not valid'
        self.PROJECT_INPUT_FILE_TYPE_IS_NOT_SPECIFIED = 'project input file type is not specified'
        self.PROJECT_INPUT_FILE_HAS_MORE_THAN_TWO_DOTS = 'project input file has more than two dots'
        self.PROJECT_INPUT_FILE_DOES_NOT_EXIST = 'project input_file does not exist'
        self.PROJECT_IS_NOT_ACTIVE = 'project is not active'
        self.PROJECT_OUTPUT_FILE_IS_NOT_DEFINED = 'project output file is not defined'
        self.PROJECT_OUTPUT_FILE_TYPE_IS_NOT_SPECIFIED = 'project output file type is not defined'
        self.PROJECT_OUTPUT_FILE_WAS_NOT_CREATED = 'project output file was not created'
        self.PROJECT_TYPESETTER_IS_NOT_AVAILABLE = 'project typesetter is not available'
        self.PROJECT_TYPESETTER_IS_NOT_SPECIFIED = 'project typesetter is not specified'
        self.PROJECT_TYPESETTER_NAME_IS_NOT_SPECIFIED = 'project typesetter name is not specified'
        self.PROJECT_TYPESETTER_VAR_IS_NOT_SPECIFIED = 'project typesetter varaible is not specified'
        self.PROJECT_TYPESETTERS_ARE_NOT_SPECIFIED = 'project typesetters are not specified'
        self.PROJECTS_VAR_IS_NOT_SPECIFIED = 'project variable is not  specified'
        self.PROJECT_TYPESETTER_PROCESS_METHOD_NOT_SPECIFIED='project typesetter process method not specified'
        self.PROJECTS_TYPESETTER_RUNS_WITH_NO_ARGUMENTS = 'projects typesetter runs with no arguments'


        # typesetter errors
        self.TYPESETTER_ARGUMENTS_NOT_DEFINED = "typesetter arguments not defined"
        self.TYPESETTER_EXECUTABLE_VARIABLE_IS_UNDEFINED = 'typesetter executable variable is undefined'
        self.TYPESETTER_FILE_OUTPUT_TYPE_IS_UNDEFINED = 'typesetter file output type is undefined'
        self.TYPESETTER_METADATA_FILE_WAS_NOT_SPECIFIED = 'Metadata file wasn\'t specified '
        self.TYPESETTER_METYPESET_RUNS_WITH_DEFAULT_METADATA_FILE = 'typesetter metypeset runs with default metadata file'
        self.TYPESETTER_IS_NOT_SPECIFIED = 'typesetter is not specified '
        self.TYPESETTER_PATH_IS_NOT_SPECIFIED = 'typesetter path is not specified '
        self.TYPESETTER_BINARY_IS_UNAVAILABLE = 'typesetter binary is unavailable '
        self.TYPESETTER_RUNS_WITH_NO_ARGUMENTS = 'typesetter runs with no arguments'

        # xml
        self.RUNNING_FO_CONVERSION = 'running FO conversion'
        self.RUNNING_PDF_CONVERSION = 'running PDF conversion'
        self.XML_ELEMENT_NOT_FOUND = 'xml element not found'
        self.XML_FILE_NOT_CREATED = 'xml file not created'
        self.XML_INPUT_FILE_IS_NOT_FOUND = 'xml input file is not found'
        self.XML_INPUT_FILE_IS_NOT_VALID = 'xml input file is not valid'
        self.SAXON_IS_NOT_AVAILABLE = 'saxon is not available'
        self.FOP_PATH_IS_NOT_AVAILABLE='fop path is not available'

        # WORDS
        self.OUTPUT = 'Output'

        self.debug = Debug()
        self.numeral_map = numeral_map

        #LOG Object
        self.log= []

        self.uuid = 'mpt'
        self.version = '0.0.1'
Exemplo n.º 26
0
                        nargs=1,
                        help='specify spec file',
                        required=True)
    parser.add_argument('-o',
                        '--output',
                        action='store_true',
                        help='save session to GardenTakes directory')
    args = parser.parse_args()
    specFile = args.spec[0]
    print("using spec:", specFile)
    specs = Specs(specFile)
    if args.output:
        makeTakesDir()
    print("takesDir:", takesDir)

    Debug().enable(specs.s['debug'])

    pygame.mixer.pre_init(frequency=44100, size=-16, channels=2, buffer=4096)
    pygame.init()
    SoundFile().setCurrentCollection()

    gardenTrack.TrackManager().changeNumGardenThreads(specs.s["numThreads"])
    threads = gardenTrack.TrackManager().eventThreads
    pulser = Pulser()
    pulser.setDaemon(True)
    pulser.start()

    pt = gardenPlayer.playerThread(threads)
    pt.setDaemon(True)
    pt.start()
    while True:
Exemplo n.º 27
0
                            logger.warn('ID只能输为数字')
                        elif input_id == '0':
                            exit()

                    browser_choice = ''
                    while not browser_choice.isdigit():
                        browser_choice = input(
                            '请选择要运行的浏览器(输入数字,回车):1、谷歌 2、IE 3、火狐 0-返回上级:')
                        if not browser_choice.isdigit():
                            logger.warn('只能输入数字')
                        elif browser_choice == '0':
                            break

                    if browser_choice == '1':
                        browser_choice = '谷歌'
                    elif browser_choice == '2':
                        browser_choice = 'IE'
                    elif browser_choice == '3':
                        browser_choice == '火狐'
                    elif browser_choice == '0':
                        continue

                    Debug().run(running_plan_num, input_id, browser_choice)

            except Exception as e:
                logger.error('%s' % e)
    except Exception as e:
        logger.error('运行出错:%s' % e)
    finally:
        test_platform_db.close()
Exemplo n.º 28
0
    def __init__(self):
        # Initialize pygame
        pygame.init()
        self.screen = pygame.display.set_mode((1280,720))

        # Global variables
        self.max_tps = 0
        self.max_fps = 30
        self.lifespan = 10000
        self.rockets = 100

        self.lifecount = 0
        self.environment = Environment(self)
        self.population = Population(self)
        self.debug = Debug(self)

        # Local variables
        self.running = True
        self.simulating = False

        self.tps_counter = 0
        self.tps_timer = 0
        self.tps_value = 0

        self.fps_counter = 0
        self.fps_timer = 0
        self.fps_value = 0

        self.sec_timer = 0

        # Main loop
        while self.running:
            # Get events
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE and not self.simulating:
                        self.simulating = True
                    elif event.key == pygame.K_d:
                        self.environment.obstructions = []
                    elif event.key == pygame.K_t:
                        self.environment.target = pygame.mouse.get_pos()
                    elif event.key == pygame.K_LEFTBRACKET:
                        if self.max_tps >= 100:
                            self.max_tps -= 100
                    elif event.key == pygame.K_RIGHTBRACKET:
                        self.max_tps += 100
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    if event.button == 1:
                        self.environment.make_obstruction(event.pos)

            if self.simulating:
                self.update()
            self.draw()

            # Performance statistics
            if time()-self.sec_timer >= 1.0:
                self.sec_timer = time()
                self.tps_value = self.tps_counter
                self.tps_counter = 0
                self.fps_value = self.fps_counter
                self.fps_counter = 0
Exemplo n.º 29
0
def service_shutdown(signum, frame):
    Debug().p('Caught signal %d' % signum)
    raise ServiceExit
Exemplo n.º 30
0
 def getLocalAttr(self,a):
   rval = self.getHost(self.getLocalHost())[a]
   Debug().p("Get Local Attr %s: %s"%(a,rval))
   return rval