コード例 #1
0
 def __call__(self, version, lower, upper):
     try:
         version = utils.version(version)
         lower = utils.version(lower)
         upper = utils.version(upper)
         return (version >= lower and version <= upper)
     except:
         import traceback
         traceback.print_exc()
         raise
コード例 #2
0
    def getHeaderInfo(self, element, name=None):
        log.debug("Getting info for the header...")

        # ACV FIX 20110301 - remove the auto injection of year in the copyright notice, y the notice already incluides the year
        aYearStr = str(time.localtime()[0])
        aCopyrightOrAuthor = self.getOption('copyright', element,
                                            self.copyright) or self.author
        if aYearStr in aCopyrightOrAuthor:
            copyright = COPYRIGHT_wo_year % aCopyrightOrAuthor
        else:
            copyright = COPYRIGHT % (aYearStr, aCopyrightOrAuthor)

        log.debug("Copyright = %r.", copyright)

        license = self.getLicenseInfo(element)
        authors, emails, authorline = self.getAuthors(element)

        if self.getOption('rcs_id', element, False):
            log.debug("Using id keyword.")
            filename_or_id = '$' + 'Id' + '$'
        else:
            log.debug("Using filename.")
            filename_or_id = 'File: %s.py' % (name or element.getModuleName())

        if self.getOption('generated_date', element, False):
            date = '# Generated: %s\n' % time.ctime()
        else:
            date = ''

        if utils.isTGVTrue(self.getOption('version_info', element, True)):
            log.debug("We want version info in every file.")
            versiontext = utils.version()
        elif element.__class__ == XMIParser.XMIModel:
            log.debug("We don't want version info in all files, "
                      "but we do want them in the config and Install.")
            versiontext = utils.version()
        else:
            log.debug("We don't want version info in this file.")
            versiontext = ''

        encoding = self.getOption('encoding', element, 'utf-8')
        log.debug("Encoding for python files is set to %s" % encoding)

        moduleinfo = {
            'authors': ', '.join(authors),
            'emails': ', '.join(emails),
            'authorline': authorline,
            'version': versiontext,
            'date': date,
            'copyright': '\n# '.join(utils.wrap(copyright, 77).split('\n')),
            'license': license,
            'filename_or_id': filename_or_id,
            'encoding': encoding,
        }
        return moduleinfo
コード例 #3
0
    def getHeaderInfo(self, element, name=None, all=0):
        log.debug("Getting info for the header...")

        encoding = self.getOption('encoding', element, 'utf-8')
        log.debug("Encoding for python files is set to %s" % encoding)
        
        authors, emails, authorline = self.getAuthors(element)
        copyright = COPYRIGHT.encode(encoding) % \
            (str(time.localtime()[0]),
             self.getOption('copyright', element, self.copyright) or
                 authorline)
        log.debug("Copyright = %r.", copyright)

        license = self.getLicenseInfo(element, all=all)

        if self.getOption('rcs_id', element, False):
            log.debug("Using id keyword.")
            filename_or_id = '$'+'Id'+'$'
        else:
            log.debug("Using filename.")
            filename_or_id = 'File: %s.py' % (name or element.getModuleName())

        if self.getOption('generated_date', element, False):
            date = '# Generated: %s\n' % time.ctime()
        else:
            date = ''

        if utils.isTGVTrue(self.getOption('version_info', element, True)):
            log.debug("We want version info in every file.")
            versiontext = utils.version()
        elif element.__class__ == xmiparser.XMIModel:
            log.debug("We don't want version info in all files, "
                      "but we do want them in the config and Install.")
            versiontext = utils.version()
        else:
            log.debug("We don't want version info in this file.")
            versiontext = ''
            
        moduleinfo = {
            'authors': ', '.join(authors),
            'emails': ', '.join(emails),
            'authorline': authorline,
            'version': versiontext,
            'date': date,
            'copyright': '\n# '.join(utils.wrap(copyright, 77).split('\n')),
            'license': license,
            'filename_or_id': filename_or_id,
            'encoding': encoding,
        }
        return moduleinfo
コード例 #4
0
ファイル: main.py プロジェクト: JBoggsy/chromabot
    def generate_markdown_report(self, loop_start):
        """
        Separate from the others as this logs to a sidebar rather than
        a file
        """
        s = self.session

        land_report = StatusCommand.lands_status_for(s, self.config)
        hq = self.reddit.get_subreddit(self.config.headquarters)

        cur = now()
        elapsed = (cur - loop_start) + self.config["bot"]["sleep"]
        version_str = version(self.config)

        bot_report = ("Bot Status:\n\n" "* Last run at %s\n\n" "* Seconds per Frame: %d\n\n" "* Version: %s") % (
            timestr(cur),
            elapsed,
            version_str,
        )

        report = "%s\n\n%s" % (land_report, bot_report)

        # This is apparently not immediately done, or there's some caching.
        # Keep an eye on it.
        hq.update_settings(description=report)
コード例 #5
0
def redeclipse(s=None):
    if s is None:
        s = {"version": defaultversion}
    if type(s) is str:
        s = {"version": s}
    if s["version"] in cache:
        return cache[s["version"]]
    version = utils.version(s["version"])
    for m, v in list(cfg.get('versions').items()):
        if (version >= utils.version(v[0]) and version <= utils.version(v[1])):
            cache[s["version"]] = importlib.import_module(
                "redeclipse.re%s" % m).RE()
            return cache[s["version"]]
    cache[s["version"]] = importlib.import_module(
        "redeclipse.re%s" % defaultversion).RE()
    return cache[s["version"]]
コード例 #6
0
ファイル: app.py プロジェクト: LauraTSD/hedy
def adventure_page(adventure_name, level):

    user = current_user(request)
    level = int(level)
    adventures = load_adventure_for_language(requested_lang())

    # If requested adventure does not exist, return 404
    if not adventure_name in adventures['adventures']:
        return 'No such Hedy adventure!', 404

    adventure = adventures['adventures'][adventure_name]

    # If no level is specified (this will happen if the last element of the path (minus the query parameter) is the same as the adventure_name)
    if re.sub(r'\?.+', '',
              request.url.split('/')[len(request.url.split('/')) -
                                     1]) == adventure_name:
        # If user is logged in, check if they have a program for this adventure
        # If there are many, note the highest level for which there is a saved program
        desired_level = 0
        if user['username']:
            existing_programs = DATABASE.programs_for_user(user['username'])
            for program in existing_programs:
                if 'adventure_name' in program and program[
                        'adventure_name'] == adventure_name and program[
                            'level'] > desired_level:
                    desired_level = program['level']
            # If the user has a saved program for this adventure, redirect them to the level with the highest adventure
            if desired_level != 0:
                return redirect(request.url.replace(
                    '/' + adventure_name,
                    '/' + adventure_name + '/' + str(desired_level)),
                                code=302)
        # If user is not logged in, or has no saved programs for this adventure, default to the lowest level available for the adventure
        if desired_level == 0:
            for key in adventure['levels'].keys():
                if isinstance(key, int) and (desired_level == 0
                                             or desired_level > key):
                    desired_level = key
        level = desired_level

    # If requested level is not in adventure, return 404
    if not level in adventure['levels']:
        abort(404)

    adventure_assignments = load_adventure_assignments_per_level(
        requested_lang(), level)
    g.prefix = '/hedy'
    return hedyweb.render_assignment_editor(
        request=request,
        course=HEDY_COURSE[requested_lang()],
        level_number=level,
        assignment_number=1,
        menu=render_main_menu('hedy'),
        translations=TRANSLATIONS,
        version=version(),
        adventure_assignments=adventure_assignments,
        # The relevant loaded program will be available to client-side js and it will be loaded by js.
        loaded_program='',
        adventure_name=adventure_name)
コード例 #7
0
ファイル: app.py プロジェクト: Tazaria/hedy
def save_program(user):

    body = request.json
    if not type_check(body, 'dict'):
        return 'body must be an object', 400
    if not object_check(body, 'code', 'str'):
        return 'code must be a string', 400
    if not object_check(body, 'name', 'str'):
        return 'name must be a string', 400
    if not object_check(body, 'level', 'int'):
        return 'level must be an integer', 400
    if 'adventure_name' in body:
        if not object_check(body, 'adventure_name', 'str'):
            return 'if present, adventure_name must be a string', 400

    name = body['name']

    # We check if a program with a name `xyz` exists in the database for the username.
    # It'd be ideal to search by username & program name, but since DynamoDB doesn't allow searching for two indexes at the same time, this would require to create a special index to that effect, which is cumbersome.
    # For now, we bring all existing programs for the user and then search within them for repeated names.
    programs = db_get_many('programs', {'username': user['username']}, True)
    program = {}
    overwrite = False
    for program in programs:
        if program['name'] == name:
            overwrite = True
            break

    stored_program = {
        'id': program.get('id') if overwrite else uuid.uuid4().hex,
        'session': session_id(),
        'date': timems(),
        'lang': requested_lang(),
        'version': version(),
        'level': body['level'],
        'code': body['code'],
        'name': name,
        'username': user['username']
    }

    if 'adventure_name' in body:
        stored_program['adventure_name'] = body['adventure_name']

    if overwrite:
        db_update('programs', stored_program)
    else:
        db_create('programs', stored_program)

    program_count = 0
    if 'program_count' in user:
        program_count = user['program_count']
    db_update('users', {
        'username': user['username'],
        'program_count': program_count + 1
    })

    return jsonify({'name': name})
コード例 #8
0
ファイル: app.py プロジェクト: TiBiBa/hedy
def index(level, step):


    # Sublevel requested
    if re.match ('\d+-\d+', level):
        pass
        # If level has a dash, we keep it as a string
    # Normal level requested
    elif re.match ('\d', level):
        try:
            g.level = level = int(level)
        except:
            return 'No such Hedy level!', 404
    else:
        return 'No such Hedy level!', 404

    g.lang = requested_lang()
    g.prefix = '/hedy'

    initialize_gfi_session(g.lang)

    loaded_program = ''
    loaded_program_name = ''
    adventure_name = ''

    # If step is a string that has more than two characters, it must be an id of a program
    if step and type_check (step, 'str') and len (step) > 2:
        result = db_get ('programs', {'id': step})
        if not result:
            return 'No such program', 404
        # If the program is not public, allow only the owner of the program, the admin user and the teacher users to access the program
        user = current_user (request)
        public_program = 'public' in result and result ['public']
        if not public_program and user ['username'] != result ['username'] and not is_admin (request) and not is_teacher (request):
            return 'No such program!', 404
        loaded_program = result ['code']
        loaded_program_name = result ['name']
        if 'adventure_name' in result:
            adventure_name = result ['adventure_name']
        # We default to step 1 to provide a meaningful default assignment
        step = 1

    adventure_assignments = load_adventure_assignments_per_level(g.lang, level)
    return hedyweb.render_assignment_editor(
        request=request,
        course=HEDY_COURSE[g.lang],
        level_number=level,
        assignment_number=step,
        menu=render_main_menu('hedy'),
        translations=TRANSLATIONS,
        version=version(),
        adventure_assignments=adventure_assignments,
        loaded_program=loaded_program,
        loaded_program_name=loaded_program_name,
        adventure_name=adventure_name)
コード例 #9
0
def report_client_exception():
    post_body = request.json

    querylog.log_value(session=session_id(),
                       date=str(datetime.datetime.now()),
                       client_error=post_body,
                       version=version(),
                       username=current_user(request)['username'] or None,
                       is_test=1 if os.getenv('IS_TEST_ENV') else None)

    return 'logged', 500
コード例 #10
0
def OSserver():
    user = ""
    password = ""
    ua = "kodi_%s_v%s" % (name().lower(), version())
    if boolsetting('OScustomuser'):
        if setting('OSuser') != '' or setting('OSpassword') != '':
            user = setting('OSuser')
            password = setting('OSpassword')
        else:
            user = "******"
            password = "******"
    return OpenSubtitles.LogIn(user, password, 'en', ua)
コード例 #11
0
def report_client_exception():
    post_body = request.json

    querylog.log_value(session=session_id(),
                       date=str(datetime.datetime.now()),
                       client_error=post_body,
                       version=version(),
                       username=current_user(request)['username'] or None,
                       is_test=1 if os.getenv('IS_TEST_ENV') else None)

    # Return a 500 so the HTTP status codes will stand out in our monitoring/logging
    return 'logged', 500
コード例 #12
0
ファイル: ArchGenXML.py プロジェクト: carrascoMDD/gvSIG-i18n
def main():
    utils.initLog('archgenxml.log')
    utils.addConsoleLogging()
    log = logging.getLogger('main')

    log.debug("Reading command line options first.")
    (settings, args) = parser.parse_args()
    try:
        model = args[0]
        log.debug("Model file is '%s'.", model)
    except:
        log.critical("Hey, we need to be passed a UML file as an argument!")
        parser.print_help()
        sys.exit(2)

    print utils.ARCHGENXML_VERSION_LINE % str(utils.version())

    # This is a little bit hacky. Probably should read optparse's doc
    # better. [Reinout]

    log.debug("Figuring out the settings we're passing to the "
              "main program...")
    keys = dir(settings)
    keys = [
        key for key in keys if not key.startswith('_')
        and not key in ['ensure_value', 'read_file', 'read_module']
    ]
    log.debug("Keys available through the option parser: %r.", keys)
    options = {}
    for key in keys:
        options[key] = getattr(settings, key)
        log.debug("Option '%s' has value '%s'.", key, options[key])

    # if outfilename is not given by the -o option try getting the second
    # regular argument
    if not options['outfilename']:
        log.debug("Outfilename not specified in the options. "
                  "Trying second loose commandline argument.")
        if len(args) > 1:
            options['outfilename'] = args[1]
        else:
            log.debug("No second argument found: keeping outfilename empty.")
            # the output dir will be named after the model

    # hook into sys.excepthook if the user requested it
    if options['pdb_on_exception']:
        sys.excepthook = info

    # start generation
    gen = ArchetypesGenerator(model, **options)
    gen.parseAndGenerate()
コード例 #13
0
def index(level, step):
    # Sublevel requested
    if re.match('\d+-\d+', level):
        pass
        # If level has a dash, we keep it as a string
    # Normal level requested
    elif re.match('\d', level):
        try:
            g.level = level = int(level)
        except:
            return 'No such Hedy level!', 404
    else:
        return 'No such Hedy level!', 404

    g.lang = requested_lang()
    g.prefix = '/hedy'

    loaded_program = ''
    adventure_name = ''

    # If step is a string that has more than two characters, it must be an id of a program
    if step and isinstance(step, str) and len(step) > 2:
        result = DATABASE.program_by_id(step)
        if not result:
            return 'No such program', 404
        # If the program is not public, allow only the owner of the program, the admin user and the teacher users to access the program
        user = current_user(request)
        public_program = 'public' in result and result['public']
        if not public_program and user['username'] != result[
                'username'] and not is_admin(request) and not is_teacher(
                    request):
            return 'No such program!', 404
        loaded_program = {
            'code': result['code'],
            'name': result['name'],
            'adventure_name': result.get('adventure_name')
        }
        if 'adventure_name' in result:
            adventure_name = result['adventure_name']

    adventures = load_adventures_per_level(g.lang, level)

    return hedyweb.render_code_editor_with_tabs(request=request,
                                                course=HEDY_COURSE[g.lang],
                                                level_number=level,
                                                menu=render_main_menu('hedy'),
                                                translations=TRANSLATIONS,
                                                version=version(),
                                                adventures=adventures,
                                                loaded_program=loaded_program,
                                                adventure_name=adventure_name)
コード例 #14
0
ファイル: app.py プロジェクト: Tazaria/hedy
def report_error():
    post_body = request.json

    parse_logger.log({
        'session': session_id(),
        'date': str(datetime.datetime.now()),
        'level': post_body.get('level'),
        'code': post_body.get('code'),
        'client_error': post_body.get('client_error'),
        'version': version(),
        'username': current_user(request)['username'] or None,
        'is_test': 1 if os.getenv('IS_TEST_ENV') else None
    })

    return 'logged'
コード例 #15
0
def onlinemasters(level, step):
    g.level = level = int(level)
    g.lang = lang = requested_lang()
    g.prefix = '/onlinemasters'

    adventures = load_adventures_per_level(g.lang, level)

    return hedyweb.render_code_editor_with_tabs(request=request,
                                                course=ONLINE_MASTERS_COURSE,
                                                level_number=level,
                                                translations=TRANSLATIONS,
                                                version=version(),
                                                menu=None,
                                                adventures=adventures,
                                                loaded_program='',
                                                adventure_name='')
コード例 #16
0
def space_eu(level, step):
    g.level = level = int(level)
    g.lang = requested_lang()
    g.prefix = '/space_eu'

    adventures = load_adventures_per_level(g.lang, level)

    return hedyweb.render_code_editor_with_tabs(request=request,
                                                course=HEDY_COURSE[g.lang],
                                                level_number=level,
                                                translations=TRANSLATIONS,
                                                version=version(),
                                                menu=None,
                                                adventures=adventures,
                                                loaded_program='',
                                                adventure_name='')
コード例 #17
0
def save_program(user):

    body = request.json
    if not isinstance(body, dict):
        return 'body must be an object', 400
    if not isinstance(body.get('code'), str):
        return 'code must be a string', 400
    if not isinstance(body.get('name'), str):
        return 'name must be a string', 400
    if not isinstance(body.get('level'), int):
        return 'level must be an integer', 400
    if 'adventure_name' in body:
        if not isinstance(body.get('adventure_name'), str):
            return 'if present, adventure_name must be a string', 400

    # We check if a program with a name `xyz` exists in the database for the username.
    # It'd be ideal to search by username & program name, but since DynamoDB doesn't allow searching for two indexes at the same time, this would require to create a special index to that effect, which is cumbersome.
    # For now, we bring all existing programs for the user and then search within them for repeated names.
    programs = DATABASE.programs_for_user(user['username'])
    program_id = uuid.uuid4().hex
    overwrite = False
    for program in programs:
        if program['name'] == body['name']:
            overwrite = True
            program_id = program['id']
            break

    stored_program = {
        'id': program_id,
        'session': session_id(),
        'date': timems(),
        'lang': requested_lang(),
        'version': version(),
        'level': body['level'],
        'code': body['code'],
        'name': body['name'],
        'username': user['username']
    }

    if 'adventure_name' in body:
        stored_program['adventure_name'] = body['adventure_name']

    DATABASE.store_program(stored_program)
    if not overwrite:
        DATABASE.increase_user_program_count(user['username'])

    return jsonify({'name': body['name'], 'id': program_id})
コード例 #18
0
ファイル: app.py プロジェクト: LauraTSD/hedy
def space_eu(level, step):
    g.level = level = int(level)
    g.lang = requested_lang()
    g.prefix = '/space_eu'

    adventure_assignments = load_adventure_assignments_per_level(g.lang, level)

    return hedyweb.render_assignment_editor(
        request=request,
        course=SPACE_EU_COURSE[g.lang],
        level_number=level,
        assignment_number=step,
        translations=TRANSLATIONS,
        version=version(),
        menu=None,
        adventure_assignments=adventure_assignments,
        loaded_program='',
        adventure_name='')
コード例 #19
0
ファイル: main.py プロジェクト: atiaxi/chromabot
    def generate_markdown_report(self, loop_start):
        """
        Separate from the others as this logs to a sidebar rather than
        a file
        """
        s = self.session

        land_report = StatusCommand.lands_status_for(s, self.config)
        hq = self.reddit.get_subreddit(self.config.headquarters)

        cur = now()
        elapsed = (cur - loop_start) + self.config["bot"]["sleep"]
        version_str = version(self.config)

        bot_report = ("Bot Status:\n\n"
                      "* Last run at %s\n\n"
                      "* Seconds per Frame: %d\n\n"
                      "* Version: %s") % (timestr(cur), elapsed, version_str)

        report = "%s\n\n%s" % (land_report, bot_report)

        # This is apparently not immediately done, or there's some caching.
        # Keep an eye on it.
        hq.update_settings(description=report)
コード例 #20
0
from utils import version
blueprint, api = version("v1")
from v1.restaurants import routes
from v1.visitors import routes
コード例 #21
0
ファイル: record-ffmpeg.py プロジェクト: krogsbell/wozboxntv
			#	cmd += ' --rtmp "' + rtmp + '"'
			#cmd += '"'
	
			nowHM=datetime.datetime.today().strftime('%H:%M')
		
			if LoopCount == 0 and not RecordingDisabled:
				utils.notification('Recording %s [COLOR green]started %s[/COLOR]' % (title, nowHM))
				recordings.updateRecordingPlanned(nameAlarm, '[COLOR green]Started ' + nowHM + '[/COLOR] ' + title)
				try:
					# Create file with info on recording 'infofilename'
					LF = open(infofilename, 'a')
					crlf = '\r\n'
					# Write to our text file the information we have provided and then goto next line in our file.
					LF.write('Recorded using: ' + ADDON.getAddonInfo('name')+ crlf)
					LF.write('Version= ' + ADDON.getAddonInfo('version')+ crlf)
					LF.write('Version Info= ' + utils.version()+ crlf)
					LF.write('Version Date= ' + utils.versiondate()+ crlf)
					program  = sys.argv[0]
					LF.write('Program Name= ' + program+ crlf)
					LF.write('Platform= ' + ADDON.getSetting('platform')+ crlf)
					LF.write('Running on= ' + ADDON.getSetting('runningon')+ crlf)
					LF.write('OS= ' + ADDON.getSetting('os')+ crlf)
					LF.write('Record Path= ' + ADDON.getSetting('record_path')+ crlf + crlf)
					LF.write('Record Command:' + crlf + cmd+ crlf + crlf)
					LF.write('Title= ' + title + crlf)
					LF.write('PlayChannel= ' + playchannel + crlf)
					LF.write('cat= ' + cat + crlf)
					LF.write('StartTime= ' + startTime + crlf)
					LF.write('EndTime= ' + endTime + crlf)
					LF.write('Duration= ' + str(int(round(int(duration)/60))) + ' minutes' + crlf)
					LF.write('Argv6= ' + argv6 + crlf)
コード例 #22
0
ファイル: service.py プロジェクト: krogsbell/wozboxntv
#!/usr/bin/python
# -*- coding: utf-8 -*-
import recordings, utils, locking
import xbmcaddon, xbmc, datetime
utils.log('service.py','Start')
#PLUGIN='plugin.video.wozboxntv'
#ADDON = xbmcaddon.Addon(id=PLUGIN)
#ADDON      = xbmcaddon.Addon(id='plugin.video.wozboxntv')
import definition
ADDON      = definition.getADDON()
#xbmc.log('service.py in %s' % ADDON.getAddonInfo('name'))
utils.log('Version',utils.version())	
utils.log('VersionDate',utils.versiondate())
try:
	Platform = utils.rtmpdumpFilename()
	if not Platform == '':
		utils.notification('[COLOR green]Platform found and set[/COLOR]')
except:
	pass
	utils.log('FindPlatform','FAILED')  # Put in LOG
locking.recordUnlockAll()
locking.scanUnlockAll()
recordings.backupSetupxml()
recordings.restoreLastSetupXml()
recordings.ftvntvlist()
ADDON.setSetting('allmessages','')
ADDON.setSetting('RecursiveSearch','false')
if ADDON.getSetting('enable_record')=='true':
	now = recordings.parseDate(datetime.datetime.now()) 
	startDate=now - datetime.timedelta(days = 10)
	endDate=now + datetime.timedelta(days = 100)
コード例 #23
0
ファイル: app.py プロジェクト: Tazaria/hedy
def parse():
    body = request.json
    if not body:
        return "body must be an object", 400
    if 'code' not in body:
        return "body.code must be a string", 400
    if 'level' not in body:
        return "body.level must be a string", 400
    if 'sublevel' in body and not type_check(body['sublevel'], 'int'):
        return "If present, body.sublevel must be an integer", 400
    if 'adventure_name' in body and not type_check(body['adventure_name'],
                                                   'str'):
        return "if present, body.adventure_name must be a string", 400

    code = body['code']
    level = int(body['level'])
    sublevel = body.get('sublevel') or 0

    # Language should come principally from the request body,
    # but we'll fall back to browser default if it's missing for whatever
    # reason.
    lang = body.get('lang', requested_lang())

    response = {}
    username = current_user(request)['username'] or None

    querylog.log_value(level=level,
                       lang=lang,
                       session_id=session_id(),
                       username=username)

    # Check if user sent code
    if not code:
        response["Error"] = "no code found, please send code."
    # is so, parse
    else:
        try:
            hedy_errors = TRANSLATIONS.get_translations(
                lang, 'HedyErrorMessages')
            with querylog.log_time('transpile'):
                result = hedy.transpile(code, level, sublevel)
            response["Code"] = "# coding=utf8\nimport random\n" + result
        except hedy.HedyException as E:
            traceback.print_exc()
            # some 'errors' can be fixed, for these we throw an exception, but also
            # return fixed code, so it can be ran
            if E.args[0] == "Invalid Space":
                error_template = hedy_errors[E.error_code]
                response[
                    "Code"] = "# coding=utf8\n" + E.arguments['fixed_code']
                response["Warning"] = error_template.format(**E.arguments)
            elif E.args[0] == "Parse":
                error_template = hedy_errors[E.error_code]
                # Localize the names of characters. If we can't do that, just show the original
                # character.
                if 'character_found' in E.arguments.keys():
                    E.arguments['character_found'] = hedy_errors.get(
                        E.arguments['character_found'],
                        E.arguments['character_found'])
                elif 'keyword_found' in E.arguments.keys():
                    #if we find an invalid keyword, place it in the same location in the error message but without translating
                    E.arguments['character_found'] = E.arguments[
                        'keyword_found']

                response["Error"] = error_template.format(**E.arguments)
            elif E.args[0] == "Unquoted Text":
                error_template = hedy_errors[E.error_code]
                response["Error"] = error_template.format(**E.arguments)
            else:
                error_template = hedy_errors[E.error_code]
                response["Error"] = error_template.format(**E.arguments)
        except Exception as E:
            traceback.print_exc()
            print(f"error transpiling {code}")
            response["Error"] = str(E)
    querylog.log_value(server_error=response.get('Error'))
    parse_logger.log({
        'session': session_id(),
        'date': str(datetime.datetime.now()),
        'level': level,
        'lang': lang,
        'code': code,
        'server_error': response.get('Error'),
        'version': version(),
        'username': username,
        'is_test': 1 if os.getenv('IS_TEST_ENV') else None,
        'adventure_name': body.get('adventure_name', None)
    })

    return jsonify(response)
コード例 #24
0
ファイル: SGMLtools.py プロジェクト: wsgan001/EventRanker
class SGMLtools:
    _globals = {}
    _classes = {}
    _autoconf = {}

    def __init__(self, autoconf):
        """Create an SGMLtools object.

	    This method hunts for backend modules and does some other
	    assorted initialization things. The autoconf argument
	    contains some assorted settings that are passed down from
	    autoconf.

	"""

        self._autoconf = autoconf

        #
        #  Expand path
        #
        sys.path.append(os.path.join(autoconf['shrdir'], 'python'))
        sys.path = sys.path + autoconf['backends']

        #
        #  Import backends, instantiate a BackendGlobals object for
        #  each of them, and stash it away.
        #
        files = []
        for dir in autoconf['backends']:
            pattern = os.path.join(dir, '*.py')
            files = files + glob.glob(pattern)
        for file in files:
            name, junk = os.path.splitext(file)
            dir, module = os.path.split(name)
            cmd = 'from %s import %s, %s' % (module, module,
                                             module + 'Globals')
            exec cmd
            cmd = 'glob = %sGlobals()' % module
            exec cmd
            self._globals[glob.getName()] = glob
            cmd = 'cls = %s' % module
            exec cmd
            self._classes[glob.getName()] = cls

        #
        #  Read alias file
        #
        self._aliases = utils.readAliases(autoconf)

        #
        #  Setup SGML environment
        #
        if not os.environ.has_key('SGML_CATALOG_FILES'):
            os.environ['SGML_CATALOG_FILES'] = \
          os.path.join(autoconf['etcdir'], 'catalog') \
                               + ":" + "/usr/share/sgml/stylesheets/sgmltools/sgmltools.cat" \
                               + ":" + "/usr/share/sgml/CATALOG.docbkdsl"

    def processOptions(self, args):
        """Process command line options.

	    Process command line options, dynamically expanding them
	    based on the --backend option, and returning the list of
	    files that's left.
	"""

        #
        #  Hunt down the backend option. The first test tests for
        #  "-b x", the second for "-bx" (or the equivalend long versions).
        #
        numArgs = len(args)
        for i in range(numArgs):
            arg = args[i]
            if arg in ["-b", "--backend"]:
                if i + 1 >= numArgs:
                    raise getopt.error, "option %s requires an argument" % arg
                miniargs = [arg, args[i + 1]]
                break
            if arg[:2] == "-b" or arg[:10] == "--backend=":
                miniargs = [arg]
                break
        else:
            #
            #  Default to the HTML backend.
            #
            miniargs = ["--backend=onehtml"]

        #
        #  We should have a backend option now. Ask getopt to parse it. Once
        #  we have it, ask the backend for extra options so we can get
        #  down to business.
        #
        opt, junk = getopt.getopt(miniargs, 'b:', ['backend='])
        #
        # if opt = 'txt', check for 'w3m' else fallback to 'lynx'
        #
        if opt[0][1] == "txt":
            if not self._autoconf['progs']['w3m'] == 'N/A':
                self._curbackend = "w3m"
            else:
                self._curbackend = "lynx"
        else:
            self._curbackend = opt[0][1]

        try:
            self._curglobal = self._globals[self._curbackend]
        except KeyError:
            utils.usage(None, "Unknown backend " + self._curbackend)
        if not self._globals.has_key(self._curbackend):
            utils.usage(None, "Unknown backend " + self._curbackend)

        #
        #  Merge all the options and parse them. Return whatever is
        #  left (the list of files we need to run).
        #
        shortopts, longopts = utils.makeOpts(self._curglobal)
        try:
            options, retval = getopt.getopt(args, shortopts, longopts)
        except getopt.error, e:
            utils.usage(self._curglobal, 'Error parsing arguments: ' + ` e `)

        self._options = utils.normalizeOpts(self._curglobal, options)

        #
        #  Check for help/version/... options
        #
        if utils.findOption(self._options, 'help'):
            utils.version(self._autoconf['shrdir'])
            print
            utils.usage(self._curglobal, None)
        if utils.findOption(self._options, 'version'):
            utils.version(self._autoconf['shrdir'])
            sys.exit(0)
        if utils.findOption(self._options, 'license'):
            utils.license()

        return retval
コード例 #25
0
from utils import version
blueprint,api=version("v2")
from v2.restaurants import routes
from v2.visitors import routes
コード例 #26
0
ファイル: OptionParser.py プロジェクト: collective/ArchGenXML
        if found == False:
            log.warn("Didn't find option '%s' (from the config file) in the list "
                     "of allowable options. Run ArchGenXML.py with the --help option "
                     "for information on allowable options.",
                     option_in_file)

#============================================================================
# ArchGenXML Parsing

usage = "usage: %prog [ options ] <xmi-source-file> [output directory]"
description = """A program for generating Archetypes from XMI files.
The xmi file can either be an exported *.xmi file or a Poseidon or ArgoUML
*.zuml file.
"""

version_string = "%prog " + utils.version()

parser = AGXOptionParser(usage=usage,
                         description=description,
                         version=version_string)

parser.add_option("-o",
                  "--outfile",
                  dest="outfilename",
                  metavar="PATH",
                  help="Output directory in which to put everything",
                  section="GENERAL",
                  default='',
                  )

parser.add_option("-p",
コード例 #27
0
            log.warn(
                "Didn't find option '%s' (from the config file) in the list "
                "of allowable options. Run ArchGenXML.py with the --help option "
                "for information on allowable options.", option_in_file)


#============================================================================
# ArchGenXML Parsing

usage = "usage: %prog [ options ] <xmi-source-file> [output directory]"
description = """A program for generating Archetypes from XMI files.
The xmi file can either be an exported *.xmi file or a Poseidon or ArgoUML
*.zuml file.
"""

version_string = "%prog " + utils.version()

parser = AGXOptionParser(usage=usage,
                         description=description,
                         version=version_string)

parser.add_option(
    "-o",
    "--outfile",
    dest="outfilename",
    metavar="PATH",
    help="Output directory in which to put everything",
    section="GENERAL",
    default='',
)
コード例 #28
0
ファイル: app.py プロジェクト: TiBiBa/hedy
def save_program (user):

    body = request.json
    if not type_check (body, 'dict'):
        return 'body must be an object', 400
    if not object_check (body, 'code', 'str'):
        return 'code must be a string', 400
    if not object_check (body, 'name', 'str'):
        return 'name must be a string', 400
    if not object_check (body, 'level', 'int'):
        return 'level must be an integer', 400
    if 'adventure_name' in body:
        if not object_check (body, 'adventure_name', 'str'):
            return 'if present, adventure_name must be a string', 400

    # We execute the saved program to see if it would generate an error or not
    error = None
    try:
        hedy_errors = TRANSLATIONS.get_translations(requested_lang(), 'HedyErrorMessages')
        result = hedy.transpile(body ['code'], body ['level'])
    except hedy.HedyException as E:
        error_template = hedy_errors[E.error_code]
        error = error_template.format(**E.arguments)
    except Exception as E:
        error = str(E)

    name = body ['name']

    # If name ends with (N) or (NN), we strip them since it's very likely these addenda were added by our server to avoid overwriting existing programs.
    name = re.sub (' \(\d+\)$', '', name)
    # We check if a program with a name `xyz` exists in the database for the username. If it does, we exist whether `xyz (1)` exists, until we find a program `xyz (NN)` that doesn't exist yet.
    # It'd be ideal to search by username & program name, but since DynamoDB doesn't allow searching for two indexes at the same time, this would require to create a special index to that effect, which is cumbersome.
    # For now, we bring all existing programs for the user and then search within them for repeated names.
    existing = db_get_many ('programs', {'username': user ['username']}, True)
    name_counter = 0
    for program in existing:
        if re.match ('^' + re.escape (name) + '( \(\d+\))*', program ['name']):
            name_counter = name_counter + 1
    if name_counter:
        name = name + ' (' + str (name_counter) + ')'

    stored_program = {
        'id': uuid.uuid4().hex,
        'session': session_id(),
        'date': timems (),
        'lang': requested_lang(),
        'version': version(),
        'level': body ['level'],
        'code': body ['code'],
        'name': name,
        'server_error': error,
        'username': user ['username']
    }

    if 'adventure_name' in body:
        stored_program ['adventure_name'] = body ['adventure_name']

    db_create('programs', stored_program)

    program_count = 0
    if 'program_count' in user:
        program_count = user ['program_count']
    db_update('users', {'username': user ['username'], 'program_count': program_count + 1})

    return jsonify({'name': name})
コード例 #29
0
ファイル: ArchGenXML.py プロジェクト: collective/ArchGenXML
def main():
    starttime = time()
    # Import zope here as we want to possibly inject an extra
    # directory into the import path. Just depending on a zope in the
    # normal import path can easily mess up existing zope sites.
    

    log.debug("Reading command line options first.")
    (settings, args) = parser.parse_args()
    # Note: settings is all that the parser can recognize and parse
    # from the command line arguments. 'args' is everything else
    # that's left. The first (and probably only) left-over argument
    # should be the model file
    if len(args) > 0:
        model = args[0]
        log.debug("Model file is '%s'.", model)
    else:
        log.critical("Hey, we need to be passed a UML file as an argument!")
        parser.print_help()
        sys.exit(2)
    log.info(utils.ARCHGENXML_VERSION_LINE, str(utils.version(stripsvn=False)))
    # This is a little bit hacky. Probably should read optparse's doc
    # better. [Reinout]
    log.debug("Figuring out the settings we're passing to the "
              "main program...")
    keys = dir(settings)
    keys = [key for key in keys
            if not key.startswith('_')
            and not key in ['ensure_value', 'read_file', 'read_module']]
    log.debug("Keys available through the option parser: %r.",
              keys)
    options = {}
    for key in keys:
        options[key] = getattr(settings, key)
        log.debug("Option '%s' has value '%s'.",
                  key, options[key])

    # if outfilename is not given by the -o option try getting the second
    # regular argument
    if not options['outfilename']:
        log.debug("Outfilename not specified in the options. "
                  "Trying second loose commandline argument.")
        if len(args) > 1:
            options['outfilename'] = args[1]
        else:
            log.debug("No second argument found: keeping outfilename empty.")
            # the output dir will be named after the model

    # hook into sys.excepthook if the user requested it
    if options['pdb_on_exception']:
        sys.excepthook = info

    # start generation
    try:
        # for standalone use
        from ArchetypesGenerator import ArchetypesGenerator
    except ImportError:
        # if installed in site-packages:
        from archgenxml.ArchetypesGenerator import ArchetypesGenerator
    # Instead of passing these options to the generator (which uses it
    # to update it's self.__dict__, we ought to pass this along to a
    # utility that you can grab from anywhere.
    import utility
    from archgenxml.interfaces import IOptions
    optionsHolder = component.getUtility(IOptions, name='options')
    optionsHolder.storeOptions(options)
    gen = ArchetypesGenerator(model, **options)
    gen.parseAndGenerate()
    log.info('generator run took %1.2f sec.' % (time()-starttime))
コード例 #30
0
ファイル: app.py プロジェクト: TiBiBa/hedy
def parse():
    body = request.json
    if not body:
        return "body must be an object", 400
    if 'code' not in body:
        return "body.code must be a string", 400
    if 'level' not in body:
        return "body.level must be a string", 400
    if 'sublevel' in body and not type_check (body ['sublevel'], 'int'):
        return "If present, body.sublevel must be an integer", 400
    if 'adventure_name' in body and not type_check (body ['adventure_name'], 'str'):
        return "if present, body.adventure_name must be a string", 400

    code = body ['code']
    level = int(body ['level'])
    sublevel = body.get ('sublevel') or 0

    # Language should come principally from the request body,
    # but we'll fall back to browser default if it's missing for whatever
    # reason.
    lang = body.get('lang', requested_lang())
    querylog.log_value(level=level, lang=lang)

    response = {}
    username = current_user(request) ['username'] or None

    querylog.log_value(level=level, lang=lang, session_id=session_id(), username=username)

    # Check if user sent code
    if not code:
        response["Error"] = "no code found, please send code."
    # is so, parse
    else:
        try:
            hedy_errors = TRANSLATIONS.get_translations(lang, 'HedyErrorMessages')
            gradual_feedback = TRANSLATIONS.get_translations(lang, 'GradualFeedback')
            with querylog.log_time('transpile'):
                result = hedy.transpile(code, level,sublevel)
            response["Code"] = "# coding=utf8\nimport random\n" + result
            if gfi_support(lang):
                if not (('error_level' in session) or ('similar_code' in session)):
                    return 'session cookie must have error_level & similar_code set', 400
                response['prev_feedback_level'] = session['error_level']
                response['prev_similar_code'] = session['similar_code']
                session ['error_level'] = 0  # Code is correct: reset error_level back to 0

        except hedy.HedyException as E:
            traceback.print_exc()
            # some 'errors' can be fixed, for these we throw an exception, but also
            # return fixed code, so it can be ran
            if E.args[0] == "Invalid Space":
                error_template = hedy_errors[E.error_code]
                response["Code"] = "# coding=utf8\n" + E.arguments['fixed_code']
                response["Warning"] = error_template.format(**E.arguments)
            elif E.args[0] == "Parse":
                error_template = hedy_errors[E.error_code]
                # Localize the names of characters
                if 'character_found' in E.arguments:
                    E.arguments['character_found'] = hedy_errors[E.arguments['character_found']]
                response["Error"] = error_template.format(**E.arguments)
            elif E.args[0] == "Unquoted Text":
                error_template = hedy_errors[E.error_code]
                response["Error"] = error_template.format(**E.arguments)
            else:
                error_template = hedy_errors[E.error_code]
                response["Error"] = error_template.format(**E.arguments)
            if gfi_support(lang):
                response.update(gradual_feedback_model(code, level, gradual_feedback, lang, E, hedy_exception=True))

        except Exception as E:
            traceback.print_exc()
            print(f"error transpiling {code}")
            response["Error"] = str(E)
            if gfi_support(lang):
                response.update(gradual_feedback_model(code, level, gradual_feedback, lang, E, hedy_exception=False))
        if gfi_support(lang):
            session ['code'] = code

    querylog.log_value(server_error=response.get('Error'))
    parse_logger.log ({
        'session': session_id(),
        'date': str(datetime.datetime.now()),
        'level': level,
        'lang': lang,
        'code': code,
        'server_error': response.get('Error'),
        'version': version(),
        'username': username,
        'feedback_level': session['error_level'] if gfi_support (lang) else None,
        'GFM': True if gfi_support (lang) else False,
        'is_test': 1 if os.getenv('IS_TEST_ENV') else None,
        'adventure_name': body.get('adventure_name', None)
    })

    return jsonify(response)
コード例 #31
0
    async def on_message(client, message):
        global conn, c
        try:
            ignored = True

            now = datetime.now()
            #ligne = [now.year,now.month,now.day,now.hour,now.minute,now.second,str(message.author),str(message.channel.id),message.content]
            #c.execute("INSERT INTO logs VALUES (?,?,?,?,?,?,?,?,?)",ligne)
            #(annee, mois, jour, heure, minute, seconde, auteur, salon, message)
            #c.execute("INSERT INTO logs(annee, mois, jour, heure, minute, seconde, auteur, salon, message) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)",ligne)
            #conn.commit()

            # on ne veut pas (encore) que le bot se reponde a lui meme
            if (message.author == client.user or message.author.bot):
                # On stocke les messages envoyés par le bot, notamment pour éviter les doublons à 22h22
                ligne = [
                    now.year, now.month, now.day, now.hour, now.minute,
                    now.second,
                    str(message.author),
                    str(message.channel.id), message.content
                ]
                c.execute(
                    "INSERT INTO logs(annee, mois, jour, heure, minute, seconde, auteur, salon, message) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)",
                    ligne)
                conn.commit()
                return
            if doitEtreIgnore(str(message.channel.id)):
                print("Message posté dans un salon ignoré.")
                ignored = True
            #print(emoji.remove_emojis(message.content))
            elif str(message.channel.id) == CHANNEL_22H22_ID:
                if now.hour != int(hour22h22[:2]) or now.minute != int(
                        hour22h22[3:]):
                    print(now.hour, ":", now.minute, " != ", hour22h22[:2],
                          ":", hour22h22[3:])
                    await message.delete()
                ignored = False
            elif message.content.lower().startswith('.ignorechannel') and str(
                    message.author.id) == OWNERID:
                ajouterSalonAignorer(message.content[14:])
                await message.channel.send(
                    'Salon ajouté à la liste des salons à ignorer.')
                ignored = False
            elif message.content.lower().startswith(
                    '.showignoredchannels') and str(
                        message.author.id) == OWNERID:
                await message.channel.send(afficherSalonsIgnores(client))
                ignored = False
            elif (message.content.startswith('.ninja')):
                msgSent = await message.channel.send("~ninja~")
                await msgSent.delete()
                if (peutSupprimer(message.channel)):
                    await message.delete()
                print("Message supprimé")
                ignored = False
            elif ((str(message.author.id) == OWNERID)
                  and message.content.startswith('.ecrire')):
                messageAenvoyer = message.content[7:]
                if (peutSupprimer(message.channel)):
                    await message.delete()
                print("Envoi d'un message : ", messageAenvoyer)
                await message.channel.send(messageAenvoyer)
                ignored = False
            elif ((str(message.author.id) == OWNERID)
                  and message.content.startswith('.exec')
                  and (str(message.author.id) == OWNERID)):
                command = message.content[6:]
                print("Execution du code : ", message.content[6:])
                exec(command)
                ignored = False
            elif (message.content.startswith('.help')):
                print('Demande de help par  : {0.author.mention}. '.format(
                    message))
                await message.channel.send(utils.help())
                ignored = False
            elif (message.content.startswith('.version')):
                print('Demande de version par  : {0.author.mention}. '.format(
                    message))
                await message.channel.send(utils.version())
                ignored = False
            elif (
                (" tg " in message.content.lower()
                 or " tg" in message.content.lower() or "tg "
                 in message.content.lower() or message.content.lower() == "tg")
                    and str(message.channel.id)):
                await message.channel.send(utils.tg())
                ignored = False
            elif ("ping" in message.content.lower()
                  and not emoji.message_contains_emoji_with_ping(
                      message.content.lower()) and str(message.channel.id)):
                await message.channel.send("pong")
                ignored = False
            elif ((":weshalors:" in message.content.lower())
                  or ("wesh alors" in message.content.lower())):
                msg = 'Wesh alors' + ' {0.author.mention} !'.format(message)
                await message.channel.send(msg)
                ignored = False
            elif ((str(message.author.id) == OWNERID)
                  and (message.content.startswith('.close')
                       or message.content.startswith('.stop')
                       or message.content.startswith('.logout'))):
                conn.commit()
                conn.close()
                # a changer pour fonctionner avec postgresql
                #fichierAtransmettre = discord.File('discord.db')
                #await message.channel.send("Le bot va s'arreter. Voila les logs :",file=fichierAtransmettre)
                await message.channel.send("Au revoir :)")
                await client.close()
                ignored = False
            elif (client.user.mentioned_in(message)
                  and not message.mention_everyone):
                await message.channel.send(pleinDetoiles)
                ignored = False

            if (ignored):
                print("Message ignored :")
                print("Id du channel : ", message.channel.id)
                print("Auteur : ", message.author.name, " (",
                      message.author.id, ")")
                print("Message : ", message.content)

        except psycopg2.DatabaseError as databaseError:
            conn, c = utils.initDB()
            raise Exception(
                'Connexion avec la base de données interrompue. Reconnexion effectuée.'
            )
        except Exception as exception:
            print(exception)
            user = await client.fetch_user(OWNERID)
            await user.send(exception)
コード例 #32
0
def parse():
    body = request.json
    if not body:
        return "body must be an object", 400
    if 'code' not in body:
        return "body.code must be a string", 400
    if 'level' not in body:
        return "body.level must be a string", 400
    if 'adventure_name' in body and not isinstance(body['adventure_name'],
                                                   str):
        return "if present, body.adventure_name must be a string", 400

    code = body['code']
    level = int(body['level'])

    # Language should come principally from the request body,
    # but we'll fall back to browser default if it's missing for whatever
    # reason.
    lang = body.get('lang', requested_lang())

    # true if kid enabled the read aloud option
    read_aloud = body.get('read_aloud', False)

    response = {}
    username = current_user(request)['username'] or None

    querylog.log_value(level=level,
                       lang=lang,
                       session_id=session_id(),
                       username=username)

    try:
        hedy_errors = TRANSLATIONS.get_translations(lang, 'HedyErrorMessages')
        with querylog.log_time('transpile'):
            transpile_result = hedy.transpile(code, level)
            python_code = transpile_result.code
            has_turtle = transpile_result.has_turtle

        response['has_turtle'] = has_turtle
        if has_turtle:
            response["Code"] = textwrap.dedent("""\
            # coding=utf8
            import random, time, turtle
            t = turtle.Turtle()
            t.hideturtle()
            t.speed(0)
            t.penup()
            t.goto(50,100)
            t.showturtle()
            t.pendown()
            t.speed(3)
            """) + python_code
        else:
            response["Code"] = "# coding=utf8\nimport random\n" + python_code

    except hedy.InvalidSpaceException as ex:
        traceback.print_exc()
        response = invalid_space_error_to_response(ex, hedy_errors)
    except hedy.ParseException as ex:
        traceback.print_exc()
        response = parse_error_to_response(ex, hedy_errors)
    except hedy.HedyException as ex:
        traceback.print_exc()
        response = hedy_error_to_response(ex, hedy_errors)

    except Exception as E:
        traceback.print_exc()
        print(f"error transpiling {code}")
        response["Error"] = str(E)
    querylog.log_value(server_error=response.get('Error'))
    parse_logger.log({
        'session': session_id(),
        'date': str(datetime.datetime.now()),
        'level': level,
        'lang': lang,
        'code': code,
        'server_error': response.get('Error'),
        'version': version(),
        'username': username,
        'read_aloud': read_aloud,
        'is_test': 1 if os.getenv('IS_TEST_ENV') else None,
        'adventure_name': body.get('adventure_name', None)
    })

    return jsonify(response)