コード例 #1
0
ファイル: manager.py プロジェクト: bitvinci/skipsvaki_poc
def edit_language():
    """ Edit language file """
    #app = get_app()
    lang = ("zh-tw",T("Mandarin"))
    args = ['devicedb','languages',lang[0]+'.py']
    filename = '/'.join(args)
    response.title = args[-1]
    strings = read_dict(apath(filename, r=request))

    if '__corrupted__' in strings:
        form = SPAN(strings['__corrupted__'], _class='error')
        return dict(filename=filename, form=form)

    keys = sorted(strings.keys(), lambda x, y: cmp(
        unicode(x, 'utf-8').lower(), unicode(y, 'utf-8').lower()))
    rows = []
    rows.append(H2(T('Original/Translation')))

    for key in keys:
        name = md5_hash(key)
        s = strings[key]
        (prefix, sep, key) = key.partition('\x01')
        if sep:
            prefix = SPAN(prefix + ': ', _class='tm_ftag')
            k = key
        else:
            (k, prefix) = (prefix, '')

        _class = 'untranslated' if k == s else 'translated'

        if len(s) <= 40:
            elem = INPUT(_type='text', _name=name, value=s,
                         _size=70, _class=_class)
        else:
            elem = TEXTAREA(_name=name, value=s, _cols=70,
                            _rows=5, _class=_class)

        # Making the short circuit compatible with <= python2.4
        k = (s != k) and k or B(k)

        new_row = DIV( LABEL(prefix, k, _style="font-weight:normal;"),
                      CAT(elem, '\n', TAG.BUTTON(
                    T('delete'),
                    _onclick='return delkey("%s")' % name,
                    _class='btn' )), _id=name, _class='span6 well well-small')

        rows.append(DIV(new_row,_class="row-fluid"))
    rows.append(DIV(INPUT(_type='submit', _value=T('update'), _class="btn btn-primary"), _class='controls'))
    form = FORM(*rows)
    if form.accepts(request.vars, keepvalues=True):
        strs = dict()
        for key in keys:
            name = md5_hash(key)
            if form.vars[name] == chr(127):
                continue
            strs[key] = form.vars[name]
        write_dict(apath(filename, r=request), strs)
        session.flash = T('saved on UTC') + request.utcnow.strftime(" %Y-%m-%d %H:%M")
        redirect(URL(r=request, args=request.args))
    return dict(app=args[0], filename=filename, form=form, lang=lang)
コード例 #2
0
ファイル: default.py プロジェクト: tazjel/vtraffic
def __compute_mode( query, block_seconds=800, vertical_block_seconds=30, compare=False, use_cache=True):
	blocks_list = __get_blocks_scheduler (query, block_seconds, reset_cache=False)
	if (len(blocks_list) == 0):
		return  {'data': [],'label':'No matches', 'id':'mode_%s' %  block_seconds }

	key = 'mode_%s%s%s%s' % (block_seconds, vertical_block_seconds, compare, query)
	if len(key)>200:
		key = 'mode_%s' % md5_hash(key)
	# Cache the mode for each day, so we need to compute only the last day
	data = cache.ram( key, lambda: __wrapper_elaboration( blocks_list,
                                                          __mode,
                                                          block_seconds, 
                                                          vertical_block_seconds=vertical_block_seconds, 
                                                          compare=compare),  
                      time_expire=CACHE_TIME_EXPIRE)
	if compare:
		fdate = blocks_list[0][0][db.match.gathered_on_orig]
		label = fdate.strftime('%a %d, %b' )
	else:
		label = "Mode (%ss)" % block_seconds
	return {'data': data,'label':label, 'id':'mode_%s' %  block_seconds }
コード例 #3
0
ファイル: default.py プロジェクト: kaiwenqu/MedicalRecord
def mobile_prof_register():
    email = request.vars.email
    password = request.vars.password
    firstname = request.vars.firstname
    middlename = request.vars.middlename
    lastname = request.vars.lastname
    country = request.vars.country
    rows = db(db.prof.email==email).select()
    result = {}
    
    if len(rows) != 0:
        result['status'] = "exist"
        return response.json(result)
    
    return_result = TT.md5_hash(password)
    ret = db.prof.validate_and_insert(email=email, password=password, first_name=firstname, middle_name=middlename, last_name=lastname, md5=return_result, country=country)

    if ret.errors:
        result['status'] = "ERROR"
        return response.json(result)        
    else:
        result['status'] = "success"
        result['result'] = return_result   
        return response.json(result)
コード例 #4
0
ファイル: mail_spool.py プロジェクト: Afridocs/GlobaLeaks-0.1
path = os.path.join(projroot, 'globaleaks',
                    'applications', 'globaleaks', 'errors')

hashes = {}

### CONFIGURE HERE
ALLOW_DUPLICATES = True
### END CONFIGURATION

if settings.globals.debug_notification:
    for file in os.listdir(path):
        filename = os.path.join(path, file)

        if not ALLOW_DUPLICATES:
            file_data = open(filename, 'r').read()
            key = md5_hash(file_data)

            if key in hashes:
                continue

            hashes[key] = 1

        error = RestrictedError()
        error.load(request, request.application, filename)
        logger.debug("REQUEST-APP: %s" % dir(request))

        logger.debug("Sending email...")

        message = '<b>There has been an error on a node.</b><br>'
        message += '<h1>This is the trackback:</h1><br><pre>%s</pre><br><br><br>' % error.traceback
        message += "<h1>this is the environment:</h1><br>"
コード例 #5
0
ファイル: test_utils.py プロジェクト: leonelcamara/web2py
    def test_md5_hash(self):
        """ Tests the md5_hash function """

        data = md5_hash("web2py rocks")
        self.assertEqual(data, '79509f3246a2824dee64635303e99204')
コード例 #6
0
        pass

# ## CONFIGURE HERE
SLEEP_MINUTES = 5
ALLOW_DUPLICATES = False
global_settings.slack_hook = global_settings.slack_hook or \
    'https://hooks.slack.com/services/your_service'
# ## END CONFIGURATION

while 1:
    for file_name in os.listdir(path):
        if file_name == 'slack_errors.pickle':
            continue

        if not ALLOW_DUPLICATES:
            key = md5_hash(file_name)
            if key in hashes:
                continue
            hashes[key] = 1

        error = RestrictedError()

        try:
            error.load(request, request.application, file_name)
        except Exception as _:
            continue  # not an exception file?

        url = URL(a='admin',
                  f='ticket',
                  args=[request.application, file],
                  scheme=True)
コード例 #7
0
path = os.path.join(request.folder, 'errors')

db = SQLDB(DB_URI)
db.define_table('ticket', SQLField('app'), SQLField('name'),
                SQLField('date_saved', 'datetime'), SQLField('layer'),
                SQLField('traceback', 'text'), SQLField('code', 'text'))

hashes = {}

while 1:
    for file in os.listdir(path):
        filename = os.path.join(path, file)

        if not ALLOW_DUPLICATES:
            file_data = open(filename, 'r').read()
            key = md5_hash(file_data)

            if key in hashes:
                continue

            hashes[key] = 1

        error = RestrictedError()
        error.load(request, request.application, filename)

        modified_time = os.stat(filename)[stat.ST_MTIME]
        modified_time = datetime.datetime.fromtimestamp(modified_time)

        db.ticket.insert(app=request.application,
                         date_saved=modified_time,
                         name=file,
コード例 #8
0
def edit_language():
    """ Edit language file, copied from admin/controllers/default.py """
    import os
    import re
    import time
    from gluon.languages import (read_dict, write_dict, to_native)
    from gluon.utils import md5_hash
    if len(request.args) == 0:
        raise HTTP(400, "No language provided")
    if re.match(request.args[0], r'[^\w\.\-]') is None:
        filename = os.path.join(request.folder, "languages",
                                request.args[0] + ".py")
        if os.path.isfile(filename):
            response.title = "OneZoom language strings for " + request.args[0]
            strings = read_dict(filename)

            if '__corrupted__' in strings:
                form = SPAN(strings['__corrupted__'], _class='error')
                return dict(filename=filename, form=form)

            keys = sorted(strings.keys(), key=lambda x: to_native(x).lower())
            rows = []
            rows.append(H2(T('Original/Translation')))

            for key in keys:
                name = md5_hash(key)
                s = strings[key]
                (prefix, sep, key) = key.partition('\x01')
                if sep:
                    prefix = SPAN(prefix + ': ', _class='tm_ftag')
                    k = key
                else:
                    (k, prefix) = (prefix, '')

                _class = 'untranslated' if k == s else 'translated'
                if len(s) <= 40 and '\n' not in s:
                    elem = INPUT(_type='text',
                                 _name=name,
                                 value=s,
                                 _size=70,
                                 _class=_class)
                else:
                    elem = TEXTAREA(_name=name,
                                    value="\n" + s,
                                    _cols=80,
                                    _rows=5,
                                    _class=_class)

                # Making the short circuit compatible with <= python2.4
                k = (s != k) and k.replace('\n', '¶') or B(k.replace(
                    '\n', '¶'))
                new_row = DIV(
                    LABEL(prefix,
                          k,
                          _style="font-weight:normal; display:block;"),
                    CAT(
                        elem, '\n',
                        TAG.BUTTON(IMG(_src=URL("static", "images",
                                                "close_red.png"),
                                       _width="20",
                                       _height="20"),
                                   XML('&nbsp;'),
                                   T('Delete'),
                                   _onclick='return delkey("%s")' % name,
                                   _class='btn')),
                    _id=name,
                    _class='span6 well well-small')

                rows.append(DIV(new_row, _class="row-fluid"))
            rows.append(
                DIV(INPUT(_type='submit',
                          _value=T('Update'),
                          _class="btn btn-primary"),
                    _class='controls'))
            form = FORM(*rows)
            if form.accepts(request.vars, keepvalues=True):
                strs = dict()
                for key in keys:
                    name = md5_hash(key)
                    with warnings.catch_warnings(record=True) as w:
                        try:
                            if form.vars[name] == chr(127):
                                continue
                        except UnicodeWarning:
                            if form.vars[name] == oldchr(127):
                                continue
                    strs[key] = form.vars[name]
                write_dict(filename, strs)
                session.flash = T('file saved on %(time)s',
                                  dict(time=time.ctime()))
                redirect(URL(r=request, args=request.args))
            return dict(filename=filename, form=form)
コード例 #9
0
ファイル: validators.py プロジェクト: huiker/web2py
 def __call__(self, value):
     if self.key:
         return (hmac.new(self.key, value, sha512).hexdigest(), None)
     else:
         return (md5_hash(value), None)
コード例 #10
0
ファイル: tickets2slack.py プロジェクト: BuhtigithuB/web2py
        pass

# ## CONFIGURE HERE
SLEEP_MINUTES = 5
ALLOW_DUPLICATES = False
global_settings.slack_hook = global_settings.slack_hook or \
    'https://hooks.slack.com/services/your_service'
# ## END CONFIGURATION

while 1:
    for file_name in os.listdir(path):
        if file_name == 'slack_errors.pickle':
            continue

        if not ALLOW_DUPLICATES:
            key = md5_hash(file_name)
            if key in hashes:
                continue
            hashes[key] = 1

        error = RestrictedError()

        try:
            error.load(request, request.application, file_name)
        except Exception as _:
            continue  # not an exception file?

        url = URL(a='admin', f='ticket', args=[request.application, file],
                  scheme=True)
        payload = json.dumps(dict(text="Error in %(app)s.\n%(url)s" %
                                       dict(app=request.application, url=url)))
コード例 #11
0
ファイル: validators.py プロジェクト: dspiteself/web2py
 def __call__(self, value):
     if self.key:
         return (hmac.new(self.key, value, sha512).hexdigest(), None)
     else:
         return (md5_hash(value), None)
コード例 #12
0
ファイル: default.py プロジェクト: dspiteself/web2py
def edit():
    """ File edit handler """

    filename = '/'.join(request.args)

    # Try to discover the file type
    if filename[-3:] == '.py':
        filetype = 'python'
    elif filename[-5:] == '.html':
        filetype = 'html'
    elif filename[-4:] == '.css':
        filetype = 'css'
    elif filename[-3:] == '.js':
        filetype = 'js'
    else:
        filetype = 'text'

    # ## check if file is not there

    path = apath(filename)

    if request.vars.restore and os.path.exists(path + '.bak'):
        try:
            data = open(path + '.bak', 'r').read()
            data1 = open(path, 'r').read()
        except IOError:
            session.flash = 'Invalid action'
            redirect(URL(r=request, f='site'))

        file_hash = md5_hash(data)
        open(path, 'w').write(data)
        open(path + '.bak', 'w').write(data1)
        response.flash = T('file "%s" restored', filename)
    else:
        try:
            data = open(path, 'r').read()
        except IOError:
            session.flash = 'Invalid action'
            redirect(URL(r=request, f='site'))

        file_hash = md5_hash(data)

        if request.vars.file_hash and request.vars.file_hash != file_hash:
            session.flash = T('file changed on disk')
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            open(path + '.1', 'w').write(data)
            redirect(URL(r=request, f='resolve', args=request.args))
        elif request.vars.data:
            open(path + '.bak', 'w').write(data)
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            open(path, 'w').write(data)
            file_hash = md5_hash(data)
            response.flash = T('file saved on %(time)s',
                               dict(time=time.ctime()))

    data_or_restore = (request.vars.data or request.vars.restore)

    if data_or_restore and request.args[1] == 'modules':
        # Lets try to reload the modules
        try:
            mopath = '.'.join(request.args[2:])[:-3]
            exec 'import applications.%s.modules.%s' % (request.args[0], mopath)
            reload(sys.modules['applications.%s.modules.%s'
                    % (request.args[0], mopath)])
        except:
            response.flash = T('failed to reload module')

    edit_controller = None

    if filetype == 'html' and request.args >= 3:
        cfilename = os.path.join(request.args[0], 'controllers',
                                 request.args[2] + '.py')
        if os.path.exists(apath(cfilename)):
            edit_controller = URL(r=request, f='edit', args=[cfilename])

    if len(request.args) > 2 and request.args[1] == 'controllers':
        controller = (request.args[2])[:-3]
        functions = regex_expose.findall(data)
    else:
        (controller, functions) = (None, None)

    return dict(app=request.args[0],
                filename=filename,
                filetype=filetype,
                data=data,
                edit_controller=edit_controller,
                file_hash=file_hash,
                controller=controller,
                functions=functions)
コード例 #13
0
ファイル: default.py プロジェクト: dspiteself/web2py
def site():
    """ Site handler """

    myversion = request.env.web2py_version

    # Shortcut to make the elif statements more
    # legible
    file_or_appurl = request.vars.has_key('file') or \
                     request.vars.has_key('appurl')

    if request.vars.filename and not request.vars.has_key('file'):
        try:
            appname = cleanpath(request.vars.filename).replace('.', '_')
            path = apath(appname)
            os.mkdir(path)
            untar('welcome.tar', path)
            response.flash = T('new application "%(appname)s" created',
                               dict(appname=appname))
        except Exception:
            response.flash = \
                T('unable to create new application "%(appname)s"',
                  dict(appname=request.vars.filename))

    elif file_or_appurl and not request.vars.filename:
        msg = 'you must specify a name for the uploaded application'
        response.flash = T(msg)

    elif file_or_appurl and request.vars.filename:
        mkdir = False

        try:
            appname = cleanpath(request.vars.filename).replace('.', '_')
            tarname = apath('../deposit/%s.tar' % appname)

            if request.vars.appurl is not '':
                tarfile = urllib.urlopen(request.vars.appurl).read()
            elif request.vars.file is not '':
                tarfile = request.vars.file.file.read()

            open(tarname, 'wb').write(tarfile)
            path = apath(appname)
            os.mkdir(path)
            mkdir = True
            untar(tarname, path)
            fix_newlines(path)

            msg = 'application %(appname)s installed with md5sum: %(digest)s'
            response.flash = T(msg, dict(appname=appname,
                                         digest=md5_hash(tarfile)))
        except Exception:
            if mkdir:
                shutil.rmtree(path)

            msg = 'unable to install application "%(appname)s"'
            response.flash = T(msg, dict(appname=request.vars.filename))

    regex = re.compile('^\w+$')
    apps = sorted([(file.upper(), file) for file in os.listdir(apath())
                                        if regex.match(file)])
    apps = [item[1] for item in apps]

    return dict(app=None, apps=apps, myversion=myversion)
コード例 #14
0
ファイル: default.py プロジェクト: huiker/web2py
def site():
    """ Site handler """

    myversion = request.env.web2py_version

    # Shortcut to make the elif statements more
    # legible
    file_or_appurl = request.vars.has_key('file') or \
                     request.vars.has_key('appurl')

    if request.vars.filename and not request.vars.has_key('file'):
        try:
            appname = cleanpath(request.vars.filename).replace('.', '_')
            path = apath(appname)
            os.mkdir(path)
            untar('welcome.tar', path)
            response.flash = T('new application "%(appname)s" created',
                               dict(appname=appname))
        except Exception:
            response.flash = \
                T('unable to create new application "%(appname)s"',
                  dict(appname=request.vars.filename))

    elif file_or_appurl and not request.vars.filename:
        msg = 'you must specify a name for the uploaded application'
        response.flash = T(msg)

    elif file_or_appurl and request.vars.filename:
        mkdir = False

        try:
            appname = cleanpath(request.vars.filename).replace('.', '_')
            tarname = apath('../deposit/%s.tar' % appname)

            if request.vars.appurl is not '':
                tarfile = urllib.urlopen(request.vars.appurl).read()
            elif request.vars.file is not '':
                tarfile = request.vars.file.file.read()

            open(tarname, 'wb').write(tarfile)
            path = apath(appname)
            os.mkdir(path)
            mkdir = True
            untar(tarname, path)
            fix_newlines(path)

            msg = 'application %(appname)s installed with md5sum: %(digest)s'
            response.flash = T(msg,
                               dict(appname=appname, digest=md5_hash(tarfile)))
        except Exception:
            if mkdir:
                shutil.rmtree(path)

            msg = 'unable to install application "%(appname)s"'
            response.flash = T(msg, dict(appname=request.vars.filename))

    regex = re.compile('^\w+$')
    apps = sorted([(file.upper(), file) for file in os.listdir(apath())
                   if regex.match(file)])
    apps = [item[1] for item in apps]

    return dict(app=None, apps=apps, myversion=myversion)
コード例 #15
0
ファイル: test_utils.py プロジェクト: Br1an20/GameEventWeb
    def test_md5_hash(self):
        """ Tests the md5_hash function """

        data = md5_hash("web2py rocks")
        self.assertEqual(data, '79509f3246a2824dee64635303e99204')
コード例 #16
0
ファイル: default.py プロジェクト: huiker/web2py
def edit():
    """ File edit handler """

    filename = '/'.join(request.args)

    # Try to discover the file type
    if filename[-3:] == '.py':
        filetype = 'python'
    elif filename[-5:] == '.html':
        filetype = 'html'
    elif filename[-4:] == '.css':
        filetype = 'css'
    elif filename[-3:] == '.js':
        filetype = 'js'
    else:
        filetype = 'text'

    # ## check if file is not there

    path = apath(filename)

    if request.vars.restore and os.path.exists(path + '.bak'):
        try:
            data = open(path + '.bak', 'r').read()
            data1 = open(path, 'r').read()
        except IOError:
            session.flash = 'Invalid action'
            redirect(URL(r=request, f='site'))

        file_hash = md5_hash(data)
        open(path, 'w').write(data)
        open(path + '.bak', 'w').write(data1)
        response.flash = T('file "%s" restored', filename)
    else:
        try:
            data = open(path, 'r').read()
        except IOError:
            session.flash = 'Invalid action'
            redirect(URL(r=request, f='site'))

        file_hash = md5_hash(data)

        if request.vars.file_hash and request.vars.file_hash != file_hash:
            session.flash = T('file changed on disk')
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            open(path + '.1', 'w').write(data)
            redirect(URL(r=request, f='resolve', args=request.args))
        elif request.vars.data:
            open(path + '.bak', 'w').write(data)
            data = request.vars.data.replace('\r\n', '\n').strip() + '\n'
            open(path, 'w').write(data)
            file_hash = md5_hash(data)
            response.flash = T('file saved on %(time)s',
                               dict(time=time.ctime()))

    data_or_restore = (request.vars.data or request.vars.restore)

    if data_or_restore and request.args[1] == 'modules':
        # Lets try to reload the modules
        try:
            mopath = '.'.join(request.args[2:])[:-3]
            exec 'import applications.%s.modules.%s' % (request.args[0],
                                                        mopath)
            reload(sys.modules['applications.%s.modules.%s' %
                               (request.args[0], mopath)])
        except:
            response.flash = T('failed to reload module')

    edit_controller = None

    if filetype == 'html' and request.args >= 3:
        cfilename = os.path.join(request.args[0], 'controllers',
                                 request.args[2] + '.py')
        if os.path.exists(apath(cfilename)):
            edit_controller = URL(r=request, f='edit', args=[cfilename])

    if len(request.args) > 2 and request.args[1] == 'controllers':
        controller = (request.args[2])[:-3]
        functions = regex_expose.findall(data)
    else:
        (controller, functions) = (None, None)

    return dict(app=request.args[0],
                filename=filename,
                filetype=filetype,
                data=data,
                edit_controller=edit_controller,
                file_hash=file_hash,
                controller=controller,
                functions=functions)
コード例 #17
0
ファイル: manage.py プロジェクト: jrosindell/OneZoom
def edit_language():
    """ Edit language file, copied from admin/controllers/default.py """
    import os
    import re
    import time
    from gluon.languages import (read_dict, write_dict)
    from gluon.utils import md5_hash
    if len(request.args) == 0:
        raise HTTP(400 , "No language provided") 
    if re.match(request.args[0], r'[^\w\.\-]') is None:
        filename = os.path.join(request.folder,"languages",request.args[0] + ".py")
        if os.path.isfile(filename):
            response.title = "OneZoom language strings for " + request.args[0]
            strings = read_dict(filename)
        
            if '__corrupted__' in strings:
                form = SPAN(strings['__corrupted__'], _class='error')
                return dict(filename=filename, form=form)
        
            keys = sorted(strings.keys(), lambda x, y: cmp(
                unicode(x, 'utf-8').lower(), unicode(y, 'utf-8').lower()))
            rows = []
            rows.append(H2(T('Original/Translation')))
        
            for key in keys:
                name = md5_hash(key)
                s = strings[key]
                (prefix, sep, key) = key.partition('\x01')
                if sep:
                    prefix = SPAN(prefix + ': ', _class='tm_ftag')
                    k = key
                else:
                    (k, prefix) = (prefix, '')
        
                _class = 'untranslated' if k == s else 'translated'
                if len(s) <= 40 and '\n' not in s:
                    elem = INPUT(_type='text', _name=name, value=s,
                                 _size=70, _class=_class)
                else:
                    elem = TEXTAREA(_name=name, value="\n"+s, _cols=80,
                                    _rows=5, _class=_class)
        
                # Making the short circuit compatible with <= python2.4
                k = (s != k) and k.replace('\n','¶') or B(k.replace('\n','¶'))
                new_row = DIV(LABEL(prefix, k, _style="font-weight:normal; display:block;"),
                              CAT(elem, '\n', TAG.BUTTON(
                                  IMG(_src=URL("static","images","close_red.png"),_width="20",_height="20"), XML('&nbsp;'), T('Delete'),
                                  _onclick='return delkey("%s")' % name,
                                  _class='btn')), _id=name, _class='span6 well well-small')
        
                rows.append(DIV(new_row, _class="row-fluid"))
            rows.append(DIV(INPUT(_type='submit', _value=T('Update'), _class="btn btn-primary"), _class='controls'))
            form = FORM(*rows)
            if form.accepts(request.vars, keepvalues=True):
                strs = dict()
                for key in keys:
                    name = md5_hash(key)
                    if form.vars[name] == chr(127):
                        continue
                    strs[key] = form.vars[name]
                write_dict(filename, strs)
                session.flash = T('file saved on %(time)s', dict(time=time.ctime()))
                redirect(URL(r=request, args=request.args))
            return dict(filename=filename, form=form)