code
stringlengths
1
1.72M
language
stringclasses
1 value
# coding: utf8 EXPERIMENTAL_STUFF = True if EXPERIMENTAL_STUFF: if is_mobile: response.view = response.view.replace('default/', 'default.mobile/') response.menu = [] import re from gluon.admin import * from gluon.fileutils import abspath, read_file, write_file from gluon.utils import web2py_uuid from glob import glob import shutil import platform try: import git if git.__version__ < '0.3.1': raise ImportError("Your version of git is %s. Upgrade to 0.3.1 or better." % git.__version__) have_git = True except ImportError, e: have_git = False GIT_MISSING = 'Requires gitpython module, but not installed or incompatible version: %s' % e from gluon.languages import (read_possible_languages, read_dict, write_dict, read_plural_dict, write_plural_dict) if DEMO_MODE and request.function in ['change_password', 'pack', 'pack_custom','pack_plugin', 'upgrade_web2py', 'uninstall', 'cleanup', 'compile_app', 'remove_compiled_app', 'delete', 'delete_plugin', 'create_file', 'upload_file', 'update_languages', 'reload_routes', 'git_push', 'git_pull']: session.flash = T('disabled in demo mode') redirect(URL('site')) if not is_manager() and request.function in ['change_password', 'upgrade_web2py']: session.flash = T('disabled in multi user mode') redirect(URL('site')) if FILTER_APPS and request.args(0) and not request.args(0) in FILTER_APPS: session.flash = T('disabled in demo mode') redirect(URL('site')) if not session.token: session.token = web2py_uuid() def count_lines(data): return len([line for line in data.split('\n') if line.strip() and not line.startswith('#')]) def log_progress(app, mode='EDIT', filename=None, progress=0): progress_file = os.path.join(apath(app, r=request), 'progress.log') now = str(request.now)[:19] if not os.path.exists(progress_file): safe_open(progress_file, 'w').write('[%s] START\n' % now) if filename: safe_open(progress_file, 'a').write( '[%s] %s %s: %s\n' % (now, mode, filename, progress)) def safe_open(a, b): if DEMO_MODE and ('w' in b or 'a' in b): class tmp: def write(self, data): pass return tmp() return open(a, b) def safe_read(a, b='r'): safe_file = safe_open(a, b) try: return safe_file.read() finally: safe_file.close() def safe_write(a, value, b='w'): safe_file = safe_open(a, b) try: safe_file.write(value) finally: safe_file.close() def get_app(name=None): app = name or request.args(0) if app and (not MULTI_USER_MODE or is_manager() or db(db.app.name == app)(db.app.owner == auth.user.id).count()): return app session.flash = T('App does not exist or your are not authorized') redirect(URL('site')) def index(): """ Index handler """ send = request.vars.send if DEMO_MODE: session.authorized = True session.last_time = t0 if not send: send = URL('site') if session.authorized: redirect(send) elif request.vars.password: if verify_password(request.vars.password): session.authorized = True login_record(True) if CHECK_VERSION: session.check_version = True else: session.check_version = False session.last_time = t0 if isinstance(send, list): # ## why does this happen? send = str(send[0]) redirect(send) else: times_denied = login_record(False) if times_denied >= allowed_number_of_attempts: response.flash = \ T('admin disabled because too many invalid login attempts') elif times_denied == allowed_number_of_attempts - 1: response.flash = \ T('You have one more login attempt before you are locked out') else: response.flash = T('invalid password.') return dict(send=send) def check_version(): """ Checks if web2py is up to date """ session.forget() session._unlock(response) new_version, version_number = check_new_version(request.env.web2py_version, WEB2PY_VERSION_URL) if new_version == -1: return A(T('Unable to check for upgrades'), _href=WEB2PY_URL) elif new_version != True: return A(T('web2py is up to date'), _href=WEB2PY_URL) elif platform.system().lower() in ('windows', 'win32', 'win64') and os.path.exists("web2py.exe"): return SPAN('You should upgrade to version %s' % version_number) else: return sp_button(URL('upgrade_web2py'), T('upgrade now to %s') % version_number.split('-')[0]) def logout(): """ Logout handler """ session.authorized = None if MULTI_USER_MODE: redirect(URL('user/logout')) redirect(URL('index')) def change_password(): if session.pam_user: session.flash = T( 'PAM authenticated user, cannot change password here') redirect(URL('site')) form = SQLFORM.factory(Field('current_admin_password', 'password'), Field('new_admin_password', 'password', requires=IS_STRONG()), Field('new_admin_password_again', 'password'), _class="span4 well") if form.accepts(request.vars): if not verify_password(request.vars.current_admin_password): form.errors.current_admin_password = T('invalid password') elif form.vars.new_admin_password != form.vars.new_admin_password_again: form.errors.new_admin_password_again = T('no match') else: path = abspath('parameters_%s.py' % request.env.server_port) safe_write(path, 'password="%s"' % CRYPT()( request.vars.new_admin_password)[0]) session.flash = T('password changed') redirect(URL('site')) return dict(form=form) def site(): """ Site handler """ myversion = request.env.web2py_version # Shortcut to make the elif statements more legible file_or_appurl = 'file' in request.vars or 'appurl' in request.vars class IS_VALID_APPNAME(object): def __call__(self, value): if not re.compile('\w+').match(value): return (value, T('Invalid application name')) if not request.vars.overwrite and \ os.path.exists(os.path.join(apath(r=request), value)): return (value, T('Application exists already')) return (value, None) is_appname = IS_VALID_APPNAME() form_create = SQLFORM.factory(Field('name', requires=is_appname), table_name='appcreate') form_update = SQLFORM.factory(Field('name', requires=is_appname), Field('file', 'upload', uploadfield=False), Field('url'), Field('overwrite', 'boolean'), table_name='appupdate') form_create.process() form_update.process() if DEMO_MODE: pass elif form_create.accepted: # create a new application appname = cleanpath(form_create.vars.name) created, error = app_create(appname, request, info=True) if created: if MULTI_USER_MODE: db.app.insert(name=appname, owner=auth.user.id) log_progress(appname) session.flash = T('new application "%s" created', appname) redirect(URL('design', args=appname)) else: session.flash = \ DIV(T('unable to create application "%s"' % appname), PRE(error)) redirect(URL(r=request)) elif form_update.accepted: if (form_update.vars.url or '').endswith('.git'): if not have_git: session.flash = GIT_MISSING redirect(URL(r=request)) target = os.path.join(apath(r=request), form_update.vars.name) try: new_repo = git.Repo.clone_from(form_update.vars.url, target) session.flash = T('new application "%s" imported', form_update.vars.name) except git.GitCommandError, err: session.flash = T('Invalid git repository specified.') redirect(URL(r=request)) elif form_update.vars.url: # fetch an application via URL or file upload try: f = urllib.urlopen(form_update.vars.url) if f.code == 404: raise Exception("404 file not found") except Exception, e: session.flash = \ DIV(T('Unable to download app because:'), PRE(str(e))) redirect(URL(r=request)) fname = form_update.vars.url elif form_update.accepted and form_update.vars.file: fname = request.vars.file.filename f = request.vars.file.file else: session.flash = 'No file uploaded and no URL specified' redirect(URL(r=request)) if f: appname = cleanpath(form_update.vars.name) installed = app_install(appname, f, request, fname, overwrite=form_update.vars.overwrite) if f and installed: msg = 'application %(appname)s installed with md5sum: %(digest)s' if MULTI_USER_MODE: db.app.insert(name=appname, owner=auth.user.id) log_progress(appname) session.flash = T(msg, dict(appname=appname, digest=md5_hash(installed))) elif f and form_update.vars.overwrite: msg = 'unable to install application "%(appname)s"' session.flash = T(msg, dict(appname=form_update.vars.name)) else: msg = 'unable to install application "%(appname)s"' session.flash = T(msg, dict(appname=form_update.vars.name)) redirect(URL(r=request)) regex = re.compile('^\w+$') if is_manager(): apps = [f for f in os.listdir(apath(r=request)) if regex.match(f)] else: apps = [f.name for f in db(db.app.owner == auth.user_id).select()] if FILTER_APPS: apps = [f for f in apps if f in FILTER_APPS] apps = sorted(apps, lambda a, b: cmp(a.upper(), b.upper())) return dict(app=None, apps=apps, myversion=myversion, form_create=form_create, form_update=form_update) def report_progress(app): import datetime progress_file = os.path.join(apath(app, r=request), 'progress.log') regex = re.compile('\[(.*?)\][^\:]+\:\s+(\-?\d+)') if not os.path.exists(progress_file): return [] matches = regex.findall(open(progress_file, 'r').read()) events, counter = [], 0 for m in matches: if not m: continue days = -(request.now - datetime.datetime.strptime(m[0], '%Y-%m-%d %H:%M:%S')).days counter += int(m[1]) events.append([days, counter]) return events def pack(): app = get_app() try: if len(request.args) == 1: fname = 'web2py.app.%s.w2p' % app filename = app_pack(app, request, raise_ex=True) else: fname = 'web2py.app.%s.compiled.w2p' % app filename = app_pack_compiled(app, request, raise_ex=True) except Exception, e: filename = None if filename: response.headers['Content-Type'] = 'application/w2p' disposition = 'attachment; filename=%s' % fname response.headers['Content-Disposition'] = disposition return safe_read(filename, 'rb') else: session.flash = T('internal error: %s' % e) redirect(URL('site')) def pack_plugin(): app = get_app() if len(request.args) == 2: fname = 'web2py.plugin.%s.w2p' % request.args[1] filename = plugin_pack(app, request.args[1], request) if filename: response.headers['Content-Type'] = 'application/w2p' disposition = 'attachment; filename=%s' % fname response.headers['Content-Disposition'] = disposition return safe_read(filename, 'rb') else: session.flash = T('internal error') redirect(URL('plugin', args=request.args)) def pack_custom(): app = get_app() base = apath(app, r=request) if request.post_vars.file: files = request.post_vars.file files = [files] if not isinstance(files,list) else files fname = 'web2py.app.%s.w2p' % app try: filename = app_pack(app, request, raise_ex=True, filenames=files) except Exception, e: filename = None if filename: response.headers['Content-Type'] = 'application/w2p' disposition = 'attachment; filename=%s' % fname response.headers['Content-Disposition'] = disposition return safe_read(filename, 'rb') else: session.flash = T('internal error: %s' % e) redirect(URL(args=request.args)) def ignore(fs): return [f for f in fs if not ( f[:1] in '#' or f.endswith('~') or f.endswith('.bak'))] files = {} for (r,d,f) in os.walk(base): files[r] = {'folders':ignore(d),'files':ignore(f)} return locals() def upgrade_web2py(): dialog = FORM.confirm(T('Upgrade'), {T('Cancel'): URL('site')}) if dialog.accepted: (success, error) = upgrade(request) if success: session.flash = T('web2py upgraded; please restart it') else: session.flash = T('unable to upgrade because "%s"', error) redirect(URL('site')) return dict(dialog=dialog) def uninstall(): app = get_app() dialog = FORM.confirm(T('Uninstall'), {T('Cancel'): URL('site')}) dialog['_id'] = 'confirm_form' dialog['_class'] = 'well' for component in dialog.components: component['_class'] = 'btn' if dialog.accepted: if MULTI_USER_MODE: if is_manager() and db(db.app.name == app).delete(): pass elif db(db.app.name == app)(db.app.owner == auth.user.id).delete(): pass else: session.flash = T('no permission to uninstall "%s"', app) redirect(URL('site')) try: filename = app_pack(app, request, raise_ex=True) except: session.flash = T('unable to uninstall "%s"', app) else: if app_uninstall(app, request): session.flash = T('application "%s" uninstalled', app) else: session.flash = T('unable to uninstall "%s"', app) redirect(URL('site')) return dict(app=app, dialog=dialog) def cleanup(): app = get_app() clean = app_cleanup(app, request) if not clean: session.flash = T("some files could not be removed") else: session.flash = T('cache, errors and sessions cleaned') redirect(URL('site')) def compile_app(): app = get_app() c = app_compile(app, request) if not c: session.flash = T('application compiled') else: session.flash = DIV(T('Cannot compile: there are errors in your app:'), CODE(c)) redirect(URL('site')) def remove_compiled_app(): """ Remove the compiled application """ app = get_app() remove_compiled_application(apath(app, r=request)) session.flash = T('compiled application removed') redirect(URL('site')) def delete(): """ Object delete handler """ app = get_app() filename = '/'.join(request.args) sender = request.vars.sender if isinstance(sender, list): # ## fix a problem with Vista sender = sender[0] if 'nodelete' in request.vars: redirect(URL(sender, anchor=request.vars.id)) elif 'delete' in request.vars: try: full_path = apath(filename, r=request) lineno = count_lines(open(full_path, 'r').read()) os.unlink(full_path) log_progress(app, 'DELETE', filename, progress=-lineno) session.flash = T('file "%(filename)s" deleted', dict(filename=filename)) except Exception: session.flash = T('unable to delete file "%(filename)s"', dict(filename=filename)) redirect(URL(sender, anchor=request.vars.id2)) return dict(filename=filename, sender=sender) def delete(): """ Object delete handler """ app = get_app() filename = '/'.join(request.args) sender = request.vars.sender if isinstance(sender, list): # ## fix a problem with Vista sender = sender[0] dialog = FORM.confirm(T('Delete'), {T('Cancel'): URL(sender, anchor=request.vars.id)}) if dialog.accepted: try: full_path = apath(filename, r=request) lineno = count_lines(open(full_path, 'r').read()) os.unlink(full_path) log_progress(app, 'DELETE', filename, progress=-lineno) session.flash = T('file "%(filename)s" deleted', dict(filename=filename)) except Exception: session.flash = T('unable to delete file "%(filename)s"', dict(filename=filename)) redirect(URL(sender, anchor=request.vars.id2)) return dict(dialog=dialog, filename=filename) def enable(): app = get_app() filename = os.path.join(apath(app, r=request), 'DISABLED') if is_gae: return SPAN(T('Not supported'), _style='color:yellow') elif os.path.exists(filename): os.unlink(filename) return SPAN(T('Disable'), _style='color:green') else: safe_open(filename, 'wb').write(time.ctime()) return SPAN(T('Enable'), _style='color:red') def peek(): """ Visualize object code """ app = get_app(request.vars.app) filename = '/'.join(request.args) if request.vars.app: path = abspath(filename) else: path = apath(filename, r=request) try: data = safe_read(path).replace('\r', '') except IOError: session.flash = T('file does not exist') redirect(URL('site')) extension = filename[filename.rfind('.') + 1:].lower() return dict(app=app, filename=filename, data=data, extension=extension) def test(): """ Execute controller tests """ app = get_app() if len(request.args) > 1: file = request.args[1] else: file = '.*\.py' controllers = listdir( apath('%s/controllers/' % app, r=request), file + '$') return dict(app=app, controllers=controllers) def keepalive(): return '' def search(): keywords = request.vars.keywords or '' app = get_app() def match(filename, keywords): filename = os.path.join(apath(app, r=request), filename) if keywords in read_file(filename, 'rb'): return True return False path = apath(request.args[0], r=request) files1 = glob(os.path.join(path, '*/*.py')) files2 = glob(os.path.join(path, '*/*.html')) files3 = glob(os.path.join(path, '*/*/*.html')) files = [x[len(path) + 1:].replace( '\\', '/') for x in files1 + files2 + files3 if match(x, keywords)] return response.json(dict(files=files, message=T.M('Searching: **%s** %%{file}', len(files)))) def edit(): """ File edit handler """ # Load json only if it is ajax edited... app = get_app(request.vars.app) filename = '/'.join(request.args) response.title = request.args[-1] if request.vars.app: path = abspath(filename) else: path = apath(filename, r=request) # Try to discover the file type if filename[-3:] == '.py': filetype = 'python' elif filename[-5:] == '.html': filetype = 'html' elif filename[-5:] == '.load': filetype = 'html' elif filename[-4:] == '.css': filetype = 'css' elif filename[-3:] == '.js': filetype = 'js' else: filetype = 'html' # ## check if file is not there if ('revert' in request.vars) and os.path.exists(path + '.bak'): try: data = safe_read(path + '.bak') data1 = safe_read(path) except IOError: session.flash = T('Invalid action') if 'from_ajax' in request.vars: return response.json({'error': str(T('Invalid action'))}) else: redirect(URL('site')) safe_write(path, data) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) safe_write(path + '.bak', data1) response.flash = T('file "%s" of %s restored', (filename, saved_on)) else: try: data = safe_read(path) except IOError: session.flash = T('Invalid action') if 'from_ajax' in request.vars: return response.json({'error': str(T('Invalid action'))}) else: redirect(URL('site')) lineno_old = count_lines(data) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) 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' safe_write(path + '.1', data) if 'from_ajax' in request.vars: return response.json({'error': str(T('file changed on disk')), 'redirect': URL('resolve', args=request.args)}) else: redirect(URL('resolve', args=request.args)) elif request.vars.data: safe_write(path + '.bak', data) data = request.vars.data.replace('\r\n', '\n').strip() + '\n' safe_write(path, data) lineno_new = count_lines(data) log_progress( app, 'EDIT', filename, progress=lineno_new - lineno_old) file_hash = md5_hash(data) saved_on = time.ctime(os.stat(path)[stat.ST_MTIME]) response.flash = T('file saved on %s', saved_on) data_or_revert = (request.vars.data or request.vars.revert) # Check compile errors highlight = None if filetype == 'python' and request.vars.data: import _ast try: code = request.vars.data.rstrip().replace('\r\n', '\n') + '\n' compile(code, path, "exec", _ast.PyCF_ONLY_AST) except Exception, e: # offset calculation is only used for textarea (start/stop) start = sum([len(line) + 1 for l, line in enumerate(request.vars.data.split("\n")) if l < e.lineno - 1]) if e.text and e.offset: offset = e.offset - (len(e.text) - len( e.text.splitlines()[-1])) else: offset = 0 highlight = {'start': start, 'end': start + offset + 1, 'lineno': e.lineno, 'offset': offset} try: ex_name = e.__class__.__name__ except: ex_name = 'unknown exception!' response.flash = DIV(T('failed to compile file because:'), BR(), B(ex_name), ' ' + T('at line %s', e.lineno), offset and ' ' + T('at char %s', offset) or '', PRE(str(e))) if data_or_revert 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 Exception, e: response.flash = DIV( T('failed to reload module because:'), PRE(str(e))) edit_controller = None editviewlinks = None view_link = None if filetype == 'html' and len(request.args) >= 3: cfilename = os.path.join(request.args[0], 'controllers', request.args[2] + '.py') if os.path.exists(apath(cfilename, r=request)): edit_controller = URL('edit',args=[cfilename.replace(os.sep, "/")]) view = request.args[3].replace('.html', '') view_link = URL(request.args[0], request.args[2], view) elif filetype == 'python' and request.args[1] == 'controllers': ## it's a controller file. ## Create links to all of the associated view files. app = get_app() viewname = os.path.splitext(request.args[2])[0] viewpath = os.path.join(app, 'views', viewname) aviewpath = apath(viewpath, r=request) viewlist = [] if os.path.exists(aviewpath): if os.path.isdir(aviewpath): viewlist = glob(os.path.join(aviewpath, '*.html')) elif os.path.exists(aviewpath + '.html'): viewlist.append(aviewpath + '.html') if len(viewlist): editviewlinks = [] for v in viewlist: vf = os.path.split(v)[-1] vargs = "/".join([viewpath.replace(os.sep, "/"), vf]) editviewlinks.append(A(vf.split(".")[0], _href=URL('edit', args=[vargs]))) 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) if 'from_ajax' in request.vars: return response.json({'file_hash': file_hash, 'saved_on': saved_on, 'functions': functions, 'controller': controller, 'application': request.args[0], 'highlight': highlight}) else: editarea_preferences = {} editarea_preferences['FONT_SIZE'] = '10' editarea_preferences['FULL_SCREEN'] = 'false' editarea_preferences['ALLOW_TOGGLE'] = 'true' editarea_preferences['REPLACE_TAB_BY_SPACES'] = '4' editarea_preferences['DISPLAY'] = 'onload' for key in editarea_preferences: if key in globals(): editarea_preferences[key] = globals()[key] return dict(app=request.args[0], filename=filename, filetype=filetype, data=data, edit_controller=edit_controller, file_hash=file_hash, saved_on=saved_on, controller=controller, functions=functions, view_link=view_link, editarea_preferences=editarea_preferences, editviewlinks=editviewlinks) def resolve(): """ """ filename = '/'.join(request.args) # ## check if file is not there path = apath(filename, r=request) a = safe_read(path).split('\n') try: b = safe_read(path + '.1').split('\n') except IOError: session.flash = 'Other file, no longer there' redirect(URL('edit', args=request.args)) d = difflib.ndiff(a, b) def leading(line): """ """ # TODO: we really need to comment this z = '' for (k, c) in enumerate(line): if c == ' ': z += '&nbsp;' elif c == ' \t': z += '&nbsp;' elif k == 0 and c == '?': pass else: break return XML(z) def getclass(item): """ Determine item class """ if item[0] == ' ': return 'normal' if item[0] == '+': return 'plus' if item[0] == '-': return 'minus' if request.vars: c = '\n'.join([item[2:].rstrip() for (i, item) in enumerate(d) if item[0] == ' ' or 'line%i' % i in request.vars]) safe_write(path, c) session.flash = 'files merged' redirect(URL('edit', args=request.args)) else: # Making the short circuit compatible with <= python2.4 gen_data = lambda index, item: not item[:1] in ['+', '-'] and "" \ or INPUT(_type='checkbox', _name='line%i' % index, value=item[0] == '+') diff = TABLE(*[TR(TD(gen_data(i, item)), TD(item[0]), TD(leading(item[2:]), TT(item[2:].rstrip())), _class=getclass(item)) for (i, item) in enumerate(d) if item[0] != '?']) return dict(diff=diff, filename=filename) def edit_language(): """ Edit language file """ app = get_app() filename = '/'.join(request.args) response.title = request.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('file saved on %(time)s', dict(time=time.ctime())) redirect(URL(r=request, args=request.args)) return dict(app=request.args[0], filename=filename, form=form) def edit_plurals(): """ Edit plurals file """ app = get_app() filename = '/'.join(request.args) plurals = read_plural_dict( apath(filename, r=request)) # plural forms dictionary nplurals = int(request.vars.nplurals) - 1 # plural forms quantity xnplurals = xrange(nplurals) if '__corrupted__' in plurals: # show error message and exit form = SPAN(plurals['__corrupted__'], _class='error') return dict(filename=filename, form=form) keys = sorted(plurals.keys(), lambda x, y: cmp( unicode(x, 'utf-8').lower(), unicode(y, 'utf-8').lower())) tab_rows = [] for key in keys: name = md5_hash(key) forms = plurals[key] if len(forms) < nplurals: forms.extend(None for i in xrange(nplurals - len(forms))) tab_col1 = DIV(CAT(LABEL(T("Singular Form")), B(key, _class='fake-input'))) tab_inputs = [SPAN(LABEL(T("Plural Form #%s", n + 1)), INPUT(_type='text', _name=name + '_' + str(n), value=forms[n], _size=20), _class='span6') for n in xnplurals] tab_col2 = DIV(CAT(*tab_inputs)) tab_col3 = DIV(CAT(LABEL(XML('&nbsp;')), TAG.BUTTON(T('delete'), _onclick='return delkey("%s")' % name, _class='btn'), _class='span6')) tab_row = DIV(DIV(tab_col1, '\n', tab_col2, '\n', tab_col3, _class='well well-small'), _id=name, _class='row-fluid tab_row') tab_rows.append(tab_row) tab_rows.append(DIV(TAG['button'](T('update'), _type='submit', _class='btn btn-primary'), _class='controls')) tab_container = DIV(*tab_rows, **dict(_class="row-fluid")) form = FORM(tab_container) if form.accepts(request.vars, keepvalues=True): new_plurals = dict() for key in keys: name = md5_hash(key) if form.vars[name + '_0'] == chr(127): continue new_plurals[key] = [form.vars[name + '_' + str(n)] for n in xnplurals] write_plural_dict(apath(filename, r=request), new_plurals) session.flash = T('file saved on %(time)s', dict(time=time.ctime())) redirect(URL(r=request, args=request.args, vars=dict( nplurals=request.vars.nplurals))) return dict(app=request.args[0], filename=filename, form=form) def about(): """ Read about info """ app = get_app() # ## check if file is not there about = safe_read(apath('%s/ABOUT' % app, r=request)) license = safe_read(apath('%s/LICENSE' % app, r=request)) return dict(app=app, about=MARKMIN(about), license=MARKMIN(license), progress=report_progress(app)) def design(): """ Application design handler """ app = get_app() if not response.flash and app == request.application: msg = T('ATTENTION: you cannot edit the running application!') response.flash = msg if request.vars and not request.vars.token == session.token: redirect(URL('logout')) if request.vars.pluginfile is not None and not isinstance(request.vars.pluginfile, str): filename = os.path.basename(request.vars.pluginfile.filename) if plugin_install(app, request.vars.pluginfile.file, request, filename): session.flash = T('new plugin installed') redirect(URL('design', args=app)) else: session.flash = \ T('unable to create application "%s"', request.vars.filename) redirect(URL(r=request)) elif isinstance(request.vars.pluginfile, str): session.flash = T('plugin not specified') redirect(URL(r=request)) # If we have only pyc files it means that # we cannot design if os.path.exists(apath('%s/compiled' % app, r=request)): session.flash = \ T('application is compiled and cannot be designed') redirect(URL('site')) # Get all models models = listdir(apath('%s/models/' % app, r=request), '.*\.py$') models = [x.replace('\\', '/') for x in models] defines = {} for m in models: data = safe_read(apath('%s/models/%s' % (app, m), r=request)) defines[m] = regex_tables.findall(data) defines[m].sort() # Get all controllers controllers = sorted( listdir(apath('%s/controllers/' % app, r=request), '.*\.py$')) controllers = [x.replace('\\', '/') for x in controllers] functions = {} for c in controllers: data = safe_read(apath('%s/controllers/%s' % (app, c), r=request)) items = regex_expose.findall(data) functions[c] = items # Get all views views = sorted( listdir(apath('%s/views/' % app, r=request), '[\w/\-]+(\.\w+)+$')) views = [x.replace('\\', '/') for x in views if not x.endswith('.bak')] extend = {} include = {} for c in views: data = safe_read(apath('%s/views/%s' % (app, c), r=request)) items = regex_extend.findall(data) if items: extend[c] = items[0][1] items = regex_include.findall(data) include[c] = [i[1] for i in items] # Get all modules modules = listdir(apath('%s/modules/' % app, r=request), '.*\.py$') modules = modules = [x.replace('\\', '/') for x in modules] modules.sort() # Get all private files privates = listdir(apath('%s/private/' % app, r=request), '[^\.#].*') privates = [x.replace('\\', '/') for x in privates] privates.sort() # Get all static files statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*') statics = [x.replace('\\', '/') for x in statics] statics.sort() # Get all languages langpath = os.path.join(apath(app, r=request),'languages') languages = dict([(lang, info) for lang, info in read_possible_languages(langpath).iteritems() if info[2] != 0]) # info[2] is langfile_mtime: # get only existed files #Get crontab cronfolder = apath('%s/cron' % app, r=request) if not os.path.exists(cronfolder): os.mkdir(cronfolder) crontab = apath('%s/cron/crontab' % app, r=request) if not os.path.exists(crontab): safe_write(crontab, '#crontab') plugins = [] def filter_plugins(items, plugins): plugins += [item[7:].split('/')[0].split( '.')[0] for item in items if item.startswith('plugin_')] plugins[:] = list(set(plugins)) plugins.sort() return [item for item in items if not item.startswith('plugin_')] return dict(app=app, models=filter_plugins(models, plugins), defines=defines, controllers=filter_plugins(controllers, plugins), functions=functions, views=filter_plugins(views, plugins), modules=filter_plugins(modules, plugins), extend=extend, include=include, privates=filter_plugins(privates, plugins), statics=filter_plugins(statics, plugins), languages=languages, crontab=crontab, plugins=plugins) def delete_plugin(): """ Object delete handler """ app = request.args(0) plugin = request.args(1) plugin_name = 'plugin_' + plugin dialog = FORM.confirm( T('Delete'), {T('Cancel'): URL('design', args=app)}) if dialog.accepted: try: for folder in ['models', 'views', 'controllers', 'static', 'modules', 'private']: path = os.path.join(apath(app, r=request), folder) for item in os.listdir(path): if item.rsplit('.', 1)[0] == plugin_name: filename = os.path.join(path, item) if os.path.isdir(filename): shutil.rmtree(filename) else: os.unlink(filename) session.flash = T('plugin "%(plugin)s" deleted', dict(plugin=plugin)) except Exception: session.flash = T('unable to delete file plugin "%(plugin)s"', dict(plugin=plugin)) redirect(URL('design', args=request.args(0), anchor=request.vars.id2)) return dict(dialog=dialog, plugin=plugin) def plugin(): """ Application design handler """ app = get_app() plugin = request.args(1) if not response.flash and app == request.application: msg = T('ATTENTION: you cannot edit the running application!') response.flash = msg # If we have only pyc files it means that # we cannot design if os.path.exists(apath('%s/compiled' % app, r=request)): session.flash = \ T('application is compiled and cannot be designed') redirect(URL('site')) # Get all models models = listdir(apath('%s/models/' % app, r=request), '.*\.py$') models = [x.replace('\\', '/') for x in models] defines = {} for m in models: data = safe_read(apath('%s/models/%s' % (app, m), r=request)) defines[m] = regex_tables.findall(data) defines[m].sort() # Get all controllers controllers = sorted( listdir(apath('%s/controllers/' % app, r=request), '.*\.py$')) controllers = [x.replace('\\', '/') for x in controllers] functions = {} for c in controllers: data = safe_read(apath('%s/controllers/%s' % (app, c), r=request)) items = regex_expose.findall(data) functions[c] = items # Get all views views = sorted( listdir(apath('%s/views/' % app, r=request), '[\w/\-]+\.\w+$')) views = [x.replace('\\', '/') for x in views] extend = {} include = {} for c in views: data = safe_read(apath('%s/views/%s' % (app, c), r=request)) items = regex_extend.findall(data) if items: extend[c] = items[0][1] items = regex_include.findall(data) include[c] = [i[1] for i in items] # Get all modules modules = listdir(apath('%s/modules/' % app, r=request), '.*\.py$') modules = modules = [x.replace('\\', '/') for x in modules] modules.sort() # Get all private files privates = listdir(apath('%s/private/' % app, r=request), '[^\.#].*') privates = [x.replace('\\', '/') for x in privates] privates.sort() # Get all static files statics = listdir(apath('%s/static/' % app, r=request), '[^\.#].*') statics = [x.replace('\\', '/') for x in statics] statics.sort() # Get all languages languages = sorted([lang + '.py' for lang, info in T.get_possible_languages_info().iteritems() if info[2] != 0]) # info[2] is langfile_mtime: # get only existed files #Get crontab crontab = apath('%s/cron/crontab' % app, r=request) if not os.path.exists(crontab): safe_write(crontab, '#crontab') def filter_plugins(items): regex = re.compile('^plugin_' + plugin + '(/.*|\..*)?$') return [item for item in items if item and regex.match(item)] return dict(app=app, models=filter_plugins(models), defines=defines, controllers=filter_plugins(controllers), functions=functions, views=filter_plugins(views), modules=filter_plugins(modules), extend=extend, include=include, privates=filter_plugins(privates), statics=filter_plugins(statics), languages=languages, crontab=crontab) def create_file(): """ Create files handler """ if request.vars and not request.vars.token == session.token: redirect(URL('logout')) try: anchor = '#' + request.vars.id if request.vars.id else '' if request.vars.app: app = get_app(request.vars.app) path = abspath(request.vars.location) else: app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) filename = re.sub('[^\w./-]+', '_', request.vars.filename) if path[-7:] == '/rules/': # Handle plural rules files if len(filename) == 0: raise SyntaxError if not filename[-3:] == '.py': filename += '.py' lang = re.match('^plural_rules-(.*)\.py$', filename).group(1) langinfo = read_possible_languages(apath(app, r=request))[lang] text = dedent(""" #!/usr/bin/env python # -*- coding: utf8 -*- # Plural-Forms for %(lang)s (%(langname)s) nplurals=2 # for example, English language has 2 forms: # 1 singular and 1 plural # Determine plural_id for number *n* as sequence of positive # integers: 0,1,... # NOTE! For singular form ALWAYS return plural_id = 0 get_plural_id = lambda n: int(n != 1) # Construct and return plural form of *word* using # *plural_id* (which ALWAYS>0). This function will be executed # for words (or phrases) not found in plural_dict dictionary. # By default this function simply returns word in singular: construct_plural_form = lambda word, plural_id: word """)[1:] % dict(lang=langinfo[0], langname=langinfo[1]) elif path[-11:] == '/languages/': # Handle language files if len(filename) == 0: raise SyntaxError if not filename[-3:] == '.py': filename += '.py' path = os.path.join(apath(app, r=request), 'languages', filename) if not os.path.exists(path): safe_write(path, '') # create language xx[-yy].py file: findT(apath(app, r=request), filename[:-3]) session.flash = T('language file "%(filename)s" created/updated', dict(filename=filename)) redirect(request.vars.sender + anchor) elif path[-8:] == '/models/': # Handle python models if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n' elif path[-13:] == '/controllers/': # Handle python controllers if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = '# coding: utf8\n# %s\ndef index(): return dict(message="hello from %s")' text = text % (T('try something like'), filename) elif path[-7:] == '/views/': if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle template (html) views if filename.find('.') < 0: filename += '.html' extension = filename.split('.')[-1].lower() if len(filename) == 5: raise SyntaxError msg = T( 'This is the %(filename)s template', dict(filename=filename)) if extension == 'html': text = dedent(""" {{extend 'layout.html'}} <h1>%s</h1> {{=BEAUTIFY(response._vars)}}""" % msg)[1:] else: generic = os.path.join(path, 'generic.' + extension) if os.path.exists(generic): text = read_file(generic) else: text = '' elif path[-9:] == '/modules/': if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) # Handle python module files if not filename[-3:] == '.py': filename += '.py' if len(filename) == 3: raise SyntaxError text = dedent(""" #!/usr/bin/env python # coding: utf8 from gluon import *\n""")[1:] elif (path[-8:] == '/static/') or (path[-9:] == '/private/'): if request.vars.plugin and not filename.startswith('plugin_%s/' % request.vars.plugin): filename = 'plugin_%s/%s' % (request.vars.plugin, filename) text = '' else: redirect(request.vars.sender + anchor) full_filename = os.path.join(path, filename) dirpath = os.path.dirname(full_filename) if not os.path.exists(dirpath): os.makedirs(dirpath) if os.path.exists(full_filename): raise SyntaxError safe_write(full_filename, text) log_progress(app, 'CREATE', filename) session.flash = T('file "%(filename)s" created', dict(filename=full_filename[len(path):])) vars = {} if request.vars.id: vars['id'] = request.vars.id if request.vars.app: vars['app'] = request.vars.app redirect(URL('edit', args=[os.path.join(request.vars.location, filename)], vars=vars)) except Exception, e: if not isinstance(e, HTTP): session.flash = T('cannot create file') redirect(request.vars.sender + anchor) def upload_file(): """ File uploading handler """ if request.vars and not request.vars.token == session.token: redirect(URL('logout')) try: filename = None app = get_app(name=request.vars.location.split('/')[0]) path = apath(request.vars.location, r=request) if request.vars.filename: filename = re.sub('[^\w\./]+', '_', request.vars.filename) else: filename = os.path.split(request.vars.file.filename)[-1] if path[-8:] == '/models/' and not filename[-3:] == '.py': filename += '.py' if path[-9:] == '/modules/' and not filename[-3:] == '.py': filename += '.py' if path[-13:] == '/controllers/' and not filename[-3:] == '.py': filename += '.py' if path[-7:] == '/views/' and not filename[-5:] == '.html': filename += '.html' if path[-11:] == '/languages/' and not filename[-3:] == '.py': filename += '.py' filename = os.path.join(path, filename) dirpath = os.path.dirname(filename) if not os.path.exists(dirpath): os.makedirs(dirpath) data = request.vars.file.file.read() lineno = count_lines(data) safe_write(filename, data, 'wb') log_progress(app, 'UPLOAD', filename, lineno) session.flash = T('file "%(filename)s" uploaded', dict(filename=filename[len(path):])) except Exception: if filename: d = dict(filename=filename[len(path):]) else: d = dict(filename='unkown') session.flash = T('cannot upload file "%(filename)s"', d) redirect(request.vars.sender) def errors(): """ Error handler """ import operator import os import pickle import hashlib app = get_app() method = request.args(1) or 'new' db_ready = {} db_ready['status'] = get_ticket_storage(app) db_ready['errmessage'] = T( "No ticket_storage.txt found under /private folder") db_ready['errlink'] = "http://web2py.com/books/default/chapter/29/13#Collecting-tickets" if method == 'new': errors_path = apath('%s/errors' % app, r=request) delete_hashes = [] for item in request.vars: if item[:7] == 'delete_': delete_hashes.append(item[7:]) hash2error = dict() for fn in listdir(errors_path, '^[a-fA-F0-9.\-]+$'): fullpath = os.path.join(errors_path, fn) if not os.path.isfile(fullpath): continue try: fullpath_file = open(fullpath, 'r') try: error = pickle.load(fullpath_file) finally: fullpath_file.close() except IOError: continue except EOFError: continue hash = hashlib.md5(error['traceback']).hexdigest() if hash in delete_hashes: os.unlink(fullpath) else: try: hash2error[hash]['count'] += 1 except KeyError: error_lines = error['traceback'].split("\n") last_line = error_lines[-2] if len(error_lines)>1 else 'unknown' error_causer = os.path.split(error['layer'])[1] hash2error[hash] = dict(count=1, pickel=error, causer=error_causer, last_line=last_line, hash=hash, ticket=fn) decorated = [(x['count'], x) for x in hash2error.values()] decorated.sort(key=operator.itemgetter(0), reverse=True) return dict(errors=[x[1] for x in decorated], app=app, method=method, db_ready=db_ready) elif method == 'dbnew': errors_path = apath('%s/errors' % app, r=request) tk_db, tk_table = get_ticket_storage(app) delete_hashes = [] for item in request.vars: if item[:7] == 'delete_': delete_hashes.append(item[7:]) hash2error = dict() for fn in tk_db(tk_table.id > 0).select(): try: error = pickle.loads(fn.ticket_data) except AttributeError: tk_db(tk_table.id == fn.id).delete() tk_db.commit() hash = hashlib.md5(error['traceback']).hexdigest() if hash in delete_hashes: tk_db(tk_table.id == fn.id).delete() tk_db.commit() else: try: hash2error['hash']['count'] += 1 except KeyError: error_lines = error['traceback'].split("\n") last_line = error_lines[-2] error_causer = os.path.split(error['layer'])[1] hash2error[hash] = dict(count=1, pickel=error, causer=error_causer, last_line=last_line, hash=hash, ticket=fn.ticket_id) decorated = [(x['count'], x) for x in hash2error.values()] decorated.sort(key=operator.itemgetter(0), reverse=True) return dict(errors=[x[1] for x in decorated], app=app, method=method) elif method == 'dbold': tk_db, tk_table = get_ticket_storage(app) for item in request.vars: if item[:7] == 'delete_': tk_db(tk_table.ticket_id == item[7:]).delete() tk_db.commit() tickets_ = tk_db(tk_table.id > 0).select(tk_table.ticket_id, tk_table.created_datetime, orderby=~tk_table.created_datetime) tickets = [row.ticket_id for row in tickets_] times = dict( [(row.ticket_id, row.created_datetime) for row in tickets_]) return dict(app=app, tickets=tickets, method=method, times=times) else: for item in request.vars: # delete_all} rows doesn't contain any ticket # Remove anything else as requested if item[:7] == 'delete_' and (not item == "delete_all}"): os.unlink(apath('%s/errors/%s' % (app, item[7:]), r=request)) func = lambda p: os.stat(apath('%s/errors/%s' % (app, p), r=request)).st_mtime tickets = sorted( listdir(apath('%s/errors/' % app, r=request), '^\w.*'), key=func, reverse=True) return dict(app=app, tickets=tickets, method=method, db_ready=db_ready) def get_ticket_storage(app): private_folder = apath('%s/private' % app, r=request) ticket_file = os.path.join(private_folder, 'ticket_storage.txt') if os.path.exists(ticket_file): db_string = open(ticket_file).read() db_string = db_string.strip().replace('\r', '').replace('\n', '') else: return False tickets_table = 'web2py_ticket' tablename = tickets_table + '_' + app db_path = apath('%s/databases' % app, r=request) ticketsdb = DAL(db_string, folder=db_path, auto_import=True) if not ticketsdb.get(tablename): table = ticketsdb.define_table( tablename, Field('ticket_id', length=100), Field('ticket_data', 'text'), Field('created_datetime', 'datetime'), ) return ticketsdb, ticketsdb.get(tablename) def make_link(path): """ Create a link from a path """ tryFile = path.replace('\\', '/') if os.path.isabs(tryFile) and os.path.isfile(tryFile): (folder, filename) = os.path.split(tryFile) (base, ext) = os.path.splitext(filename) app = get_app() editable = {'controllers': '.py', 'models': '.py', 'views': '.html'} for key in editable.keys(): check_extension = folder.endswith("%s/%s" % (app, key)) if ext.lower() == editable[key] and check_extension: return A('"' + tryFile + '"', _href=URL(r=request, f='edit/%s/%s/%s' % (app, key, filename))).xml() return '' def make_links(traceback): """ Make links using the given traceback """ lwords = traceback.split('"') # Making the short circuit compatible with <= python2.4 result = (len(lwords) != 0) and lwords[0] or '' i = 1 while i < len(lwords): link = make_link(lwords[i]) if link == '': result += '"' + lwords[i] else: result += link if i + 1 < len(lwords): result += lwords[i + 1] i = i + 1 i = i + 1 return result class TRACEBACK(object): """ Generate the traceback """ def __init__(self, text): """ TRACEBACK constructor """ self.s = make_links(CODE(text).xml()) def xml(self): """ Returns the xml """ return self.s def ticket(): """ Ticket handler """ if len(request.args) != 2: session.flash = T('invalid ticket') redirect(URL('site')) app = get_app() myversion = request.env.web2py_version ticket = request.args[1] e = RestrictedError() e.load(request, app, ticket) return dict(app=app, ticket=ticket, output=e.output, traceback=(e.traceback and TRACEBACK(e.traceback)), snapshot=e.snapshot, code=e.code, layer=e.layer, myversion=myversion) def ticketdb(): """ Ticket handler """ if len(request.args) != 2: session.flash = T('invalid ticket') redirect(URL('site')) app = get_app() myversion = request.env.web2py_version ticket = request.args[1] e = RestrictedError() request.tickets_db = get_ticket_storage(app)[0] e.load(request, app, ticket) response.view = 'default/ticket.html' return dict(app=app, ticket=ticket, output=e.output, traceback=(e.traceback and TRACEBACK(e.traceback)), snapshot=e.snapshot, code=e.code, layer=e.layer, myversion=myversion) def error(): """ Generate a ticket (for testing) """ raise RuntimeError('admin ticket generator at your service') def update_languages(): """ Update available languages """ app = get_app() update_all_languages(apath(app, r=request)) session.flash = T('Language files (static strings) updated') redirect(URL('design', args=app, anchor='languages')) def twitter(): session.forget() session._unlock(response) import gluon.tools import gluon.contrib.simplejson as sj try: if TWITTER_HASH: page = urllib.urlopen("http://search.twitter.com/search.json?q=%%40%s" % TWITTER_HASH).read() data = sj.loads(page, encoding="utf-8")['results'] d = dict() for e in data: d[e["id"]] = e r = reversed(sorted(d)) return dict(tweets=[d[k] for k in r]) else: return 'disabled' except Exception, e: return DIV(T('Unable to download because:'), BR(), str(e)) def user(): if MULTI_USER_MODE: if not db(db.auth_user).count(): auth.settings.registration_requires_approval = False return dict(form=auth()) else: return dict(form=T("Disabled")) def reload_routes(): """ Reload routes.py """ import gluon.rewrite gluon.rewrite.load() redirect(URL('site')) def manage_students(): if not (MULTI_USER_MODE and is_manager()): session.flash = T('Not Authorized') redirect(URL('site')) db.auth_user.registration_key.writable = True grid = SQLFORM.grid(db.auth_user) return locals() def bulk_register(): if not (MULTI_USER_MODE and is_manager()): session.flash = T('Not Authorized') redirect(URL('site')) form = SQLFORM.factory(Field('emails', 'text')) if form.process().accepted: emails = [x.strip() for x in form.vars.emails.split('\n') if x.strip()] n = 0 for email in emails: if not db.auth_user(email=email): n += db.auth_user.insert(email=email) and 1 or 0 session.flash = T('%s students registered', n) redirect(URL('site')) return locals() ### Begin experimental stuff need fixes: # 1) should run in its own process - cannot os.chdir # 2) should not prompt user at console # 3) should give option to force commit and not reuqire manual merge def git_pull(): """ Git Pull handler """ app = get_app() if not have_git: session.flash = GIT_MISSING redirect(URL('site')) dialog = FORM.confirm(T('Pull'), {T('Cancel'): URL('site')}) if dialog.accepted: try: repo = git.Repo(os.path.join(apath(r=request), app)) origin = repo.remotes.origin origin.fetch() origin.pull() session.flash = T("Application updated via git pull") redirect(URL('site')) except git.CheckoutError: session.flash = T("Pull failed, certain files could not be checked out. Check logs for details.") redirect(URL('site')) except git.UnmergedEntriesError: session.flash = T("Pull is not possible because you have unmerged files. Fix them up in the work tree, and then try again.") redirect(URL('site')) except git.GitCommandError: session.flash = T( "Pull failed, git exited abnormally. See logs for details.") redirect(URL('site')) except AssertionError: session.flash = T("Pull is not possible because you have unmerged files. Fix them up in the work tree, and then try again.") redirect(URL('site')) elif 'cancel' in request.vars: redirect(URL('site')) return dict(app=app, dialog=dialog) def git_push(): """ Git Push handler """ app = get_app() if not have_git: session.flash = GIT_MISSING redirect(URL('site')) form = SQLFORM.factory(Field('changelog', requires=IS_NOT_EMPTY())) form.element('input[type=submit]')['_value'] = T('Push') form.add_button(T('Cancel'), URL('site')) form.process() if form.accepted: try: repo = git.Repo(os.path.join(apath(r=request), app)) index = repo.index index.add([apath(r=request) + app + '/*']) new_commit = index.commit(form.vars.changelog) origin = repo.remotes.origin origin.push() session.flash = T( "Git repo updated with latest application changes.") redirect(URL('site')) except git.UnmergedEntriesError: session.flash = T("Push failed, there are unmerged entries in the cache. Resolve merge issues manually and try again.") redirect(URL('site')) return dict(app=app, form=form)
Python
response.files = response.files[:3] response.menu = [] def index(): return locals() def about(): return locals()
Python
# -*- coding: utf-8 -*- import os import uuid import re import pickle import urllib import glob from gluon.admin import app_create, plugin_install from gluon.fileutils import abspath, read_file, write_file def reset(session): session.app = { 'name': '', 'params': [('title', 'My New App'), ('subtitle', 'powered by web2py'), ('author', 'you'), ('author_email', 'you@example.com'), ('keywords', ''), ('description', ''), ('layout_theme', 'Default'), ('database_uri', 'sqlite://storage.sqlite'), ('security_key', str(uuid.uuid4())), ('email_server', 'localhost'), ('email_sender', 'you@example.com'), ('email_login', ''), ('login_method', 'local'), ('login_config', ''), ('plugins', [])], 'tables': ['auth_user'], 'table_auth_user': ['username', 'first_name', 'last_name', 'email', 'password'], 'pages': ['index', 'error'], 'page_index': '# Welcome to my new app', 'page_error': '# Error: the document does not exist', } if not session.app: reset(session) def listify(x): if not isinstance(x, (list, tuple)): return x and [x] or [] return x def clean(name): return re.sub('\W+', '_', name.strip().lower()) def index(): response.view = 'wizard/step.html' reset(session) apps = os.listdir(os.path.join(request.folder, '..')) form = SQLFORM.factory(Field('name', requires=[IS_NOT_EMPTY(), IS_ALPHANUMERIC()]), _class='span5 well well-small') if form.accepts(request.vars): app = form.vars.name session.app['name'] = app if MULTI_USER_MODE and db(db.app.name == app)(db.app.owner != auth.user.id).count(): session.flash = 'App belongs already to other user' elif app in apps: meta = os.path.normpath( os.path.join(os.path.normpath(request.folder), '..', app, 'wizard.metadata')) if os.path.exists(meta): try: metafile = open(meta, 'rb') try: session.app = pickle.load(metafile) finally: metafile.close() session.flash = T("The app exists, was created by wizard, continue to overwrite!") except: session.flash = T("The app exists, was NOT created by wizard, continue to overwrite!") redirect(URL('step1')) return dict(step='Start', form=form) def step1(): from gluon.contrib.simplejson import loads import urllib if not session.themes: url = LAYOUTS_APP + '/default/layouts.json' try: data = urllib.urlopen(url).read() session.themes = ['Default'] + loads(data)['layouts'] except: session.themes = ['Default'] themes = session.themes if not session.plugins: url = PLUGINS_APP + '/default/plugins.json' try: data = urllib.urlopen(url).read() session.plugins = loads(data)['plugins'] except: session.plugins = [] plugins = [x.split('.')[2] for x in session.plugins] response.view = 'wizard/step.html' params = dict(session.app['params']) form = SQLFORM.factory( Field('title', default=params.get('title', None), requires=IS_NOT_EMPTY()), Field('subtitle', default=params.get('subtitle', None)), Field('author', default=params.get('author', None)), Field( 'author_email', default=params.get('author_email', None)), Field('keywords', default=params.get('keywords', None)), Field('description', 'text', default=params.get('description', None)), Field('layout_theme', requires=IS_IN_SET(themes), default=params.get('layout_theme', themes[0])), Field( 'database_uri', default=params.get('database_uri', None)), Field( 'security_key', default=params.get('security_key', None)), Field( 'email_server', default=params.get('email_server', None)), Field( 'email_sender', default=params.get('email_sender', None)), Field('email_login', default=params.get('email_login', None)), Field('login_method', requires=IS_IN_SET(('local', 'janrain')), default=params.get('login_method', 'local')), Field( 'login_config', default=params.get('login_config', None)), Field('plugins', 'list:string', requires=IS_IN_SET(plugins, multiple=True)), _class='span7 well well-small') if form.accepts(request.vars): session.app['params'] = [(key, form.vars.get(key, None)) for key, value in session.app['params']] redirect(URL('step2') + '/#xwizard_form') return dict(step='1: Setting Parameters', form=form) def step2(): response.view = 'wizard/step.html' form = SQLFORM.factory(Field('table_names', 'list:string', default=session.app['tables']), _class="span7 well well-small") if form.accepts(request.vars): table_names = [clean(t) for t in listify(form.vars.table_names) if t.strip()] if [t for t in table_names if t.startswith('auth_') and not t == 'auth_user']: form.error.table_names = \ T('invalid table names (auth_* tables already defined)') else: session.app['tables'] = table_names for table in session.app['tables']: if not 'table_' + table in session.app: session.app['table_' + table] = ['name'] if not table == 'auth_user': name = table + '_manage' if not name in session.app['pages']: session.app['pages'].append(name) session.app['page_' + name] = \ '## Manage %s\n\n{{=form}}' % (table) if session.app['tables']: redirect(URL('step3', args=0) + '/#xwizard_form') else: redirect(URL('step4') + '/#xwizard_form') return dict(step='2: Tables', form=form) def step3(): response.view = 'wizard/step.html' n = int(request.args(-1) or 0) m = len(session.app['tables']) if n >= m: redirect(URL('step2')) table = session.app['tables'][n] form = SQLFORM.factory(Field('field_names', 'list:string', default=session.app.get('table_' + table, [])), _class="span7 well well-small") if form.accepts(request.vars) and form.vars.field_names: fields = listify(form.vars.field_names) if table == 'auth_user': for field in ['first_name', 'last_name', 'username', 'email', 'password']: if not field in fields: fields.append(field) session.app['table_' + table] = [t.strip().lower() for t in listify(form.vars.field_names) if t.strip()] try: tables = sort_tables(session.app['tables']) except RuntimeError: response.flash = T('invalid circular reference') else: if n < m - 1: redirect(URL('step3', args=n + 1) + '/#xwizard_form') else: redirect(URL('step4') + '/#xwizard_form') return dict(step='3: Fields for table "%s" (%s of %s)' % (table, n + 1, m), table=table, form=form) def step4(): response.view = 'wizard/step.html' form = SQLFORM.factory(Field('pages', 'list:string', default=session.app['pages']), _class="span7 well well-small") if form.accepts(request.vars): session.app['pages'] = [clean(t) for t in listify(form.vars.pages) if t.strip()] if session.app['pages']: redirect(URL('step5', args=0) + '/#xwizard_form') else: redirect(URL('step6') + '/#xwizard_form') return dict(step='4: Pages', form=form) def step5(): response.view = 'wizard/step.html' n = int(request.args(-1) or 0) m = len(session.app['pages']) if n >= m: redirect(URL('step4')) page = session.app['pages'][n] markmin_url = 'http://web2py.com/examples/static/markmin.html' form = SQLFORM.factory(Field('content', 'text', default=session.app.get('page_' + page, []), comment=A('use markmin', _href=markmin_url, _target='_blank')), formstyle='table2cols', _class="span7 well well-small") if form.accepts(request.vars): session.app['page_' + page] = form.vars.content if n < m - 1: redirect(URL('step5', args=n + 1) + '/#xwizard_form') else: redirect(URL('step6') + '/#xwizard_form') return dict(step='5: View for page "%s" (%s of %s)' % (page, n + 1, m), form=form) def step6(): response.view = 'wizard/step.html' params = dict(session.app['params']) app = session.app['name'] form = SQLFORM.factory( Field('generate_model', 'boolean', default=True), Field('generate_controller', 'boolean', default=True), Field('generate_views', 'boolean', default=True), Field('generate_menu', 'boolean', default=True), Field('apply_layout', 'boolean', default=True), Field('erase_database', 'boolean', default=True), Field('populate_database', 'boolean', default=True), _id="generate_form", _class="form-horizontal span7 well well-small") if form.accepts(request.vars): if DEMO_MODE: session.flash = T('Application cannot be generated in demo mode') redirect(URL('index')) create(form.vars) session.flash = 'Application %s created' % app redirect(URL('generated')) return dict(step='6: Generate app "%s"' % app, form=form) def generated(): return dict(app=session.app['name']) def sort_tables(tables): import re regex = re.compile('(%s)' % '|'.join(tables)) is_auth_user = 'auth_user' in tables d = {} for table in tables: d[table] = [] for field in session.app['table_%s' % table]: d[table] += regex.findall(field) tables = [] if is_auth_user: tables.append('auth_user') def append(table, trail=[]): if table in trail: raise RuntimeError for t in d[table]: # if not t==table: (problem, no dropdown for self references) append(t, trail=trail + [table]) if not table in tables: tables.append(table) for table in d: append(table) return tables def make_table(table, fields): rawtable = table if table != 'auth_user': table = 't_' + table s = '' s += '\n' + '#' * 40 + '\n' s += "db.define_table('%s',\n" % table first_field = 'id' for field in fields: items = [x.lower() for x in field.split()] has = {} keys = [] for key in ['notnull', 'unique', 'integer', 'double', 'boolean', 'float', 'boolean', 'date', 'time', 'datetime', 'text', 'wiki', 'html', 'file', 'upload', 'image', 'true', 'hidden', 'readonly', 'writeonly', 'multiple', 'notempty', 'required']: if key in items[1:]: keys.append(key) has[key] = True tables = session.app['tables'] refs = [t for t in tables if t in items] items = items[:1] + [x for x in items[1:] if not x in keys and not x in tables] barename = name = '_'.join(items) if table[:2] == 't_': name = 'f_' + name if first_field == 'id': first_field = name ### determine field type ftype = 'string' deftypes = {'integer': 'integer', 'double': 'double', 'boolean': 'boolean', 'float': 'double', 'bool': 'boolean', 'date': 'date', 'time': 'time', 'datetime': 'datetime', 'text': 'text', 'file': 'upload', 'image': 'upload', 'upload': 'upload', 'wiki': 'text', 'html': 'text'} for key, t in deftypes.items(): if key in has: ftype = t if refs: key = refs[0] if not key == 'auth_user': key = 't_' + key if 'multiple' in has: ftype = 'list:reference %s' % key else: ftype = 'reference %s' % key if ftype == 'string' and 'multiple' in has: ftype = 'list:string' elif ftype == 'integer' and 'multiple' in has: ftype = 'list:integer' elif name == 'password': ftype = 'password' s += " Field('%s', type='%s'" % (name, ftype) ### determine field attributes if 'notnull' in has or 'notempty' in has or 'required' in has: s += ', notnull=True' if 'unique' in has: s += ', unique=True' if ftype == 'boolean' and 'true' in has: s += ",\n default=True" ### determine field representation elif 'wiki' in has: s += ",\n represent=lambda x, row: MARKMIN(x)" s += ",\n comment='WIKI (markmin)'" elif 'html' in has: s += ",\n represent=lambda x, row: XML(x,sanitize=True)" s += ",\n comment='HTML (sanitized)'" ### determine field access if name == 'password' or 'writeonly' in has: s += ",\n readable=False" elif 'hidden' in has: s += ",\n writable=False, readable=False" elif 'readonly' in has: s += ",\n writable=False" ### make up a label s += ",\n label=T('%s')),\n" % \ ' '.join(x.capitalize() for x in barename.split('_')) if table == 'auth_user': s += " Field('created_on','datetime',default=request.now,\n" s += " label=T('Created On'),writable=False,readable=False),\n" s += " Field('modified_on','datetime',default=request.now,\n" s += " label=T('Modified On'),writable=False,readable=False,\n" s += " update=request.now),\n" s += " Field('registration_key',default='',\n" s += " writable=False,readable=False),\n" s += " Field('reset_password_key',default='',\n" s += " writable=False,readable=False),\n" s += " Field('registration_id',default='',\n" s += " writable=False,readable=False),\n" elif 'auth_user' in session.app['tables']: s += " auth.signature,\n" s += " format='%(" + first_field + ")s',\n" s += " migrate=settings.migrate)\n\n" if table == 'auth_user': s += """ db.auth_user.first_name.requires = IS_NOT_EMPTY( error_message=auth.messages.is_empty) db.auth_user.last_name.requires = IS_NOT_EMPTY( error_message=auth.messages.is_empty) db.auth_user.password.requires = CRYPT( key=auth.settings.hmac_key, min_length=4) db.auth_user.username.requires = IS_NOT_IN_DB(db, db.auth_user.username) db.auth_user.email.requires = ( IS_EMAIL(error_message=auth.messages.invalid_email), IS_NOT_IN_DB(db, db.auth_user.email)) """ else: s += "db.define_table('%s_archive',db.%s,Field('current_record','reference %s',readable=False,writable=False))\n" % (table, table, table) return s def fix_db(filename): params = dict(session.app['params']) content = read_file(filename, 'rb') if 'auth_user' in session.app['tables']: auth_user = make_table('auth_user', session.app['table_auth_user']) content = content.replace('sqlite://storage.sqlite', params['database_uri']) content = content.replace('auth.define_tables()', auth_user + 'auth.define_tables(migrate = settings.migrate)') content += """ mail.settings.server = settings.email_server mail.settings.sender = settings.email_sender mail.settings.login = settings.email_login """ if params['login_method'] == 'janrain': content += """ from gluon.contrib.login_methods.rpx_account import RPXAccount auth.settings.actions_disabled=['register','change_password', 'request_reset_password'] auth.settings.login_form = RPXAccount(request, api_key = settings.login_config.split(':')[-1], domain = settings.login_config.split(':')[0], url = "http://%s/%s/default/user/login" % (request.env.http_host,request.application)) """ write_file(filename, content, 'wb') def make_menu(pages): s = '' s += 'response.title = settings.title\n' s += 'response.subtitle = settings.subtitle\n' s += "response.meta.author = '%(author)s <%(author_email)s>' % settings\n" s += 'response.meta.keywords = settings.keywords\n' s += 'response.meta.description = settings.description\n' s += 'response.menu = [\n' for page in pages: if not page.startswith('error'): if page.endswith('_manage'): page_name = page[:-7] else: page_name = page page_name = ' '.join(x.capitalize() for x in page_name.split('_')) s += "(T('%s'),URL('default','%s')==URL(),URL('default','%s'),[]),\n" \ % (page_name, page, page) s += ']' return s def make_page(page, contents): if 'auth_user' in session.app['tables'] and not page in ('index', 'error'): s = "@auth.requires_login()\ndef %s():\n" % page else: s = "def %s():\n" % page items = page.rsplit('_', 1) if items[0] in session.app['tables'] and len(items) == 2 and items[1] == 'manage': s += " form = SQLFORM.smartgrid(db.t_%s,onupdate=auth.archive)\n" % items[0] s += " return locals()\n\n" else: s += " return dict()\n\n" return s def make_view(page, contents): s = "{{extend 'layout.html'}}\n\n" s += str(MARKMIN(contents)) return s def populate(tables): s = 'from gluon.contrib.populate import populate\n' s += 'if db(db.auth_user).isempty():\n' for table in sort_tables(tables): t = table == 'auth_user' and 'auth_user' or 't_' + table s += " populate(db.%s,10)\n" % t return s def create(options): if DEMO_MODE: session.flash = T('disabled in demo mode') redirect(URL('step6')) params = dict(session.app['params']) app = session.app['name'] if app_create(app, request, force=True, key=params['security_key']): if MULTI_USER_MODE: db.app.insert(name=app, owner=auth.user.id) else: session.flash = 'Failure to create application' redirect(URL('step6')) ### save metadata in newapp/wizard.metadata try: meta = os.path.join(request.folder, '..', app, 'wizard.metadata') file = open(meta, 'wb') pickle.dump(session.app, file) file.close() except IOError: session.flash = 'Failure to write wizard metadata' redirect(URL('step6')) ### apply theme if options.apply_layout and params['layout_theme'] != 'Default': try: fn = 'web2py.plugin.layout_%s.w2p' % params['layout_theme'] theme = urllib.urlopen( LAYOUTS_APP + '/static/plugin_layouts/plugins/' + fn) plugin_install(app, theme, request, fn) except: session.flash = T("unable to download layout") ### apply plugins for plugin in params['plugins']: try: plugin_name = 'web2py.plugin.' + plugin + '.w2p' stream = urllib.urlopen(PLUGINS_APP + '/static/' + plugin_name) plugin_install(app, stream, request, plugin_name) except Exception, e: session.flash = T("unable to download plugin: %s" % plugin) ### write configuration file into newapp/models/0.py model = os.path.join(request.folder, '..', app, 'models', '0.py') file = open(model, 'wb') try: file.write("from gluon.storage import Storage\n") file.write("settings = Storage()\n\n") file.write("settings.migrate = True\n") for key, value in session.app['params']: file.write("settings.%s = %s\n" % (key, repr(value))) finally: file.close() ### write configuration file into newapp/models/menu.py if options.generate_menu: model = os.path.join(request.folder, '..', app, 'models', 'menu.py') file = open(model, 'wb') try: file.write(make_menu(session.app['pages'])) finally: file.close() ### customize the auth_user table model = os.path.join(request.folder, '..', app, 'models', 'db.py') fix_db(model) ### create newapp/models/db_wizard.py if options.generate_model: model = os.path.join( request.folder, '..', app, 'models', 'db_wizard.py') file = open(model, 'wb') try: file.write('### we prepend t_ to tablenames and f_ to fieldnames for disambiguity\n\n') tables = sort_tables(session.app['tables']) for table in tables: if table == 'auth_user': continue file.write(make_table(table, session.app['table_' + table])) finally: file.close() model = os.path.join(request.folder, '..', app, 'models', 'db_wizard_populate.py') if os.path.exists(model): os.unlink(model) if options.populate_database and session.app['tables']: file = open(model, 'wb') try: file.write(populate(session.app['tables'])) finally: file.close() ### create newapp/controllers/default.py if options.generate_controller: controller = os.path.join( request.folder, '..', app, 'controllers', 'default.py') file = open(controller, 'wb') try: file.write("""# -*- coding: utf-8 -*- ### required - do no delete def user(): return dict(form=auth()) def download(): return response.download(request,db) def call(): return service() ### end requires """) for page in session.app['pages']: file.write( make_page(page, session.app.get('page_' + page, ''))) finally: file.close() ### create newapp/views/default/*.html if options.generate_views: for page in session.app['pages']: view = os.path.join( request.folder, '..', app, 'views', 'default', page + '.html') file = open(view, 'wb') try: file.write( make_view(page, session.app.get('page_' + page, ''))) finally: file.close() if options.erase_database: path = os.path.join(request.folder, '..', app, 'databases', '*') for file in glob.glob(path): os.unlink(file)
Python
# -*- coding: utf-8 -*- response.menu = [ (T('Home'), False, URL('default', 'index')), (T('About'), False, URL('default', 'what')), (T('Download'), False, URL('default', 'download')), (T('Docs & Resources'), False, URL('default', 'documentation')), (T('Support'), False, URL('default', 'support')), (T('Contributors'), False, URL('default', 'who'))] ######################################################################### ## Changes the menu active item ######################################################################### def toggle_menuclass(cssclass='pressed', menuid='headermenu'): """This function changes the menu class to put pressed appearance""" positions = dict( index='', what='-108px -115px', download='-211px -115px', who='-315px -115px', support='-418px -115px', documentation='-520px -115px' ) if request.function in positions.keys(): jscript = """ <script> $(document).ready(function(){ $('.%(menuid)s a').removeClass('%(cssclass)s'); $('.%(function)s').toggleClass('%(cssclass)s').css('background-position','%(cssposition)s') }); </script> """ % dict(cssclass=cssclass, menuid=menuid, function=request.function, cssposition=positions[request.function] ) return XML(jscript) else: return ''
Python
session.connect(request,response,cookie_key='yoursecret')
Python
def group_feed_reader(group, mode='div', counter='5'): """parse group feeds""" url = "http://groups.google.com/group/%s/feed/rss_v2_0_topics.xml?num=%s" %\ (group, counter) from gluon.contrib import feedparser g = feedparser.parse(url) if mode == 'div': html = XML(TAG.BLOCKQUOTE(UL(*[LI(A(entry['title'] + ' - ' + entry['author'][ entry['author'].rfind('('):], _href=entry['link'], _target='_blank')) for entry in g['entries']]), _class="boxInfo", _style="padding-bottom:5px;")) else: html = XML(UL(*[LI(A(entry['title'] + ' - ' + entry['author'][entry['author'].rfind('('):], _href=entry['link'], _target='_blank')) for entry in g['entries']])) return html def code_feed_reader(project, mode='div'): """parse code feeds""" url = "http://code.google.com/feeds/p/%s/hgchanges/basic" % project from gluon.contrib import feedparser g = feedparser.parse(url) if mode == 'div': html = XML(DIV(UL(*[LI(A(entry['title'], _href=entry['link'], _target='_blank')) for entry in g['entries'][0:5]]), _class="boxInfo", _style="padding-bottom:5px;")) else: html = XML(UL(*[LI(A(entry['title'], _href=entry['link'], _target='_blank')) for entry in g['entries'][0:5]])) return html
Python
import gluon.template markmin_dict = dict( code_python=lambda code: str(CODE(code)), template=lambda code: gluon.template.render(code, context=globals()), sup=lambda code: '<sup style="font-size:0.5em;">%s</sup>' % code, br=lambda n: '<br>' * int(n), groupdates=lambda group: group_feed_reader(group), ) def get_content(b=None, c=request.controller, f=request.function, l='en', format='markmin'): """Gets and renders the file in <app>/private/content/<lang>/<controller>/<function>/<block>.<format> """ def openfile(): import os path = os.path.join( request.folder, 'private', 'content', l, c, f, b + '.' + format) return open(path) try: openedfile = openfile() except Exception, IOError: l = 'en' openedfile = openfile() if format == 'markmin': html = MARKMIN(str(T(openedfile.read())), markmin_dict) else: html = str(T(openedfile.read())) openedfile.close() return html
Python
def hello1(): """ simple page without template """ return 'Hello World' def hello2(): """ simple page without template but with internationalization """ return T('Hello World') def hello3(): """ page rendered by template simple_examples/index3.html or generic.html""" return dict(message='Hello World') def hello4(): """ page rendered by template simple_examples/index3.html or generic.html""" response.view = 'simple_examples/hello3.html' return dict(message=T('Hello World')) def hello5(): """ generates full page in controller """ return HTML(BODY(H1(T('Hello World'), _style='color: red;'))).xml() # .xml to serialize def hello6(): """ page rendered with a flash""" response.flash = 'Hello World in a flash!' return dict(message=T('Hello World')) def status(): """ page that shows internal status""" return dict(toolbar=response.toolbar()) def redirectme(): """ redirects to /{{=request.application}}/{{=request.controller}}/hello3 """ redirect(URL('hello3')) def raisehttp(): """ returns an HTTP 400 ERROR page """ raise HTTP(400, 'internal error') def servejs(): """ serves a js document """ import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.js') return 'alert("This is a Javascript document, it is not supposed to run!");' def makejson(): import gluon.contrib.simplejson as sj return sj.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}]) def makertf(): import gluon.contrib.pyrtf as q doc = q.Document() section = q.Section() doc.Sections.append(section) section.append('Section Title') section.append('web2py is great. ' * 100) response.headers['Content-Type'] = 'text/rtf' return q.dumps(doc) def rss_aggregator(): import datetime import gluon.contrib.rss2 as rss2 import gluon.contrib.feedparser as feedparser d = feedparser.parse('http://rss.slashdot.org/Slashdot/slashdot/to') rss = rss2.RSS2(title=d.channel.title, link=d.channel.link, description=d.channel.description, lastBuildDate=datetime.datetime.now(), items=[rss2.RSSItem(title=entry.title, link=entry.link, description=entry.description, pubDate=datetime.datetime.now()) for entry in d.entries]) response.headers['Content-Type'] = 'application/rss+xml' return rss.to_xml(encoding='utf-8') def ajaxwiki(): default = """ # section ## subsection ### sub subsection - **bold** text - ''italic'' - [[link http://google.com]] `` def index: return 'hello world' `` ----------- Quoted text ----------- --------- 0 | 0 | 1 0 | 2 | 0 3 | 0 | 0 --------- """ form = FORM(TEXTAREA(_id='text', _name='text', value=default), INPUT(_type='button', _value='markmin', _onclick="ajax('ajaxwiki_onclick',['text'],'html')")) return dict(form=form, html=DIV(_id='html')) def ajaxwiki_onclick(): return MARKMIN(request.vars.text).xml()
Python
def index(): return dict() def data(): if not session.m or len(session.m) == 10: session.m = [] if request.vars.q: session.m.append(request.vars.q) session.m.sort() return TABLE(*[TR(v) for v in session.m]).xml() def flash(): response.flash = 'this text should appear!' return dict() def fade(): return dict()
Python
def variables(): return dict(a=10, b=20) def test_for(): return dict() def test_if(): return dict() def test_try(): return dict() def test_def(): return dict() def escape(): return dict(message='<h1>text is scaped</h1>') def xml(): return dict(message=XML('<h1>text is not escaped</h1>')) def beautify(): return dict(message=BEAUTIFY(request))
Python
def form(): """ a simple entry form with various types of objects """ form = FORM(TABLE( TR('Your name:', INPUT(_type='text', _name='name', requires=IS_NOT_EMPTY())), TR('Your email:', INPUT(_type='text', _name='email', requires=IS_EMAIL())), TR('Admin', INPUT(_type='checkbox', _name='admin')), TR('Sure?', SELECT('yes', 'no', _name='sure', requires=IS_IN_SET(['yes', 'no']))), TR('Profile', TEXTAREA(_name='profile', value='write something here')), TR('', INPUT(_type='submit', _value='SUBMIT')), )) if form.process().accepted: response.flash = 'form accepted' elif form.errors: response.flash = 'form is invalid' else: response.flash = 'please fill the form' return dict(form=form, vars=form.vars)
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils try: import pygraphviz as pgv except ImportError: pgv = None response.subtitle = 'Database Administration (appadmin)' # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1', '127.0.0.1', '::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.is_https: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if (request.application == 'admin' and not session.authorized) or \ (request.application != 'admin' and not gluon.fileutils.check_credentials(request)): redirect(URL('admin', 'default', 'index', vars=dict(send=URL(args=request.args, vars=request.vars)))) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### if False and request.tickets_db: from gluon.restricted import TicketStorage ts = TicketStorage() ts._get_table(request.tickets_db, ts.tablename, request.application) def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename, db, request=request): keyed = hasattr(db[tablename], '_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % ( request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form, table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request, db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query, ignore_common_filters=True).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY( error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value=T('submit')))), _action=URL(r=request, args=request.args)) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s %%{row} updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s %%{row} deleted', nrows) nrows = db(query).count() if orderby: rows = db(query, ignore_common_filters=True).select(limitby=( start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select( limitby=(start, stop)) except Exception, e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'), PRE(str(e))) # begin handle upload csv csv_table = table or request.vars.table if csv_table: formcsv = FORM(str(T('or import from csv file')) + " ", INPUT(_type='file', _name='csvfile'), INPUT(_type='hidden', _value=csv_table, _name='table'), INPUT(_type='submit', _value=T('import'))) else: formcsv = None if formcsv and formcsv.process().accepted: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e))) # end handle upload csv return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, formcsv=formcsv, tb=tb, ) # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table], '_primarykey') record = None db[table]._common_filter = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[ 0]]).select().first() else: record = db(db[table].id == request.args( 2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable = False form = SQLFORM( db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form, table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): cache.ram.initialize() cache.disk.initialize() form = FORM( P(TAG.BUTTON( T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON( T("Clear RAM"), _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON( T("Clear DISK"), _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += T("Ram Cleared") if clear_disk: cache.disk.clear() session.flash += T("Disk Cleared") redirect(URL(r=request)) try: from guppy import hpy hp = hpy() except ImportError: hp = False import shelve import os import copy import time import math from gluon import portalocker ram = { 'entries': 0, 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time(), 'keys': [] } disk = copy.copy(ram) total = copy.copy(ram) disk['keys'] = [] total['keys'] = [] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) for key, value in cache.ram.storage.iteritems(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count ram['entries'] += 1 if value[0] < ram['oldest']: ram['oldest'] = value[0] ram['keys'].append((key, GetInHMS(time.time() - value[0]))) folder = os.path.join(request.folder,'cache') if not os.path.exists(folder): os.mkdir(folder) locker = open(os.path.join(folder, 'cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open( os.path.join(folder, 'cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count disk['entries'] += 1 if value[0] < disk['oldest']: disk['oldest'] = value[0] disk['keys'].append((key, GetInHMS(time.time() - value[0]))) finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['entries'] = ram['entries'] + disk['entries'] total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] total['keys'] = ram['keys'] + disk['keys'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) def key_table(keys): return TABLE( TR(TD(B(T('Key'))), TD(B(T('Time in Cache (h:m:s)')))), *[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys], **dict(_class='cache-keys', _style="border-collapse: separate; border-spacing: .5em;")) ram['keys'] = key_table(ram['keys']) disk['keys'] = key_table(disk['keys']) total['keys'] = key_table(total['keys']) return dict(form=form, total=total, ram=ram, disk=disk, object_stats=hp != False) def table_template(table): from gluon.html import TR, TD, TABLE, TAG def FONT(*args, **kwargs): return TAG.font(*args, **kwargs) def types(field): f_type = field.type if not isinstance(f_type,str): return ' ' elif f_type == 'string': return field.length elif f_type == 'id': return B('pk') elif f_type.startswith('reference') or \ f_type.startswith('list:reference'): return B('fk') else: return ' ' # This is horribe HTML but the only one graphiz understands rows = [] cellpadding = 4 color = "#000000" bgcolor = "#FFFFFF" face = "Helvetica" face_bold = "Helvetica Bold" border = 0 rows.append(TR(TD(FONT(table, _face=face_bold, _color=bgcolor), _colspan=3, _cellpadding=cellpadding, _align="center", _bgcolor=color))) for row in db[table]: rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(row.type, _color=color, _face=face), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(types(row), _color=color, _face=face), _align="center", _cellpadding=cellpadding, _border=border))) return "< %s >" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1, _cellborder=0, _cellspacing=0) ).xml() def bg_graph_model(): graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR') subgraphs = dict() for tablename in db.tables: if hasattr(db[tablename],'_meta_graphmodel'): meta_graphmodel = db[tablename]._meta_graphmodel else: meta_graphmodel = dict(group='Undefined', color='#ECECEC') group = meta_graphmodel['group'].replace(' ', '') if not subgraphs.has_key(group): subgraphs[group] = dict(meta=meta_graphmodel, tables=[]) subgraphs[group]['tables'].append(tablename) else: subgraphs[group]['tables'].append(tablename) graph.add_node(tablename, name=tablename, shape='plaintext', label=table_template(tablename)) for n, key in enumerate(subgraphs.iterkeys()): graph.subgraph(nbunch=subgraphs[key]['tables'], name='cluster%d' % n, style='filled', color=subgraphs[key]['meta']['color'], label=subgraphs[key]['meta']['group']) for tablename in db.tables: for field in db[tablename]: f_type = field.type if isinstance(f_type,str) and ( f_type.startswith('reference') or f_type.startswith('list:reference')): referenced_table = f_type.split()[1].split('.')[0] n1 = graph.get_node(tablename) n2 = graph.get_node(referenced_table) graph.add_edge(n1, n2, color="#4C4C4C", label='') graph.layout() #return graph.draw(format='png', prog='dot') if not request.args: return graph.draw(format='png', prog='dot') else: response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0) if request.args(0) == 'dot': return graph.string() else: return graph.draw(format=request.args(0), prog='dot') def graph_model(): return dict(databases=databases, pgv=pgv)
Python
def counter(): """ every time you reload, it increases the session.counter """ if not session.counter: session.counter = 0 session.counter += 1 return dict(counter=session.counter)
Python
# -*- coding: utf-8 -*- from gluon.fileutils import read_file response.title = T('web2py Web Framework') response.keywords = T('web2py, Python, Web Framework') response.description = T('web2py Web Framework') session.forget() cache_expire = not request.is_local and 300 or 0 @cache('index', time_expire=cache_expire) def index(): return response.render() @cache('what', time_expire=cache_expire) def what(): import urllib try: images = XML(urllib.urlopen( 'http://www.web2py.com/poweredby/default/images').read()) except: images = [] return response.render(images=images) @cache('download', time_expire=cache_expire) def download(): return response.render() @cache('who', time_expire=cache_expire) def who(): return response.render() @cache('support', time_expire=cache_expire) def support(): return response.render() @cache('documentation', time_expire=cache_expire) def documentation(): return response.render() @cache('usergroups', time_expire=cache_expire) def usergroups(): return response.render() def contact(): redirect(URL('default', 'usergroups')) @cache('videos', time_expire=cache_expire) def videos(): return response.render() def security(): redirect('http://www.web2py.com/book/default/chapter/01#Security') def api(): redirect('http://www.web2py.com/book/default/chapter/04#API') @cache('license', time_expire=cache_expire) def license(): import os filename = os.path.join(request.env.gluon_parent, 'LICENSE') return response.render(dict(license=MARKMIN(read_file(filename)))) def version(): if request.args(0)=='raw': return request.env.web2py_version from gluon.fileutils import parse_version (a, b, c, pre_release, build) = parse_version(request.env.web2py_version) return 'Version %i.%i.%i (%.4i-%.2i-%.2i %.2i:%.2i:%.2i) %s' % ( a,b,c,build.year,build.month,build.day, build.hour,build.minute,build.second,pre_release) @cache('examples', time_expire=cache_expire) def examples(): return response.render() @cache('changelog', time_expire=cache_expire) def changelog(): import os filename = os.path.join(request.env.gluon_parent, 'CHANGELOG') return response.render(dict(changelog=MARKMIN(read_file(filename))))
Python
def civilized(): response.menu = [['civilized', True, URL('civilized' )], ['slick', False, URL('slick')], ['basic', False, URL('basic')]] response.flash = 'you clicked on civilized' return dict(message='you clicked on civilized') def slick(): response.menu = [['civilized', False, URL('civilized' )], ['slick', True, URL('slick')], ['basic', False, URL('basic')]] response.flash = 'you clicked on slick' return dict(message='you clicked on slick') def basic(): response.menu = [['civilized', False, URL('civilized' )], ['slick', False, URL('slick')], ['basic', True, URL('basic')]] response.flash = 'you clicked on basic' return dict(message='you clicked on basic')
Python
session.forget() def get(args): if args[0].startswith('__'): return None try: obj = globals(),get(args[0]) for k in range(1,len(args)): obj = getattr(obj,args[k]) return obj except: return None def vars(): """the running controller function!""" title = '.'.join(request.args) attributes = {} if not request.args: (doc,keys,t,c,d,value)=('Global variables',globals(),None,None,[],None) elif len(request.args) < 3: obj = get(request.args) if obj: doc = getattr(obj,'__doc__','no documentation') keys = dir(obj) t = type(obj) c = getattr(obj,'__class__',None) d = getattr(obj,'__bases__',None) for key in keys: a = getattr(obj,key,None) if a and not isinstance(a,DAL): doc1 = getattr(a, '__doc__', '') t1 = type(a) c1 = getattr(a,'__class__',None) d1 = getattr(a,'__bases__',None) key = '.'.join(request.args)+'.'+key attributes[key] = (doc1, t1, c1, d1) else: doc = 'Unkown' keys = [] t = c = d = None else: raise HTTP(400) return dict( title=title, args=request.args, t=t, c=c, d=d, doc=doc, attributes=attributes, )
Python
import time def cache_in_ram(): """cache the output of the lambda function in ram""" t = cache.ram('time', lambda: time.ctime(), time_expire=5) return dict(time=t, link=A('click to reload', _href=URL(r=request))) def cache_on_disk(): """cache the output of the lambda function on disk""" t = cache.disk('time', lambda: time.ctime(), time_expire=5) return dict(time=t, link=A('click to reload', _href=URL(r=request))) def cache_in_ram_and_disk(): """cache the output of the lambda function on disk and in ram""" t = cache.ram('time', lambda: cache.disk('time', lambda: time.ctime(), time_expire=5), time_expire=5) return dict(time=t, link=A('click to reload', _href=URL(r=request))) @cache(request.env.path_info, time_expire=5, cache_model=cache.ram) def cache_controller_in_ram(): """cache the output of the controller in ram""" t = time.ctime() return dict(time=t, link=A('click to reload', _href=URL(r=request))) @cache(request.env.path_info, time_expire=5, cache_model=cache.disk) def cache_controller_on_disk(): """cache the output of the controller on disk""" t = time.ctime() return dict(time=t, link=A('click to reload', _href=URL(r=request))) @cache(request.env.path_info, time_expire=5, cache_model=cache.ram) def cache_controller_and_view(): """cache the output of the controller rendered by the view in ram""" t = time.ctime() d = dict(time=t, link=A('click to reload', _href=URL(r=request))) return response.render(d)
Python
from gluon.contrib.spreadsheet import Sheet def callback(): return cache.ram('sheet1', lambda: None, None).process(request) def index(): sheet = cache.ram('sheet1', lambda: Sheet(10, 10, URL('callback')), 0) #sheet.cell('r0c3',value='=r0c0+r0c1+r0c2',readonly=True) return dict(sheet=sheet)
Python
# coding: utf8 { '!langcode!': 'zh-tw', '!langname!': '中文', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"更新" 是選擇性的條件式, 格式就像 "欄位1=\'值\'". 但是 JOIN 的資料不可以使用 update 或是 delete"', '%s %%{row} deleted': '已刪除 %s 筆', '%s %%{row} updated': '已更新 %s 筆', '%s selected': '%s 已選擇', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(格式類似 "zh-tw")', 'A new version of web2py is available': '新版的 web2py 已發行', 'A new version of web2py is available: %s': '新版的 web2py 已發行: %s', 'about': '關於', 'About': '關於', 'About application': '關於本應用程式', 'Access Control': 'Access Control', 'Admin is disabled because insecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Admin is disabled because unsecure channel': '管理功能(Admin)在不安全連線環境下自動關閉', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': '點此處進入管理介面', 'Administrator Password:': '管理員密碼:', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': '因為來自非安全通道,管理介面關閉', 'Are you sure you want to delete file "%s"?': '確定要刪除檔案"%s"?', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Are you sure you want to uninstall application "%s"': '確定要移除應用程式 "%s"', 'Are you sure you want to uninstall application "%s"?': '確定要移除應用程式 "%s"', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': '注意: 登入管理帳號需要安全連線(HTTPS)或是在本機連線(localhost).', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': '注意: 因為在測試模式不保證多執行緒安全性,也就是說不可以同時執行多個測試案例', 'ATTENTION: you cannot edit the running application!': '注意:不可編輯正在執行的應用程式!', 'Authentication': '驗證', 'Available Databases and Tables': '可提供的資料庫和資料表', 'Buy this book': 'Buy this book', 'cache': '快取記憶體', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': '不可空白', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': '無法編譯:應用程式中含有錯誤,請除錯後再試一次.', 'Change Password': '變更密碼', 'change password': '變更密碼', 'Check to delete': '打勾代表刪除', 'Check to delete:': '點選以示刪除:', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': '客戶端網址(IP)', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': '控件', 'Controllers': '控件', 'Copyright': '版權所有', 'Create new application': '創建應用程式', 'Current request': '目前網路資料要求(request)', 'Current response': '目前網路資料回應(response)', 'Current session': '目前網路連線資訊(session)', 'customize me!': '請調整我!', 'data uploaded': '資料已上傳', 'Database': '資料庫', 'Database %s select': '已選擇 %s 資料庫', 'Date and Time': '日期和時間', 'db': 'db', 'DB Model': '資料庫模組', 'Delete': '刪除', 'Delete:': '刪除:', 'Demo': 'Demo', 'Deploy on Google App Engine': '配置到 Google App Engine', 'Deployment Recipes': 'Deployment Recipes', 'Description': '描述', 'DESIGN': '設計', 'design': '設計', 'Design for': '設計為了', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': '完成!', 'Download': 'Download', 'E-mail': '電子郵件', 'EDIT': '編輯', 'Edit': '編輯', 'Edit application': '編輯應用程式', 'Edit current record': '編輯當前紀錄', 'edit profile': '編輯設定檔', 'Edit Profile': '編輯設定檔', 'Edit This App': '編輯本應用程式', 'Editing file': '編輯檔案', 'Editing file "%s"': '編輯檔案"%s"', 'Email and SMS': 'Email and SMS', 'Error logs for "%(app)s"': '"%(app)s"的錯誤紀錄', 'Errors': 'Errors', 'export as csv file': '以逗號分隔檔(csv)格式匯出', 'FAQ': 'FAQ', 'First name': '名', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Functions with no doctests will result in [passed] tests.': '沒有 doctests 的函式會顯示 [passed].', 'Group ID': '群組編號', 'Groups': 'Groups', 'Hello World': '嗨! 世界', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': '匯入/匯出', 'Index': '索引', 'insert new': '插入新資料', 'insert new %s': '插入新資料 %s', 'Installed applications': '已安裝應用程式', 'Internal State': '內部狀態', 'Introduction': 'Introduction', 'Invalid action': '不合法的動作(action)', 'Invalid email': '不合法的電子郵件', 'Invalid Query': '不合法的查詢', 'invalid request': '不合法的網路要求(request)', 'Key': 'Key', 'Language files (static strings) updated': '語言檔已更新', 'Languages': '各國語言', 'Last name': '姓', 'Last saved on:': '最後儲存時間:', 'Layout': '網頁配置', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'License for': '軟體版權為', 'Live Chat': 'Live Chat', 'login': '登入', 'Login': '登入', 'Login to the Administrative Interface': '登入到管理員介面', 'logout': '登出', 'Logout': '登出', 'Lost Password': '密碼遺忘', 'Main Menu': '主選單', 'Manage Cache': 'Manage Cache', 'Menu Model': '選單模組(menu)', 'Models': '資料模組', 'Modules': '程式模組', 'My Sites': 'My Sites', 'Name': '名字', 'New Record': '新紀錄', 'new record inserted': '已插入新紀錄', 'next 100 rows': '往後 100 筆', 'NO': '否', 'No databases in this application': '這應用程式不含資料庫', 'Online examples': '點此處進入線上範例', 'or import from csv file': '或是從逗號分隔檔(CSV)匯入', 'Origin': '原文', 'Original/Translation': '原文/翻譯', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': '密碼', "Password fields don't match": '密碼欄不匹配', 'Peeking at file': '選擇檔案', 'Plugins': 'Plugins', 'Powered by': '基於以下技術構建:', 'Preface': 'Preface', 'previous 100 rows': '往前 100 筆', 'Python': 'Python', 'Query:': '查詢:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': '紀錄', 'record does not exist': '紀錄不存在', 'Record ID': '紀錄編號', 'Record id': '紀錄編號', 'Register': '註冊', 'register': '註冊', 'Registration key': '註冊金鑰', 'Remember me (for 30 days)': '記住我(30 天)', 'Reset Password key': '重設密碼', 'Resolve Conflict file': '解決衝突檔案', 'Role': '角色', 'Rows in Table': '在資料表裏的資料', 'Rows selected': '筆資料被選擇', 'Saved file hash:': '檔案雜湊值已紀錄:', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': '狀態', 'Static files': '靜態檔案', 'Statistics': 'Statistics', 'Stylesheet': '網頁風格檔', 'submit': 'submit', 'Submit': '傳送', 'Support': 'Support', 'Sure you want to delete this object?': '確定要刪除此物件?', 'Table': '資料表', 'Table name': '資料表名稱', 'Testing application': '測試中的應用程式', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"查詢"是一個像 "db.表1.欄位1==\'值\'" 的條件式. 以"db.表1.欄位1==db.表2.欄位2"方式則相當於執行 JOIN SQL.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'There are no controllers': '沒有控件(controllers)', 'There are no models': '沒有資料庫模組(models)', 'There are no modules': '沒有程式模組(modules)', 'There are no static files': '沒有靜態檔案', 'There are no translators, only default language is supported': '沒有翻譯檔,只支援原始語言', 'There are no views': '沒有視圖', 'This App': 'This App', 'This is the %(filename)s template': '這是%(filename)s檔案的樣板(template)', 'Ticket': '問題單', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': '時間標記', 'Twitter': 'Twitter', 'Unable to check for upgrades': '無法做升級檢查', 'Unable to download': '無法下載', 'Unable to download app': '無法下載應用程式', 'unable to parse csv file': '無法解析逗號分隔檔(csv)', 'Update:': '更新:', 'Upload existing application': '更新存在的應用程式', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': '使用下列方式來組合更複雜的條件式, (...)&(...) 代表同時存在的條件, (...)|(...) 代表擇一的條件, ~(...)則代表反向條件.', 'User %(id)s Logged-in': '使用者 %(id)s 已登入', 'User %(id)s Registered': '使用者 %(id)s 已註冊', 'User ID': '使用者編號', 'Verify Password': '驗證密碼', 'Videos': 'Videos', 'View': '視圖', 'Views': '視圖', 'Welcome %s': '歡迎 %s', 'Welcome to web2py': '歡迎使用 web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'YES': '是', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!=': '!=', '!langcode!': 'it', '!langname!': 'Italiano', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ', '%(nrows)s records found': '%(nrows)s record trovati', '%d seconds ago': '%d secondi fa', '%s %%{row} deleted': '%s righe ("record") cancellate', '%s %%{row} updated': '%s righe ("record") modificate', '%s selected': '%s selezionato', '%Y-%m-%d': '%d/%m/%Y', '%Y-%m-%d %H:%M:%S': '%d/%m/%Y %H:%M:%S', '<': '<', '<=': '<=', '=': '=', '>': '>', '>=': '>=', '@markmin\x01Number of entries: **%s**': 'Numero di entità: **%s**', 'About': 'About', 'Access Control': 'Controllo Accessi', 'Add': 'Aggiungi', 'Administrative Interface': 'Interfaccia Amministrativa', 'Administrative interface': 'Interfaccia amministrativa', 'Ajax Recipes': 'Ajax Recipes', 'An error occured, please %s the page': "È stato rilevato un errore, prego %s la pagina", 'And': 'E', 'appadmin is disabled because insecure channel': 'Amministrazione (appadmin) disabilitata: comunicazione non sicura', 'Are you sure you want to delete this object?': 'Sicuro di voler cancellare questo oggetto ?', 'Available Databases and Tables': 'Database e tabelle disponibili', 'Back': 'Indietro', 'Buy this book': 'Compra questo libro', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Non può essere vuoto', 'Change password': 'Cambia Password', 'change password': 'Cambia password', 'Check to delete': 'Seleziona per cancellare', 'Clear': 'Resetta', 'Clear CACHE?': 'Resetta CACHE?', 'Clear DISK': 'Resetta DISK', 'Clear RAM': 'Resetta RAM', 'Client IP': 'Client IP', 'Close': 'Chiudi', 'Cognome': 'Cognome', 'Community': 'Community', 'Components and Plugins': 'Componenti and Plugin', 'contains': 'contiene', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Created By': 'Creato Da', 'Created On': 'Creato Il', 'CSV': 'CSV', 'CSV (hidden cols)': 'CSV (hidden cols)', 'Current request': 'Richiesta (request) corrente', 'Current response': 'Risposta (response) corrente', 'Current session': 'Sessione (session) corrente', 'customize me!': 'Personalizzami!', 'data uploaded': 'dati caricati', 'Database': 'Database', 'Database %s select': 'Database %s select', 'db': 'db', 'DB Model': 'Modello di DB', 'Delete': 'Cancella', 'Delete:': 'Cancella:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Descrizione', 'design': 'progetta', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentazione', "Don't know what to do?": 'Non sai cosa fare?', 'done!': 'fatto!', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit': 'Modifica', 'Edit current record': 'Modifica record corrente', 'edit profile': 'modifica profilo', 'Edit This App': 'Modifica questa applicazione', 'Email and SMS': 'Email e SMS', 'Email non valida': 'Email non valida', 'enter an integer between %(min)g and %(max)g': 'inserisci un intero tra %(min)g e %(max)g', 'Errors': 'Errori', 'Errors in form, please check it out.': 'Errori nel form, ricontrollalo', 'export as csv file': 'esporta come file CSV', 'Export:': 'Esporta:', 'FAQ': 'FAQ', 'First name': 'Nome', 'Forgot username?': 'Dimenticato lo username?', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Graph Model': 'Graph Model', 'Group %(group_id)s created': 'Group %(group_id)s created', 'Group ID': 'ID Gruppo', 'Group uniquely assigned to user %(id)s': 'Group uniquely assigned to user %(id)s', 'Groups': 'Groups', 'hello': 'hello', 'hello world': 'salve mondo', 'Hello World': 'Salve Mondo', 'Hello World in a flash!': 'Salve Mondo in un flash!', 'Home': 'Home', 'How did you get here?': 'Come sei arrivato qui?', 'HTML': 'HTML', 'import': 'importa', 'Import/Export': 'Importa/Esporta', 'Index': 'Indice', 'insert new': 'inserisci nuovo', 'insert new %s': 'inserisci nuovo %s', 'Internal State': 'Stato interno', 'Introduction': 'Introduzione', 'Invalid email': 'Email non valida', 'Invalid login': 'Login non valido', 'Invalid Query': 'Richiesta (query) non valida', 'invalid request': 'richiesta non valida', 'Is Active': "E' attivo", 'Key': 'Chiave', 'Last name': 'Cognome', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Logged in': 'Loggato', 'Logged out': 'Disconnesso', 'login': 'accesso', 'Login': 'Login', 'logout': 'uscita', 'Logout': 'Logout', 'Lost Password': 'Password Smarrita', 'Lost password?': 'Password smarrita?', 'lost password?': 'dimenticato la password?', 'Main Menu': 'Menu principale', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu Modelli', 'Modified By': 'Modificato da', 'Modified On': 'Modificato il', 'My Sites': 'My Sites', 'Name': 'Nome', 'New': 'Nuovo', 'New password': 'Nuova password', 'New Record': 'Nuovo elemento (record)', 'new record inserted': 'nuovo record inserito', 'next 100 rows': 'prossime 100 righe', 'No databases in this application': 'Nessun database presente in questa applicazione', 'No records found': 'Nessun record trovato', 'Nome': 'Nome', 'Non può essere vuoto': 'Non può essere vuoto', 'not authorized': 'non autorizzato', 'Object or table name': 'Oggeto o nome tabella', 'Old password': 'Vecchia password', 'Online examples': 'Vedere gli esempi', 'Or': 'O', 'or import from csv file': 'oppure importa da file CSV', 'Origin': 'Origine', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', "Password fields don't match": 'I campi password non sono uguali', 'please input your password again': 'perfavore reimmeti la tua password', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': '100 righe precedenti', 'Profile': 'Profilo', 'pygraphviz library not found': 'pygraphviz library not found', 'Python': 'Python', 'Query:': 'Richiesta (query):', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'Record', 'record does not exist': 'il record non esiste', 'Record ID': 'Record ID', 'Record id': 'Record id', 'Register': 'Registrati', 'register': 'registrazione', 'Registration identifier': 'Registration identifier', 'Registration key': 'Chiave di Registazione', 'Registration successful': 'Registrazione avvenuta', 'reload': 'reload', 'Remember me (for 30 days)': 'Ricordami (per 30 giorni)', 'Request reset password': 'Richiedi il reset della password', 'Reset Password key': 'Resetta chiave Password ', 'Role': 'Ruolo', 'Rows in Table': 'Righe nella tabella', 'Rows selected': 'Righe selezionate', 'Save model as...': 'Salva modello come...', 'Save profile': 'Salva profilo', 'Search': 'Ricerca', 'Semantic': 'Semantic', 'Services': 'Servizi', 'Size of cache:': 'Size of cache:', 'starts with': 'comincia con', 'state': 'stato', 'Statistics': 'Statistics', 'Stylesheet': 'Foglio di stile (stylesheet)', 'submit': 'Inviai', 'Submit': 'Invia', 'Support': 'Support', 'Sure you want to delete this object?': 'Vuoi veramente cancellare questo oggetto?', 'Table': 'tabella', 'Table name': 'Nome tabella', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La richiesta (query) è una condizione come ad esempio "db.tabella1.campo1==\'valore\'". Una condizione come "db.tabella1.campo1==db.tabella2.campo2" produce un "JOIN" SQL.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'L\'output del file è un "dictionary" che è stato visualizzato dalla vista %s', 'The Views': 'The Views', 'This App': 'This App', 'This is a copy of the scaffolding application': "Questa è una copia dell'applicazione di base (scaffold)", 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Ora (timestamp)', 'too short': 'troppo corto', 'Traceback': 'Traceback', 'TSV (Excel compatible)': 'TSV (Excel compatibile)', 'TSV (Excel compatible, hidden cols)': 'TSV (Excel compatibile, hidden cols)', 'Twitter': 'Twitter', 'unable to parse csv file': 'non riesco a decodificare questo file CSV', 'Update': 'Aggiorna', 'Update:': 'Aggiorna:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Per costruire richieste (query) più complesse si usano (...)&(...) come "e" (AND), (...)|(...) come "o" (OR), e ~(...) come negazione (NOT).', 'User %(id)s Logged-in': 'User %(id)s Logged-in', 'User %(id)s Logged-out': 'User %(id)s Logged-out', 'User %(id)s Password changed': 'User %(id)s Password changed', 'User %(id)s Password reset': 'User %(id)s Password reset', 'User %(id)s Profile updated': 'User %(id)s Profile updated', 'User %(id)s Registered': 'User %(id)s Registered', 'User ID': 'ID Utente', 'value already in database or empty': 'valore già presente nel database o vuoto', 'Verify Password': 'Verifica Password', 'Videos': 'Videos', 'View': 'Vista', 'Welcome': 'Welcome', 'Welcome %s': 'Benvenuto %s', 'Welcome to web2py': 'Benvenuto su web2py', 'Welcome to web2py!': 'Benvenuto in web2py!', 'Which called the function %s located in the file %s': 'che ha chiamato la funzione %s presente nel file %s', 'XML': 'XML', 'You are successfully running web2py': 'Stai eseguendo web2py con successo', 'You can modify this application and adapt it to your needs': 'Puoi modificare questa applicazione adattandola alle tue necessità', 'You visited the url %s': "Hai visitato l'URL %s", }
Python
# coding: utf8 { '!langcode!': 'es', '!langname!': 'Español', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"actualice" es una expresión opcional como "campo1=\'nuevo_valor\'". No se puede actualizar o eliminar resultados de un JOIN', '%s %%{row} deleted': '%s filas eliminadas', '%s %%{row} updated': '%s filas actualizadas', '%s selected': '%s seleccionado(s)', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(algo como "eso-eso")', 'A new version of web2py is available': 'Hay una nueva versión de web2py disponible', 'A new version of web2py is available: %s': 'Hay una nueva versión de web2py disponible: %s', 'about': 'acerca de', 'About': 'Acerca de', 'About application': 'Acerca de la aplicación', 'Access Control': 'Control de Acceso', 'additional code for your application': 'código adicional para su aplicación', 'admin disabled because no admin password': ' por falta de contraseña', 'admin disabled because not supported on google app engine': 'admin deshabilitado, no es soportado en GAE', 'admin disabled because unable to access password file': 'admin deshabilitado, imposible acceder al archivo con la contraseña', 'Admin is disabled because insecure channel': 'Admin deshabilitado, el canal no es seguro', 'Admin is disabled because unsecure channel': 'Admin deshabilitado, el canal no es seguro', 'Administrative Interface': 'Interfaz Administrativa', 'Administrative interface': 'Interfaz administrativa', 'Administrator Password:': 'Contraseña del Administrador:', 'Ajax Recipes': 'Recetas AJAX', 'and rename it (required):': 'y renombrela (requerido):', 'and rename it:': ' y renombrelo:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'admin deshabilitado, el canal no es seguro', 'application "%s" uninstalled': 'aplicación "%s" desinstalada', 'application compiled': 'aplicación compilada', 'application is compiled and cannot be designed': 'la aplicación está compilada y no puede ser modificada', 'Are you sure you want to delete file "%s"?': '¿Está seguro que desea eliminar el archivo "%s"?', 'Are you sure you want to delete this object?': '¿Está seguro que desea borrar este objeto?', 'Are you sure you want to uninstall application "%s"': '¿Está seguro que desea desinstalar la aplicación "%s"', 'Are you sure you want to uninstall application "%s"?': '¿Está seguro que desea desinstalar la aplicación "%s"?', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENCION: Inicio de sesión requiere una conexión segura (HTTPS) o localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENCION: NO EJECUTE VARIAS PRUEBAS SIMULTANEAMENTE, NO SON THREAD SAFE.', 'ATTENTION: you cannot edit the running application!': 'ATENCION: no puede modificar la aplicación que está ejecutandose!', 'Authentication': 'Autenticación', 'Available Databases and Tables': 'Bases de datos y tablas disponibles', 'Buy this book': 'Compra este libro', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Llaves de la Cache', 'cache, errors and sessions cleaned': 'cache, errores y sesiones eliminados', 'Cannot be empty': 'No puede estar vacío', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'No se puede compilar: hay errores en su aplicación. Depure, corrija errores y vuelva a intentarlo.', 'cannot create file': 'no es posible crear archivo', 'cannot upload file "%(filename)s"': 'no es posible subir archivo "%(filename)s"', 'Change Password': 'Cambie la contraseña', 'change password': 'cambie la contraseña', 'check all': 'marcar todos', 'Check to delete': 'Marque para eliminar', 'clean': 'limpiar', 'Clear CACHE?': '¿Limpiar CACHE?', 'Clear DISK': '¿Limpiar DISCO', 'Clear RAM': '¿Limpiar RAM', 'click to check for upgrades': 'haga clic para buscar actualizaciones', 'Client IP': 'IP del Cliente', 'Community': 'Comunidad', 'compile': 'compilar', 'compiled application removed': 'aplicación compilada eliminada', 'Components and Plugins': 'Componentes y Plugins', 'Controller': 'Controlador', 'Controllers': 'Controladores', 'controllers': 'controladores', 'Copyright': 'Copyright', 'create file with filename:': 'cree archivo con nombre:', 'Create new application': 'Cree una nueva aplicación', 'create new application:': 'nombre de la nueva aplicación:', 'crontab': 'crontab', 'Current request': 'Solicitud en curso', 'Current response': 'Respuesta en curso', 'Current session': 'Sesión en curso', 'currently saved or': 'actualmente guardado o', 'customize me!': 'Adaptame!', 'data uploaded': 'datos subidos', 'Database': 'base de datos', 'Database %s select': 'selección en base de datos %s', 'database administration': 'administración base de datos', 'Date and Time': 'Fecha y Hora', 'db': 'db', 'DB Model': 'Modelo "DB"', 'defines tables': 'define tablas', 'Delete': 'Eliminar', 'delete': 'eliminar', 'delete all checked': 'eliminar marcados', 'Delete:': 'Eliminar:', 'Demo': 'Demo', 'Deploy on Google App Engine': 'Despliegue en Google App Engine', 'Deployment Recipes': 'Recetas de despliegue', 'Description': 'Descripción', 'DESIGN': 'DISEÑO', 'design': 'modificar', 'Design for': 'Diseño por', 'DISK': 'DISK', 'Disk Cache Keys': 'Llaves de Cache en Disco', 'Disk Cleared': 'Disco limpiado', 'Documentation': 'Documentación', "Don't know what to do?": "¿No sabe que hacer?", 'done!': 'listo!', 'Download': 'Download', 'E-mail': 'Correo electrónico', 'EDIT': 'EDITAR', 'edit': 'editar', 'Edit': 'Editar', 'Edit application': 'Editar aplicación', 'edit controller': 'editar controlador', 'Edit current record': 'Edite el registro actual', 'edit profile': 'editar perfil', 'Edit Profile': 'Editar Perfil', 'Edit This App': 'Edite esta App', 'Editing file': 'Editando archivo', 'Editing file "%s"': 'Editando archivo "%s"', 'Email and SMS': 'Correo electrónico y SMS', 'Error logs for "%(app)s"': 'Bitácora de errores en "%(app)s"', 'Errors': 'Errores', 'errors': 'errores', 'export as csv file': 'exportar como archivo CSV', 'exposes': 'expone', 'extends': 'extiende', 'failed to reload module': 'la recarga del módulo ha fallado', 'FAQ': 'FAQ', 'file "%(filename)s" created': 'archivo "%(filename)s" creado', 'file "%(filename)s" deleted': 'archivo "%(filename)s" eliminado', 'file "%(filename)s" uploaded': 'archivo "%(filename)s" subido', 'file "%(filename)s" was not deleted': 'archivo "%(filename)s" no fué eliminado', 'file "%s" of %s restored': 'archivo "%s" de %s restaurado', 'file changed on disk': 'archivo modificado en el disco', 'file does not exist': 'archivo no existe', 'file saved on %(time)s': 'archivo guardado %(time)s', 'file saved on %s': 'archivo guardado %s', 'First name': 'Nombre', 'Forms and Validators': 'Formularios y validadores', 'Free Applications': 'Aplicaciones Libres', 'Functions with no doctests will result in [passed] tests.': 'Funciones sin doctests equivalen a pruebas [aceptadas].', 'Group ID': 'ID de Grupo', 'Groups': 'Groupos', 'Hello World': 'Hola Mundo', 'help': 'ayuda', 'Home': 'Home', 'How did you get here?': '¿Cómo llegaste aquí?', 'htmledit': 'htmledit', 'import': 'importar', 'Import/Export': 'Importar/Exportar', 'includes': 'incluye', 'Index': 'Indice', 'insert new': 'inserte nuevo', 'insert new %s': 'inserte nuevo %s', 'Installed applications': 'Aplicaciones instaladas', 'internal error': 'error interno', 'Internal State': 'Estado Interno', 'Introduction': 'Introducción', 'Invalid action': 'Acción inválida', 'Invalid email': 'Correo electrónico inválido', 'invalid password': 'contraseña inválida', 'Invalid Query': 'Consulta inválida', 'invalid request': 'solicitud inválida', 'invalid ticket': 'tiquete inválido', 'Key': 'Llave', 'language file "%(filename)s" created/updated': 'archivo de lenguaje "%(filename)s" creado/actualizado', 'Language files (static strings) updated': 'Archivos de lenguaje (cadenas estáticas) actualizados', 'languages': 'lenguajes', 'Languages': 'Lenguajes', 'languages updated': 'lenguajes actualizados', 'Last name': 'Apellido', 'Last saved on:': 'Guardado en:', 'Layout': 'Diseño de página', 'Layout Plugins': 'Plugins de diseño', 'Layouts': 'Diseños de páginas', 'License for': 'Licencia para', 'Live Chat': 'Chat en vivo', 'loading...': 'cargando...', 'login': 'inicio de sesión', 'Login': 'Inicio de sesión', 'Login to the Administrative Interface': 'Inicio de sesión para la Interfaz Administrativa', 'logout': 'fin de sesión', 'Logout': 'Fin de sesión', 'Lost Password': 'Contraseña perdida', 'lost password?': '¿Olvido la contraseña?', 'Main Menu': 'Menú principal', 'Manage Cache': 'Manejar la Cache', 'Menu Model': 'Modelo "menu"', 'merge': 'combinar', 'Models': 'Modelos', 'models': 'modelos', 'Modules': 'Módulos', 'modules': 'módulos', 'My Sites': 'Mis Sitios', 'Name': 'Nombre', 'new application "%s" created': 'nueva aplicación "%s" creada', 'New Record': 'Registro nuevo', 'new record inserted': 'nuevo registro insertado', 'next 100 rows': '100 filas siguientes', 'NO': 'NO', 'No databases in this application': 'No hay bases de datos en esta aplicación', 'Online examples': 'Ejemplos en línea', 'or import from csv file': 'o importar desde archivo CSV', 'or provide application url:': 'o provea URL de la aplicación:', 'Origin': 'Origen', 'Original/Translation': 'Original/Traducción', 'Other Plugins': 'Otros Plugins', 'Other Recipes': 'Otas Recetas', 'Overview': 'Resumen', 'pack all': 'empaquetar todo', 'pack compiled': 'empaquete compiladas', 'Password': 'Contraseña', 'Peeking at file': 'Visualizando archivo', 'Plugins': 'Plugins', 'Powered by': 'Este sitio usa', 'Preface': 'Preface', 'previous 100 rows': '100 filas anteriores', 'Python': 'Python', 'Query:': 'Consulta:', 'Quick Examples': 'Ejemplos Rápidos', 'RAM': 'RAM', 'RAM Cache Keys':'Llaves de la RAM Cache', 'Ram Cleared': 'Ram Limpiada', 'Recipes': 'Recetas', 'Record': 'registro', 'record does not exist': 'el registro no existe', 'Record ID': 'ID de Registro', 'Record id': 'id de registro', 'Register': 'Registrese', 'register': 'registrese', 'Registration key': 'Llave de Registro', 'remove compiled': 'eliminar compiladas', 'Reset Password key': 'Restaurar Llave de la Contraseña', 'Resolve Conflict file': 'archivo Resolución de Conflicto', 'restore': 'restaurar', 'revert': 'revertir', 'Role': 'Rol', 'Rows in Table': 'Filas en la tabla', 'Rows selected': 'Filas seleccionadas', 'save': 'guardar', 'Saved file hash:': 'Hash del archivo guardado:', 'Semantic': 'Semantica', 'Services': 'Servicios', 'session expired': 'sesión expirada', 'shell': 'terminal', 'site': 'sitio', 'Size of cache:': 'Tamaño del Cache:', 'some files could not be removed': 'algunos archivos no pudieron ser removidos', 'state': 'estado', 'static': 'estáticos', 'Static files': 'Archivos estáticos', 'Statistics': 'Estadísticas', 'Stylesheet': 'Hoja de estilo', 'submit': 'enviar', 'Support': 'Soporte', 'Sure you want to delete this object?': '¿Está seguro que desea eliminar este objeto?', 'Table': 'tabla', 'Table name': 'Nombre de la tabla', 'test': 'probar', 'Testing application': 'Probando aplicación', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "consulta" es una condición como "db.tabla1.campo1==\'valor\'". Algo como "db.tabla1.campo1==db.tabla2.campo2" resulta en un JOIN SQL.', 'the application logic, each URL path is mapped in one exposed function in the controller': 'la lógica de la aplicación, cada ruta URL se mapea en una función expuesta en el controlador', 'The Core': 'El Núcleo', 'the data representation, define database tables and sets': 'la representación de datos, define tablas y conjuntos de base de datos', 'The output of the file is a dictionary that was rendered by the view %s': 'La salida de dicha función es un diccionario que es desplegado por la vista %s', 'the presentations layer, views are also known as templates': 'la capa de presentación, las vistas también son llamadas plantillas', 'The Views': 'Las Vistas', 'There are no controllers': 'No hay controladores', 'There are no models': 'No hay modelos', 'There are no modules': 'No hay módulos', 'There are no static files': 'No hay archivos estáticos', 'There are no translators, only default language is supported': 'No hay traductores, sólo el lenguaje por defecto es soportado', 'There are no views': 'No hay vistas', 'these files are served without processing, your images go here': 'estos archivos son servidos sin procesar, sus imágenes van aquí', 'This App': 'Esta Aplicación', 'This is a copy of the scaffolding application': 'Esta es una copia de la aplicación de andamiaje', 'This is the %(filename)s template': 'Esta es la plantilla %(filename)s', 'Ticket': 'Tiquete', 'Time in Cache (h:m:s)': 'Tiempo en Cache (h:m:s)', 'Timestamp': 'Marca de tiempo', 'to previous version.': 'a la versión previa.', 'translation strings for the application': 'cadenas de carácteres de traducción para la aplicación', 'try': 'intente', 'try something like': 'intente algo como', 'Twitter': 'Twitter', 'Unable to check for upgrades': 'No es posible verificar la existencia de actualizaciones', 'unable to create application "%s"': 'no es posible crear la aplicación "%s"', 'unable to delete file "%(filename)s"': 'no es posible eliminar el archivo "%(filename)s"', 'Unable to download': 'No es posible la descarga', 'Unable to download app': 'No es posible descarga la aplicación', 'unable to parse csv file': 'no es posible analizar el archivo CSV', 'unable to uninstall "%s"': 'no es posible instalar "%s"', 'uncheck all': 'desmarcar todos', 'uninstall': 'desinstalar', 'update': 'actualizar', 'update all languages': 'actualizar todos los lenguajes', 'Update:': 'Actualice:', 'upload application:': 'subir aplicación:', 'Upload existing application': 'Suba esta aplicación', 'upload file:': 'suba archivo:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, y ~(...) para NOT, para crear consultas más complejas.', 'User ID': 'ID de Usuario', 'versioning': 'versiones', 'Videos': 'Videos', 'view': 'vista', 'View': 'Vista', 'Views': 'Vistas', 'views': 'vistas', 'web2py is up to date': 'web2py está actualizado', 'web2py Recent Tweets': 'Tweets Recientes de web2py', 'Welcome': 'Bienvenido', 'Welcome %s': 'Bienvenido %s', 'Welcome to web2py': 'Bienvenido a web2py', 'Welcome to web2py!': '¡Bienvenido to web2py!', 'Which called the function %s located in the file %s': 'La cual llamó la función %s localizada en el archivo %s', 'YES': 'SÍ', 'You are successfully running web2py': 'Usted está ejecutando web2py exitosamente', 'You can modify this application and adapt it to your needs': 'Usted puede modificar esta aplicación y adaptarla a sus necesidades', 'You visited the url %s': 'Usted visitó la url %s', }
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'выбрана': ['выбраны','выбрано'], 'запись': ['записи','записей'], 'изменена': ['изменены','изменено'], 'строка': ['строки','строк'], 'удалена': ['удалены','удалено'], 'день': ['дня', 'дней'], 'месяц': ['месяца','месяцев'], 'неделю': ['недели','недель'], 'год': ['года','лет'], 'час': ['часа','часов'], 'минуту': ['минуты','минут'], 'секунду': ['секунды','секунд'], }
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'account': ['accounts'], 'book': ['books'], 'is': ['are'], 'man': ['men'], 'miss': ['misses'], 'person': ['people'], 'quark': ['quarks'], 'shop': ['shops'], 'this': ['these'], 'was': ['were'], 'woman': ['women'], }
Python
# coding: utf8 { '!langcode!': 'cs-cz', '!langname!': 'čeština', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': 'Kolonka "Upravit" je nepovinný výraz, například "pole1=\'nováhodnota\'". Výsledky databázového JOINu nemůžete mazat ani upravovat.', '"User Exception" debug mode. An error ticket could be issued!': '"User Exception" debug mode. An error ticket could be issued!', '%%{Row} in Table': '%%{řádek} v tabulce', '%%{Row} selected': 'označených %%{řádek}', '%s %%{row} deleted': '%s smazaných %%{záznam}', '%s %%{row} updated': '%s upravených %%{záznam}', '%s selected': '%s označených', '%Y-%m-%d': '%d.%m.%Y', '%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', '(requires internet access)': '(vyžaduje připojení k internetu)', '(requires internet access, experimental)': '(requires internet access, experimental)', '(something like "it-it")': '(například "cs-cs")', '@markmin\x01(file **gluon/contrib/plural_rules/%s.py** is not found)': '(soubor **gluon/contrib/plural_rules/%s.py** nenalezen)', '@markmin\x01Searching: **%s** %%{file}': 'Hledání: **%s** %%{soubor}', 'About': 'O programu', 'About application': 'O aplikaci', 'Access Control': 'Řízení přístupu', 'Add breakpoint': 'Přidat bod přerušení', 'Additional code for your application': 'Další kód pro Vaši aplikaci', 'Admin design page': 'Admin design page', 'Admin language': 'jazyk rozhraní', 'Administrative interface': 'pro administrátorské rozhraní klikněte sem', 'Administrative Interface': 'Administrátorské rozhraní', 'administrative interface': 'rozhraní pro správu', 'Administrator Password:': 'Administrátorské heslo:', 'Ajax Recipes': 'Recepty s ajaxem', 'An error occured, please %s the page': 'An error occured, please %s the page', 'and rename it:': 'a přejmenovat na:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin je zakázaná bez zabezpečeného spojení', 'Application': 'Application', 'application "%s" uninstalled': 'application "%s" odinstalována', 'application compiled': 'aplikace zkompilována', 'Application name:': 'Název aplikace:', 'are not used': 'nepoužita', 'are not used yet': 'ještě nepoužita', 'Are you sure you want to delete this object?': 'Opravdu chcete odstranit tento objekt?', 'Are you sure you want to uninstall application "%s"?': 'Opravdu chcete odinstalovat aplikaci "%s"?', 'arguments': 'arguments', 'at char %s': 'at char %s', 'at line %s': 'at line %s', 'ATTENTION:': 'ATTENTION:', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.', 'Available Databases and Tables': 'Dostupné databáze a tabulky', 'back': 'zpět', 'Back to wizard': 'Back to wizard', 'Basics': 'Basics', 'Begin': 'Začít', 'breakpoint': 'bod přerušení', 'Breakpoints': 'Body přerušení', 'breakpoints': 'body přerušení', 'Buy this book': 'Koupit web2py knihu', 'Cache': 'Cache', 'cache': 'cache', 'Cache Keys': 'Klíče cache', 'cache, errors and sessions cleaned': 'cache, chyby a relace byly pročištěny', 'can be a git repo': 'může to být git repo', 'Cancel': 'Storno', 'Cannot be empty': 'Nemůže být prázdné', 'Change Admin Password': 'Změnit heslo pro správu', 'Change admin password': 'Změnit heslo pro správu aplikací', 'Change password': 'Změna hesla', 'check all': 'vše označit', 'Check for upgrades': 'Zkusit aktualizovat', 'Check to delete': 'Označit ke smazání', 'Check to delete:': 'Označit ke smazání:', 'Checking for upgrades...': 'Zjišťuji, zda jsou k dispozici aktualizace...', 'Clean': 'Pročistit', 'Clear CACHE?': 'Vymazat CACHE?', 'Clear DISK': 'Vymazat DISK', 'Clear RAM': 'Vymazat RAM', 'Click row to expand traceback': 'Pro rozbalení stopy, klikněte na řádek', 'Click row to view a ticket': 'Pro zobrazení chyby (ticketu), klikněte na řádku...', 'Client IP': 'IP adresa klienta', 'code': 'code', 'Code listing': 'Code listing', 'collapse/expand all': 'vše sbalit/rozbalit', 'Community': 'Komunita', 'Compile': 'Zkompilovat', 'compiled application removed': 'zkompilovaná aplikace smazána', 'Components and Plugins': 'Komponenty a zásuvné moduly', 'Condition': 'Podmínka', 'continue': 'continue', 'Controller': 'Kontrolér (Controller)', 'Controllers': 'Kontroléry', 'controllers': 'kontroléry', 'Copyright': 'Copyright', 'Count': 'Počet', 'Create': 'Vytvořit', 'create file with filename:': 'vytvořit soubor s názvem:', 'created by': 'vytvořil', 'Created By': 'Vytvořeno - kým', 'Created On': 'Vytvořeno - kdy', 'crontab': 'crontab', 'Current request': 'Aktuální požadavek', 'Current response': 'Aktuální odpověď', 'Current session': 'Aktuální relace', 'currently running': 'právě běží', 'currently saved or': 'uloženo nebo', 'customize me!': 'upravte mě!', 'data uploaded': 'data nahrána', 'Database': 'Rozhraní databáze', 'Database %s select': 'databáze %s výběr', 'Database administration': 'Database administration', 'database administration': 'správa databáze', 'Date and Time': 'Datum a čas', 'day': 'den', 'db': 'db', 'DB Model': 'Databázový model', 'Debug': 'Ladění', 'defines tables': 'defines tables', 'Delete': 'Smazat', 'delete': 'smazat', 'delete all checked': 'smazat vše označené', 'delete plugin': 'delete plugin', 'Delete this file (you will be asked to confirm deletion)': 'Smazat tento soubor (budete požádán o potvrzení mazání)', 'Delete:': 'Smazat:', 'deleted after first hit': 'smazat po prvním dosažení', 'Demo': 'Demo', 'Deploy': 'Nahrát', 'Deploy on Google App Engine': 'Nahrát na Google App Engine', 'Deploy to OpenShift': 'Nahrát na OpenShift', 'Deployment Recipes': 'Postupy pro deployment', 'Description': 'Popis', 'design': 'návrh', 'Detailed traceback description': 'Podrobný výpis prostředí', 'details': 'podrobnosti', 'direction: ltr': 'směr: ltr', 'Disable': 'Zablokovat', 'DISK': 'DISK', 'Disk Cache Keys': 'Klíče diskové cache', 'Disk Cleared': 'Disk smazán', 'docs': 'dokumentace', 'Documentation': 'Dokumentace', "Don't know what to do?": 'Nevíte kudy kam?', 'done!': 'hotovo!', 'Download': 'Stáhnout', 'download layouts': 'stáhnout moduly rozvržení stránky', 'download plugins': 'stáhnout zásuvné moduly', 'E-mail': 'E-mail', 'Edit': 'Upravit', 'edit all': 'edit all', 'Edit application': 'Správa aplikace', 'edit controller': 'edit controller', 'Edit current record': 'Upravit aktuální záznam', 'Edit Profile': 'Upravit profil', 'edit views:': 'upravit pohled:', 'Editing file "%s"': 'Úprava souboru "%s"', 'Editing Language file': 'Úprava jazykového souboru', 'Editing Plural Forms File': 'Editing Plural Forms File', 'Email and SMS': 'Email a SMS', 'Enable': 'Odblokovat', 'enter a number between %(min)g and %(max)g': 'zadejte číslo mezi %(min)g a %(max)g', 'enter an integer between %(min)g and %(max)g': 'zadejte celé číslo mezi %(min)g a %(max)g', 'Error': 'Chyba', 'Error logs for "%(app)s"': 'Seznam výskytu chyb pro aplikaci "%(app)s"', 'Error snapshot': 'Snapshot chyby', 'Error ticket': 'Ticket chyby', 'Errors': 'Chyby', 'Exception %(extype)s: %(exvalue)s': 'Exception %(extype)s: %(exvalue)s', 'Exception %s': 'Exception %s', 'Exception instance attributes': 'Prvky instance výjimky', 'Expand Abbreviation': 'Expand Abbreviation', 'export as csv file': 'exportovat do .csv souboru', 'exposes': 'vystavuje', 'exposes:': 'vystavuje funkce:', 'extends': 'rozšiřuje', 'failed to compile file because:': 'soubor se nepodařilo zkompilovat, protože:', 'FAQ': 'Často kladené dotazy', 'File': 'Soubor', 'file': 'soubor', 'file "%(filename)s" created': 'file "%(filename)s" created', 'file saved on %(time)s': 'soubor uložen %(time)s', 'file saved on %s': 'soubor uložen %s', 'Filename': 'Název souboru', 'filter': 'filtr', 'Find Next': 'Najít další', 'Find Previous': 'Najít předchozí', 'First name': 'Křestní jméno', 'Forgot username?': 'Zapomněl jste svoje přihlašovací jméno?', 'forgot username?': 'zapomněl jste svoje přihlašovací jméno?', 'Forms and Validators': 'Formuláře a validátory', 'Frames': 'Frames', 'Free Applications': 'Aplikace zdarma', 'Functions with no doctests will result in [passed] tests.': 'Functions with no doctests will result in [passed] tests.', 'Generate': 'Vytvořit', 'Get from URL:': 'Stáhnout z internetu:', 'Git Pull': 'Git Pull', 'Git Push': 'Git Push', 'Globals##debug': 'Globální proměnné', 'go!': 'OK!', 'Goto': 'Goto', 'graph model': 'graph model', 'Group %(group_id)s created': 'Skupina %(group_id)s vytvořena', 'Group ID': 'ID skupiny', 'Groups': 'Skupiny', 'Hello World': 'Ahoj světe', 'Help': 'Nápověda', 'Hide/Show Translated strings': 'Skrýt/Zobrazit přeložené texty', 'Hits': 'Kolikrát dosaženo', 'Home': 'Domovská stránka', 'honored only if the expression evaluates to true': 'brát v potaz jen když se tato podmínka vyhodnotí kladně', 'How did you get here?': 'Jak jste se sem vlastně dostal?', 'If start the upgrade, be patient, it may take a while to download': 'If start the upgrade, be patient, it may take a while to download', 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.': 'If the report above contains a ticket number it indicates a failure in executing the controller, before any attempt to execute the doctests. This is usually due to an indentation error or an error outside function code.\nA green title indicates that all tests (if defined) passed. In this case test results are not shown.', 'import': 'import', 'Import/Export': 'Import/Export', 'includes': 'zahrnuje', 'Index': 'Index', 'insert new': 'vložit nový záznam ', 'insert new %s': 'vložit nový záznam %s', 'inspect attributes': 'inspect attributes', 'Install': 'Instalovat', 'Installed applications': 'Nainstalované aplikace', 'Interaction at %s line %s': 'Interakce v %s, na řádce %s', 'Interactive console': 'Interaktivní příkazová řádka', 'Internal State': 'Vnitřní stav', 'Introduction': 'Úvod', 'Invalid email': 'Neplatný email', 'Invalid password': 'Nesprávné heslo', 'invalid password.': 'neplatné heslo', 'Invalid Query': 'Neplatný dotaz', 'invalid request': 'Neplatný požadavek', 'Is Active': 'Je aktivní', 'It is %s %%{day} today.': 'Dnes je to %s %%{den}.', 'Key': 'Klíč', 'Key bindings': 'Vazby klíčů', 'Key bindings for ZenCoding Plugin': 'Key bindings for ZenCoding Plugin', 'languages': 'jazyky', 'Languages': 'Jazyky', 'Last name': 'Příjmení', 'Last saved on:': 'Naposledy uloženo:', 'Layout': 'Rozvržení stránky (layout)', 'Layout Plugins': 'Moduly rozvržení stránky (Layout Plugins)', 'Layouts': 'Rozvržení stránek', 'License for': 'Licence pro', 'Line number': 'Číslo řádku', 'LineNo': 'Č.řádku', 'Live Chat': 'Online pokec', 'loading...': 'nahrávám...', 'locals': 'locals', 'Locals##debug': 'Lokální proměnné', 'Logged in': 'Přihlášení proběhlo úspěšně', 'Logged out': 'Odhlášení proběhlo úspěšně', 'Login': 'Přihlásit se', 'login': 'přihlásit se', 'Login to the Administrative Interface': 'Přihlásit se do Správce aplikací', 'logout': 'odhlásit se', 'Logout': 'Odhlásit se', 'Lost Password': 'Zapomněl jste heslo', 'Lost password?': 'Zapomněl jste heslo?', 'lost password?': 'zapomněl jste heslo?', 'Manage': 'Manage', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Model rozbalovací nabídky', 'Models': 'Modely', 'models': 'modely', 'Modified By': 'Změněno - kým', 'Modified On': 'Změněno - kdy', 'Modules': 'Moduly', 'modules': 'moduly', 'My Sites': 'Správa aplikací', 'Name': 'Jméno', 'new application "%s" created': 'nová aplikace "%s" vytvořena', 'New Application Wizard': 'Nový průvodce aplikací', 'New application wizard': 'Nový průvodce aplikací', 'New password': 'Nové heslo', 'New Record': 'Nový záznam', 'new record inserted': 'nový záznam byl založen', 'New simple application': 'Vytvořit primitivní aplikaci', 'next': 'next', 'next 100 rows': 'dalších 100 řádků', 'No databases in this application': 'V této aplikaci nejsou žádné databáze', 'No Interaction yet': 'Ještě žádná interakce nenastala', 'No ticket_storage.txt found under /private folder': 'Soubor ticket_storage.txt v adresáři /private nenalezen', 'Object or table name': 'Objekt či tabulka', 'Old password': 'Původní heslo', 'online designer': 'online návrhář', 'Online examples': 'Příklady online', 'Open new app in new window': 'Open new app in new window', 'or alternatively': 'or alternatively', 'Or Get from URL:': 'Or Get from URL:', 'or import from csv file': 'nebo importovat z .csv souboru', 'Origin': 'Původ', 'Original/Translation': 'Originál/Překlad', 'Other Plugins': 'Ostatní moduly', 'Other Recipes': 'Ostatní zásuvné moduly', 'Overview': 'Přehled', 'Overwrite installed app': 'Přepsat instalovanou aplikaci', 'Pack all': 'Zabalit', 'Pack compiled': 'Zabalit zkompilované', 'pack plugin': 'pack plugin', 'password': 'heslo', 'Password': 'Heslo', "Password fields don't match": 'Hesla se neshodují', 'Peeking at file': 'Peeking at file', 'Please': 'Prosím', 'Plugin "%s" in application': 'Plugin "%s" in application', 'plugins': 'zásuvné moduly', 'Plugins': 'Zásuvné moduly', 'Plural Form #%s': 'Plural Form #%s', 'Plural-Forms:': 'Množná čísla:', 'Powered by': 'Poháněno', 'Preface': 'Předmluva', 'previous 100 rows': 'předchozích 100 řádků', 'Private files': 'Soukromé soubory', 'private files': 'soukromé soubory', 'profile': 'profil', 'Project Progress': 'Vývoj projektu', 'Python': 'Python', 'Query:': 'Dotaz:', 'Quick Examples': 'Krátké příklady', 'RAM': 'RAM', 'RAM Cache Keys': 'Klíče RAM Cache', 'Ram Cleared': 'RAM smazána', 'Readme': 'Nápověda', 'Recipes': 'Postupy jak na to', 'Record': 'Záznam', 'record does not exist': 'záznam neexistuje', 'Record ID': 'ID záznamu', 'Record id': 'id záznamu', 'refresh': 'obnovte', 'register': 'registrovat', 'Register': 'Zaregistrovat se', 'Registration identifier': 'Registrační identifikátor', 'Registration key': 'Registrační klíč', 'reload': 'reload', 'Reload routes': 'Znovu nahrát cesty', 'Remember me (for 30 days)': 'Zapamatovat na 30 dní', 'Remove compiled': 'Odstranit zkompilované', 'Removed Breakpoint on %s at line %s': 'Bod přerušení smazán - soubor %s na řádce %s', 'Replace': 'Zaměnit', 'Replace All': 'Zaměnit vše', 'request': 'request', 'Reset Password key': 'Reset registračního klíče', 'response': 'response', 'restart': 'restart', 'restore': 'obnovit', 'Retrieve username': 'Získat přihlašovací jméno', 'return': 'return', 'revert': 'vrátit se k původnímu', 'Role': 'Role', 'Rows in Table': 'Záznamy v tabulce', 'Rows selected': 'Záznamů zobrazeno', 'rules are not defined': 'pravidla nejsou definována', "Run tests in this file (to run all files, you may also use the button labelled 'test')": "Spustí testy v tomto souboru (ke spuštění všech testů, použijte tlačítko 'test')", 'Running on %s': 'Běží na %s', 'Save': 'Uložit', 'Save file:': 'Save file:', 'Save via Ajax': 'Uložit pomocí Ajaxu', 'Saved file hash:': 'hash uloženého souboru:', 'Semantic': 'Modul semantic', 'Services': 'Služby', 'session': 'session', 'session expired': 'session expired', 'Set Breakpoint on %s at line %s: %s': 'Bod přerušení nastaven v souboru %s na řádce %s: %s', 'shell': 'příkazová řádka', 'Singular Form': 'Singular Form', 'Site': 'Správa aplikací', 'Size of cache:': 'Velikost cache:', 'skip to generate': 'skip to generate', 'Sorry, could not find mercurial installed': 'Bohužel mercurial není nainstalován.', 'Start a new app': 'Vytvořit novou aplikaci', 'Start searching': 'Začít hledání', 'Start wizard': 'Spustit průvodce', 'state': 'stav', 'Static': 'Static', 'static': 'statické soubory', 'Static files': 'Statické soubory', 'Statistics': 'Statistika', 'Step': 'Step', 'step': 'step', 'stop': 'stop', 'Stylesheet': 'CSS styly', 'submit': 'odeslat', 'Submit': 'Odeslat', 'successful': 'úspěšně', 'Support': 'Podpora', 'Sure you want to delete this object?': 'Opravdu chcete smazat tento objekt?', 'Table': 'tabulka', 'Table name': 'Název tabulky', 'Temporary': 'Dočasný', 'test': 'test', 'Testing application': 'Testing application', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Dotaz" je podmínka, například "db.tabulka1.pole1==\'hodnota\'". Podmínka "db.tabulka1.pole1==db.tabulka2.pole2" pak vytvoří SQL JOIN.', 'The application logic, each URL path is mapped in one exposed function in the controller': 'Logika aplikace: každá URL je mapována na funkci vystavovanou kontrolérem.', 'The Core': 'Jádro (The Core)', 'The data representation, define database tables and sets': 'Reprezentace dat: definovat tabulky databáze a záznamy', 'The output of the file is a dictionary that was rendered by the view %s': 'Výstup ze souboru je slovník, který se zobrazil v pohledu %s.', 'The presentations layer, views are also known as templates': 'Prezentační vrstva: pohledy či templaty (šablony)', 'The Views': 'Pohledy (The Views)', 'There are no controllers': 'There are no controllers', 'There are no modules': 'There are no modules', 'There are no plugins': 'Žádné moduly nejsou instalovány.', 'There are no private files': 'Žádné soukromé soubory neexistují.', 'There are no static files': 'There are no static files', 'There are no translators, only default language is supported': 'There are no translators, only default language is supported', 'There are no views': 'There are no views', 'These files are not served, they are only available from within your app': 'Tyto soubory jsou klientům nepřístupné. K dispozici jsou pouze v rámci aplikace.', 'These files are served without processing, your images go here': 'Tyto soubory jsou servírovány bez přídavné logiky, sem patří např. obrázky.', 'This App': 'Tato aplikace', 'This is a copy of the scaffolding application': 'Toto je kopie aplikace skelet.', 'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk': 'This is an experimental feature and it needs more testing. If you decide to upgrade you do it at your own risk', 'This is the %(filename)s template': 'This is the %(filename)s template', 'this page to see if a breakpoint was hit and debug interaction is required.': 'tuto stránku, abyste uviděli, zda se dosáhlo bodu přerušení.', 'Ticket': 'Ticket', 'Ticket ID': 'Ticket ID', 'Time in Cache (h:m:s)': 'Čas v Cache (h:m:s)', 'Timestamp': 'Časové razítko', 'to previous version.': 'k předchozí verzi.', 'To create a plugin, name a file/folder plugin_[name]': 'Zásuvný modul vytvoříte tak, že pojmenujete soubor/adresář plugin_[jméno modulu]', 'To emulate a breakpoint programatically, write:': 'K nastavení bodu přerušení v kódu programu, napište:', 'to use the debugger!': ', abyste mohli ladící program používat!', 'toggle breakpoint': 'vyp./zap. bod přerušení', 'Toggle Fullscreen': 'Na celou obrazovku a zpět', 'too short': 'Příliš krátké', 'Traceback': 'Traceback', 'Translation strings for the application': 'Překlad textů pro aplikaci', 'try something like': 'try something like', 'Try the mobile interface': 'Zkuste rozhraní pro mobilní zařízení', 'try view': 'try view', 'Twitter': 'Twitter', 'Type python statement in here and hit Return (Enter) to execute it.': 'Type python statement in here and hit Return (Enter) to execute it.', 'Type some Python code in here and hit Return (Enter) to execute it.': 'Type some Python code in here and hit Return (Enter) to execute it.', 'Unable to check for upgrades': 'Unable to check for upgrades', 'unable to parse csv file': 'csv soubor nedá sa zpracovat', 'uncheck all': 'vše odznačit', 'Uninstall': 'Odinstalovat', 'update': 'aktualizovat', 'update all languages': 'aktualizovat všechny jazyky', 'Update:': 'Upravit:', 'Upgrade': 'Upgrade', 'upgrade now': 'upgrade now', 'upgrade now to %s': 'upgrade now to %s', 'upload': 'nahrát', 'Upload': 'Upload', 'Upload a package:': 'Nahrát balík:', 'Upload and install packed application': 'Nahrát a instalovat zabalenou aplikaci', 'upload file:': 'nahrát soubor:', 'upload plugin file:': 'nahrát soubor modulu:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Použijte (...)&(...) pro AND, (...)|(...) pro OR a ~(...) pro NOT pro sestavení složitějších dotazů.', 'User %(id)s Logged-in': 'Uživatel %(id)s přihlášen', 'User %(id)s Logged-out': 'Uživatel %(id)s odhlášen', 'User %(id)s Password changed': 'Uživatel %(id)s změnil heslo', 'User %(id)s Profile updated': 'Uživatel %(id)s upravil profil', 'User %(id)s Registered': 'Uživatel %(id)s se zaregistroval', 'User %(id)s Username retrieved': 'Uživatel %(id)s si nachal zaslat přihlašovací jméno', 'User ID': 'ID uživatele', 'Username': 'Přihlašovací jméno', 'variables': 'variables', 'Verify Password': 'Zopakujte heslo', 'Version': 'Verze', 'Version %s.%s.%s (%s) %s': 'Verze %s.%s.%s (%s) %s', 'Versioning': 'Verzování', 'Videos': 'Videa', 'View': 'Pohled (View)', 'Views': 'Pohledy', 'views': 'pohledy', 'Web Framework': 'Web Framework', 'web2py is up to date': 'Máte aktuální verzi web2py.', 'web2py online debugger': 'Ladící online web2py program', 'web2py Recent Tweets': 'Štěbetání na Twitteru o web2py', 'web2py upgrade': 'web2py upgrade', 'web2py upgraded; please restart it': 'web2py upgraded; please restart it', 'Welcome': 'Vítejte', 'Welcome to web2py': 'Vitejte ve web2py', 'Welcome to web2py!': 'Vítejte ve web2py!', 'Which called the function %s located in the file %s': 'která zavolala funkci %s v souboru (kontroléru) %s.', 'You are successfully running web2py': 'Úspěšně jste spustili web2py.', 'You can also set and remove breakpoint in the edit window, using the Toggle Breakpoint button': 'Nastavovat a mazat body přerušení je též možno v rámci editování zdrojového souboru přes tlačítko Vyp./Zap. bod přerušení', 'You can modify this application and adapt it to your needs': 'Tuto aplikaci si můžete upravit a přizpůsobit ji svým potřebám.', 'You need to set up and reach a': 'Je třeba nejprve nastavit a dojít až na', 'You visited the url %s': 'Navštívili jste stránku %s,', 'Your application will be blocked until you click an action button (next, step, continue, etc.)': 'Aplikace bude blokována než se klikne na jedno z tlačítek (další, krok, pokračovat, atd.)', 'Your can inspect variables using the console bellow': 'Níže pomocí příkazové řádky si můžete prohlédnout proměnné', }
Python
# coding: utf8 { '!langcode!': 'my', '!langname!': 'Malay', '%d days ago': '%d hari yang lalu', '%d hours ago': '%d jam yang lalu', '%d minutes ago': '%d minit yang lalu', '%d months ago': '%d bulan yang lalu', '%d seconds ago': '%d saat yang lalu', '%d seconds from now': '%d saat dari sekarang', '%d weeks ago': '%d minggu yang lalu', '%d years ago': '%d tahun yang lalu', '%s %%{row} deleted': '%s %%{row} dihapuskan', '%s %%{row} updated': '%s %%{row} dikemas kini', '%s selected': '%s dipilih', '%Y-%m-%d': '%d-%m-%Y', '%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S', '(requires internet access, experimental)': '(memerlukan akses internet, percubaan)', '(something like "it-it")': '(sesuatu seperti "it-it")', '1 day ago': '1 hari yang lalu', '1 hour ago': '1 jam yang lalu', '1 minute ago': '1 minit yang lalu', '1 month ago': '1 bulan yang lalu', '1 second ago': '1 saat yang lalu', '1 week ago': '1 minggu yang lalu', '1 year ago': '1 tahun yang lalu', '< Previous': '< Sebelumnya', 'About': 'Mengenai', 'Add': 'Tambah', 'Admin language': 'Bahasa admin', 'Administrator Password:': 'Kata laluan Administrator:', 'Ajax Recipes': 'Resipi Ajax', 'An error occured, please %s the page': 'Kesilapan telah berlaku, sila %s laman', 'And': 'Dan', 'and rename it:': 'dan menamakan itu:', 'are not used yet': 'tidak digunakan lagi', 'Are you sure you want to delete this object?': 'Apakah anda yakin anda mahu memadam ini?', 'Back': 'Kembali', 'Buy this book': 'Beli buku ini', 'cache, errors and sessions cleaned': 'cache, kesilapan dan sesi dibersihkan', 'Cancel': 'Batal', 'Cannot be empty': 'Tidak boleh kosong', 'Change admin password': 'Tukar kata laluan admin', 'Change password': 'Tukar kata laluan', 'Clean': 'Bersihkan', 'Clear': 'Hapus', 'Clear CACHE?': 'Hapus CACHE?', 'Clear DISK': 'Hapus DISK', 'Clear RAM': 'Hapus RAM', 'Click row to expand traceback': 'Klik baris untuk mengembangkan traceback', 'Close': 'Tutup', 'Community': 'Komuniti', 'Components and Plugins': 'Komponen dan Plugin', 'contains': 'mengandung', 'Copyright': 'Hak Cipta', 'Create': 'Buat', 'create file with filename:': 'mencipta fail dengan nama:', 'created by': 'dicipta oleh', 'currently running': 'sedang berjalan', 'data uploaded': 'data diunggah', 'Delete': 'Hapus', 'Delete this file (you will be asked to confirm deletion)': 'Padam fail ini (anda akan diminta untuk mengesahkan pemadaman)', 'Delete:': 'Hapus:', 'design': 'disain', 'direction: ltr': 'arah: ltr', 'Disk Cleared': 'Disk Dihapuskan', 'Documentation': 'Dokumentasi', "Don't know what to do?": 'Tidak tahu apa yang perlu dilakukan?', 'done!': 'selesai!', 'Download': 'Unduh', 'Duration': 'Tempoh', 'Email : ': 'Emel : ', 'Email sent': 'Emel dihantar', 'enter a valid email address': 'masukkan alamat emel yang benar', 'enter a valid URL': 'masukkan URL yang benar', 'enter a value': 'masukkan data', 'Error': 'Kesalahan', 'Errors': 'Kesalahan', 'export as csv file': 'eksport sebagai file csv', 'Export:': 'Eksport:', 'File': 'Fail', 'filter': 'menapis', 'First Name': 'Nama Depan', 'Forgot username?': 'Lupa nama pengguna?', 'Free Applications': 'Aplikasi Percuma', 'Gender': 'Jenis Kelamin', 'Group %(group_id)s created': 'Kumpulan %(group_id)s dicipta', 'Group uniquely assigned to user %(id)s': 'Kumpulan unik yang diberikan kepada pengguna %(id)s', 'Groups': 'Kumpulan', 'Hello World': 'Halo Dunia', 'Help': 'Bantuan', 'Home': 'Laman Utama', 'How did you get here?': 'Bagaimana kamu boleh di sini?', 'Image': 'Gambar', 'import': 'import', 'Import/Export': 'Import/Eksport', 'includes': 'termasuk', 'Install': 'Pasang', 'Installation': 'Pemasangan', 'Introduction': 'Pengenalan', 'Invalid email': 'Emel tidak benar', 'Language': 'Bahasa', 'languages': 'bahasa', 'Languages': 'Bahasa', 'Last Name': 'Nama Belakang', 'License for': 'lesen untuk', 'loading...': 'sedang memuat...', 'Logged in': 'Masuk', 'Logged out': 'Keluar', 'Login': 'Masuk', 'Logout': 'Keluar', 'Lost Password': 'Lupa Kata Laluan', 'Lost password?': 'Lupa kata laluan?', 'Maintenance': 'Penyelenggaraan', 'Manage': 'Menguruskan', 'Manage Cache': 'Menguruskan Cache', 'models': 'model', 'Models': 'Model', 'Modules': 'Modul', 'modules': 'modul', 'My Sites': 'Laman Saya', 'New': 'Baru', 'New password': 'Kata laluan baru', 'next 100 rows': '100 baris seterusnya', 'Next >': 'Seterusnya >', 'Next Page': 'Laman Seterusnya', 'No ticket_storage.txt found under /private folder': 'Ticket_storage.txt tidak dijumpai di bawah folder /private', 'not a Zip Code': 'bukan Pos', 'Old password': 'Kata laluan lama', 'Online examples': 'Contoh Online', 'Or': 'Atau', 'or alternatively': 'atau sebagai alternatif', 'Or Get from URL:': 'Atau Dapatkan dari URL:', 'or import from csv file': 'atau import dari file csv', 'Other Plugins': 'Plugin Lain', 'Other Recipes': 'Resipi Lain', 'Overview': 'Tinjauan', 'Pack all': 'Mengemaskan semua', 'Password': 'Kata laluan', 'Password changed': 'Kata laluan berubah', "Password fields don't match": 'Kata laluan tidak sama', 'please input your password again': 'sila masukan kata laluan anda lagi', 'plugins': 'plugin', 'Plugins': 'Plugin', 'Powered by': 'Disokong oleh', 'Preface': 'Pendahuluan', 'previous 100 rows': '100 baris sebelumnya', 'Previous Page': 'Laman Sebelumnya', 'private files': 'fail peribadi', 'Private files': 'Fail peribadi', 'Profile': 'Profil', 'Profile updated': 'Profil dikemaskini', 'Project Progress': 'Kemajuan Projek', 'Quick Examples': 'Contoh Cepat', 'Ram Cleared': 'Ram Dihapuskan', 'Recipes': 'Resipi', 'Register': 'Daftar', 'Registration successful': 'Pendaftaran berjaya', 'reload': 'memuat kembali', 'Reload routes': 'Memuat laluan kembali', 'Remember me (for 30 days)': 'Ingat saya (selama 30 hari)', 'Request reset password': 'Meminta reset kata laluan', 'Rows selected': 'Baris dipilih', 'Running on %s': 'Berjalan pada %s', 'Save model as...': 'Simpan model sebagai ...', 'Save profile': 'Simpan profil', 'Search': 'Cari', 'Select Files to Package': 'Pilih Fail untuk Pakej', 'Send Email': 'Kirim Emel', 'Size of cache:': 'Saiz cache:', 'Solution': 'Penyelesaian', 'starts with': 'bermula dengan', 'static': 'statik', 'Static': 'Statik', 'Statistics': 'Statistik', 'Support': 'Menyokong', 'test': 'ujian', 'There are no plugins': 'Tiada plugin', 'There are no private files': 'Tiada fail peribadi', 'These files are not served, they are only available from within your app': 'Fail-fail ini tidak disampaikan, mereka hanya boleh didapati dari dalam aplikasi anda', 'These files are served without processing, your images go here': 'Ini fail disampaikan tanpa pemprosesan, imej anda di sini', 'This App': 'App Ini', 'Time in Cache (h:m:s)': 'Waktu di Cache (h: m: s)', 'Title': 'Judul', 'To create a plugin, name a file/folder plugin_[name]': 'Untuk mencipta plugin, nama fail/folder plugin_ [nama]', 'too short': 'terlalu pendek', 'Unable to download because:': 'Tidak dapat memuat turun kerana:', 'unable to parse csv file': 'tidak mampu mengurai file csv', 'update all languages': 'mengemaskini semua bahasa', 'Update:': 'Kemas kini:', 'Upgrade': 'Menaik taraf', 'Upload': 'Unggah', 'Upload a package:': 'Unggah pakej:', 'upload file:': 'unggah fail:', 'upload plugin file:': 'unggah fail plugin:', 'User %(id)s Logged-in': 'Pengguna %(id)s Masuk', 'User %(id)s Logged-out': 'Pengguna %(id)s Keluar', 'User %(id)s Password changed': 'Pengguna %(id)s Kata Laluan berubah', 'User %(id)s Password reset': 'Pengguna %(id)s Kata Laluan telah direset', 'User %(id)s Profile updated': 'Pengguna %(id)s Profil dikemaskini', 'User %(id)s Registered': 'Pengguna %(id)s Didaftarkan', 'value not allowed': 'data tidak benar', 'Verify Password': 'Pengesahan Kata Laluan', 'Version': 'Versi', 'Versioning': 'Pembuatan Sejarah', 'View': 'Lihat', 'Views': 'Lihat', 'views': 'Lihat', 'Web Framework': 'Rangka Kerja Web', 'web2py Recent Tweets': 'Tweet terbaru web2py', 'Website': 'Laman Web', 'Welcome': 'Selamat Datang', 'Welcome to web2py!': 'Selamat Datang di web2py!', 'You are successfully running web2py': 'Anda berjaya menjalankan web2py', 'You can modify this application and adapt it to your needs': 'Anda boleh mengubah suai aplikasi ini dan menyesuaikan dengan keperluan anda', 'You visited the url %s': 'Anda melawat url %s', }
Python
# coding: utf8 { '!langcode!': 'sk', '!langname!': 'Slovenský', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" je voliteľný výraz ako "field1=\'newvalue\'". Nemôžete upravovať alebo zmazať výsledky JOINu', '%s %%{row} deleted': '%s zmazaných záznamov', '%s %%{row} updated': '%s upravených záznamov', '%s selected': '%s označených', '%Y-%m-%d': '%d.%m.%Y', '%Y-%m-%d %H:%M:%S': '%d.%m.%Y %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'pre administrátorské rozhranie kliknite sem', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'appadmin je zakázaný bez zabezpečeného spojenia', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available Databases and Tables': 'Dostupné databázy a tabuľky', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Nemôže byť prázdne', 'Check to delete': 'Označiť na zmazanie', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Aktuálna požiadavka', 'Current response': 'Aktuálna odpoveď', 'Current session': 'Aktuálne sedenie', 'customize me!': 'prispôsob ma!', 'data uploaded': 'údaje naplnené', 'Database': 'databáza', 'Database %s select': 'databáza %s výber', 'db': 'db', 'DB Model': 'DB Model', 'Delete:': 'Zmazať:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Popis', 'design': 'návrh', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Dokumentácia', "Don't know what to do?": "Don't know what to do?", 'done!': 'hotovo!', 'Download': 'Download', 'Edit': 'Upraviť', 'Edit current record': 'Upraviť aktuálny záznam', 'Edit Profile': 'Upraviť profil', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'exportovať do csv súboru', 'FAQ': 'FAQ', 'First name': 'Krstné meno', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group ID': 'ID skupiny', 'Groups': 'Groups', 'Hello World': 'Ahoj svet', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Import/Export', 'Index': 'Index', 'insert new': 'vložiť nový záznam ', 'insert new %s': 'vložiť nový záznam %s', 'Internal State': 'Vnútorný stav', 'Introduction': 'Introduction', 'Invalid email': 'Neplatný email', 'Invalid password': 'Nesprávne heslo', 'Invalid Query': 'Neplatná otázka', 'invalid request': 'Neplatná požiadavka', 'Key': 'Key', 'Last name': 'Priezvisko', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Logged in': 'Prihlásený', 'Logged out': 'Odhlásený', 'login': 'prihlásiť', 'logout': 'odhlásiť', 'Lost Password': 'Stratené heslo?', 'lost password?': 'stratené heslo?', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu Model', 'My Sites': 'My Sites', 'Name': 'Meno', 'New password': 'Nové heslo', 'New Record': 'Nový záznam', 'new record inserted': 'nový záznam bol vložený', 'next 100 rows': 'ďalších 100 riadkov', 'No databases in this application': 'V tejto aplikácii nie sú databázy', 'Old password': 'Staré heslo', 'Online examples': 'pre online príklady kliknite sem', 'or import from csv file': 'alebo naimportovať z csv súboru', 'Origin': 'Pôvod', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'password': 'heslo', 'Password': 'Heslo', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': 'predchádzajúcich 100 riadkov', 'Python': 'Python', 'Query:': 'Otázka:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'záznam', 'record does not exist': 'záznam neexistuje', 'Record ID': 'ID záznamu', 'Record id': 'id záznamu', 'Register': 'Zaregistrovať sa', 'register': 'registrovať', 'Registration key': 'Registračný kľúč', 'Remember me (for 30 days)': 'Zapamätaj si ma (na 30 dní)', 'Reset Password key': 'Nastaviť registračný kľúč', 'Role': 'Rola', 'Rows in Table': 'riadkov v tabuľke', 'Rows selected': 'označených riadkov', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'stav', 'Statistics': 'Statistics', 'Stylesheet': 'Stylesheet', 'submit': 'submit', 'Submit': 'Odoslať', 'Support': 'Support', 'Sure you want to delete this object?': 'Ste si istí, že chcete zmazať tento objekt?', 'Table': 'tabuľka', 'Table name': 'Názov tabuľky', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"query" je podmienka ako "db.table1.field1==\'value\'". Niečo ako "db.table1.field1==db.table2.field2" má za výsledok SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'Výstup zo súboru je slovník, ktorý bol zobrazený vo view %s', 'The Views': 'The Views', 'This App': 'This App', 'This is a copy of the scaffolding application': 'Toto je kópia skeletu aplikácie', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Časová pečiatka', 'Twitter': 'Twitter', 'unable to parse csv file': 'nedá sa načítať csv súbor', 'Update:': 'Upraviť:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Použite (...)&(...) pre AND, (...)|(...) pre OR a ~(...) pre NOT na poskladanie komplexnejších otázok.', 'User %(id)s Logged-in': 'Používateľ %(id)s prihlásený', 'User %(id)s Logged-out': 'Používateľ %(id)s odhlásený', 'User %(id)s Password changed': 'Používateľ %(id)s zmenil heslo', 'User %(id)s Profile updated': 'Používateľ %(id)s upravil profil', 'User %(id)s Registered': 'Používateľ %(id)s sa zaregistroval', 'User ID': 'ID používateľa', 'Verify Password': 'Zopakujte heslo', 'Videos': 'Videos', 'View': 'Zobraziť', 'Welcome to web2py': 'Vitajte vo web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Ktorý zavolal funkciu %s nachádzajúci sa v súbore %s', 'You are successfully running web2py': 'Úspešne ste spustili web2py', 'You can modify this application and adapt it to your needs': 'Môžete upraviť túto aplikáciu a prispôsobiť ju svojim potrebám', 'You visited the url %s': 'Navštívili ste URL %s', }
Python
# coding: utf8 { '!langcode!': 'uk', '!langname!': 'Українська', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Оновити" це додатковий вираз, такий, як "field1=\'нове_значення\'". Ви не можете змінювати або вилучати дані об\'єднаних таблиць.', '%d days ago': '%d %%{день} тому', '%d hours ago': '%d %%{годину} тому', '%d minutes ago': '%d %%{хвилину} тому', '%d months ago': '%d %%{місяць} тому', '%d secods ago': '%d %%{секунду} тому', '%d weeks ago': '%d %%{тиждень} тому', '%d years ago': '%d %%{рік} тому', '%s %%{row} deleted': 'Вилучено %s %%{рядок}', '%s %%{row} updated': 'Змінено %s %%{рядок}', '%s selected': 'Вибрано %s %%{запис}', '%Y-%m-%d': '%Y/%m/%d', '%Y-%m-%d %H:%M:%S': '%Y/%m/%d %H:%M:%S', '1 day ago': '1 день тому', '1 hour ago': '1 годину тому', '1 minute ago': '1 хвилину тому', '1 month ago': '1 місяць тому', '1 second ago': '1 секунду тому', '1 week ago': '1 тиждень тому', '1 year ago': '1 рік тому', '@markmin\x01(**%.0d MB**)': '(**``%.0d``:red МБ**)', '@markmin\x01**%(items)s** %%{item(items)}, **%(bytes)s** %%{byte(bytes)}': '**%(items)s** %%{елемент(items)}, **%(bytes)s** %%{байт(bytes)}', '@markmin\x01``**not available**``:red (requires the Python [[guppy http://pypi.python.org/pypi/guppy/ popup]] library)': '**нема в наявності** (потребує Пітонівської бібліотеки [[guppy {посилання відкриється у новому вікні} http://pypi.python.org/pypi/guppy/ popup]])', '@markmin\x01Cache contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': "Час життя об'єктів в КЕШІ сягає **%(hours)02d** %%{годину(hours)} **%(min)02d** %%{хвилину(min)} та **%(sec)02d** %%{секунду(sec)}.", '@markmin\x01DISK contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': "Час життя об'єктів в ДИСКОВОМУ КЕШІ сягає **%(hours)02d** %%{годину(hours)} **%(min)02d** %%{хвилину(min)} та **%(sec)02d** %%{секунду(sec)}.", '@markmin\x01Hit Ratio: **%(ratio)s%%** (**%(hits)s** %%{hit(hits)} and **%(misses)s** %%{miss(misses)})': 'Оцінка поцілювання: **%(ratio)s%%** (**%(hits)s** %%{поцілювання(hits)} та **%(misses)s** %%{схибнення(misses)})', '@markmin\x01Number of entries: **%s**': 'Кількість входжень: ``**%s**``:red', '@markmin\x01RAM contains items up to **%(hours)02d** %%{hour(hours)} **%(min)02d** %%{minute(min)} **%(sec)02d** %%{second(sec)} old.': "Час життя об'єктів в ОЗП-КЕШІ сягає **%(hours)02d** %%{годину(hours)} **%(min)02d** %%{хвилину(min)} та **%(sec)02d** %%{секунду(sec)}.", 'About': 'Про додаток', 'Access Control': 'Контроль доступу', 'Administrative Interface': 'Адміністративний інтерфейс', 'Ajax Recipes': 'Рецепти для Ajax', 'appadmin is disabled because insecure channel': 'використовується незахищенний канал (HTTP). Appadmin вимкнено', 'Are you sure you want to delete this object?': "Ви впевнені, що хочете вилучити цей об'єкт?", 'Available Databases and Tables': 'Доступні бази даних та таблиці', 'Buy this book': 'Купити книжку', 'cache': 'кеш', 'Cache': 'Кеш', 'Cache Keys': 'Ключі кешу', 'Cannot be empty': 'Порожнє значення неприпустиме', 'Change password': 'Змінити пароль', 'Check to delete': 'Позначити для вилучення', 'Check to delete:': 'Позначте для вилучення:', 'Clear CACHE?': 'Очистити ВЕСЬ кеш?', 'Clear DISK': 'Очистити ДИСКОВИЙ кеш', 'Clear RAM': "Очистити кеш В ПАМ'ЯТІ", 'Client IP': 'IP клієнта', 'Community': 'Спільнота', 'Components and Plugins': 'Компоненти та втулки', 'Controller': 'Контролер', 'Copyright': 'Правовласник', 'Created By': 'Створив(ла)', 'Created On': 'Створено в', 'Current request': 'Поточний запит (current request)', 'Current response': 'Поточна відповідь (current response)', 'Current session': 'Поточна сесія (current session)', 'customize me!': 'причепуріть мене!', 'data uploaded': 'дані завантажено', 'Database': 'База даних', 'Database %s select': 'Вибірка з бази даних %s', 'db': 'база даних', 'DB Model': 'Модель БД', 'Delete:': 'Вилучити:', 'Demo': 'Демо', 'Deployment Recipes': 'Способи розгортання', 'Description': 'Опис', 'design': 'налаштування', 'DISK': 'ДИСК', 'Disk Cache Keys': 'Ключі дискового кешу', 'Disk Cleared': 'Дисковий кеш очищено', 'Documentation': 'Документація', "Don't know what to do?": 'Не знаєте що робити далі?', 'done!': 'зроблено!', 'Download': 'Завантажити', 'E-mail': 'Ел.пошта', 'edit': 'редагувати', 'Edit current record': 'Редагувати поточний запис', 'Edit Page': 'Редагувати сторінку', 'Email and SMS': 'Ел.пошта та SMS', 'enter a value': 'введіть значення', 'enter an integer between %(min)g and %(max)g': 'введіть ціле число між %(min)g та %(max)g', 'Error!': 'Помилка!', 'Errors': 'Помилки', 'Errors in form, please check it out.': 'У формі є помилка. Виправте її, будь-ласка.', 'export as csv file': 'експортувати як файл csv', 'FAQ': 'ЧаПи (FAQ)', 'First name': "Ім'я", 'Forgot username?': "Забули ім'я користувача?", 'Forms and Validators': 'Форми та коректність даних', 'Free Applications': 'Вільні додатки', 'Group %(group_id)s created': 'Групу %(group_id)s створено', 'Group ID': 'Ідентифікатор групи', 'Group uniquely assigned to user %(id)s': "Група унікально зв'язана з користувачем %(id)s", 'Groups': 'Групи', 'Hello World': 'Привіт, світ!', 'Home': 'Початок', 'How did you get here?': 'Як цього було досягнуто?', 'import': 'Імпортувати', 'Import/Export': 'Імпорт/Експорт', 'insert new': 'Створити новий запис', 'insert new %s': 'створити новий запис %s', 'Internal State': 'Внутрішній стан', 'Introduction': 'Введення', 'Invalid email': 'Невірна адреса ел.пошти', 'Invalid login': "Невірне ім'я користувача", 'Invalid password': 'Невірний пароль', 'Invalid Query': 'Помилковий запит', 'invalid request': 'хибний запит', 'Is Active': 'Активна', 'Key': 'Ключ', 'Last name': 'Прізвище', 'Layout': 'Макет (Layout)', 'Layout Plugins': 'Втулки макетів', 'Layouts': 'Макети', 'Live Chat': 'Чат', 'Logged in': 'Вхід здійснено', 'Logged out': 'Вихід здійснено', 'Login': 'Вхід', 'Logout': 'Вихід', 'Lost Password': 'Забули пароль', 'Lost password?': 'Забули пароль?', 'Manage Cache': 'Управління кешем', 'Menu Model': 'Модель меню', 'Modified By': 'Зміни провадив(ла)', 'Modified On': 'Змінено в', 'My Sites': 'Сайт (усі додатки)', 'Name': "Ім'я", 'New password': 'Новий пароль', 'New Record': 'Новий запис', 'new record inserted': 'новий рядок додано', 'next 100 rows': 'наступні 100 рядків', 'No databases in this application': 'Даний додаток не використовує базу даних', 'now': 'зараз', 'Object or table name': "Об'єкт або назва таблиці", 'Old password': 'Старий пароль', 'Online examples': 'Зразковий демо-сайт', 'or import from csv file': 'або імпортувати з csv-файлу', 'Origin': 'Походження', 'Other Plugins': 'Інші втулки', 'Other Recipes': 'Інші рецепти', 'Overview': 'Огляд', 'Page Not Found!': 'Сторінку не знайдено!', 'Page saved': 'Сторінку збережено', 'Password': 'Пароль', 'Password changed': 'Пароль змінено', "Password fields don't match": 'Пароль не співпав', 'please input your password again': 'Будь-ласка введіть пароль ще раз', 'Plugins': 'Втулки (Plugins)', 'Powered by': 'Працює на', 'Preface': 'Передмова', 'previous 100 rows': 'попередні 100 рядків', 'Profile': 'Параметри', 'Profile updated': 'Параметри змінено', 'Python': 'Мова Python', 'Query:': 'Запит:', 'Quick Examples': 'Швидкі приклади', 'RAM': "ОПЕРАТИВНА ПАМ'ЯТЬ (ОЗП)", 'RAM Cache Keys': 'Ключі ОЗП-кешу', 'Ram Cleared': 'ОЗП-кеш очищено', 'Recipes': 'Рецепти', 'Record': 'запис', 'Record %(id)s updated': 'Запис %(id)s змінено', 'record does not exist': 'запису не існує', 'Record ID': 'Ід.запису', 'Record id': 'ід. запису', 'Record Updated': 'Запис змінено', 'Register': 'Реєстрація', 'Registration identifier': 'Реєстраційний ідентифікатор', 'Registration key': 'Реєстраційний ключ', 'Registration successful': 'Реєстрація пройшла успішно', 'Remember me (for 30 days)': "Запам'ятати мене (на 30 днів)", 'Request reset password': 'Запит на зміну пароля', 'Reset Password key': 'Ключ скидання пароля', 'Role': 'Роль', 'Rows in Table': 'Рядки в таблиці', 'Rows selected': 'Відмічено рядків', 'Save profile': 'Зберегти параметри', 'Semantic': 'Семантика', 'Services': 'Сервіс', 'Size of cache:': 'Розмір кешу:', 'state': 'стан', 'Statistics': 'Статистика', 'Stylesheet': 'CSS-стилі', 'submit': 'застосувати', 'Submit': 'Застосувати', 'Support': 'Підтримка', 'Table': 'Таблиця', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Запит" це умова, на зразок "db.table1.field1==\'значення\'". Вираз "db.table1.field1==db.table2.field2" повертає результат об\'єднання (SQL JOIN) таблиць.', 'The Core': 'Ядро', 'The output of the file is a dictionary that was rendered by the view %s': 'Результат функції - словник пар (назва=значення) було відображено з допомогою відображення (view) %s', 'The Views': 'Відображення (Views)', 'This App': 'Цей додаток', 'Time in Cache (h:m:s)': 'Час знаходження в кеші (h:m:s)', 'Timestamp': 'Відмітка часу', 'too short': 'Занадто короткий', 'Twitter': 'Твіттер', 'unable to parse csv file': 'не вдається розібрати csv-файл', 'Update:': 'Оновити:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Для створення складних запитів використовуйте (...)&(...) замість AND, (...)|(...) замість OR, та ~(...) замість NOT.', 'User %(id)s Logged-in': 'Користувач %(id)s увійшов', 'User %(id)s Logged-out': 'Користувач %(id)s вийшов', 'User %(id)s Password changed': 'Користувач %(id)s змінив свій пароль', 'User %(id)s Password reset': 'Користувач %(id)s скинув пароль', 'User %(id)s Profile updated': 'Параметри користувача %(id)s змінено', 'User %(id)s Registered': 'Користувач %(id)s зареєструвався', 'User ID': 'Ід.користувача', 'value already in database or empty': 'значення вже в базі даних або порожнє', 'Verify Password': 'Повторити пароль', 'Videos': 'Відео', 'View': 'Відображення (View)', 'Welcome': 'Ласкаво просимо', 'Welcome to web2py!': 'Ласкаво просимо до web2py!', 'Which called the function %s located in the file %s': 'Управління передалось функції %s, яка розташована у файлі %s', 'You are successfully running web2py': 'Ви успішно запустили web2py', 'You can modify this application and adapt it to your needs': 'Ви можете модифікувати цей додаток і адаптувати його до своїх потреб', 'You visited the url %s': 'Ви відвідали наступну адресу: %s', }
Python
# coding: utf8 { '!langcode!': 'pl', '!langname!': 'Polska', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Uaktualnij" jest dodatkowym wyrażeniem postaci "pole1=\'nowawartość\'". Nie możesz uaktualnić lub usunąć wyników z JOIN:', '%s %%{row} deleted': 'Wierszy usuniętych: %s', '%s %%{row} updated': 'Wierszy uaktualnionych: %s', '%s selected': '%s wybranych', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'Kliknij aby przejść do panelu administracyjnego', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'administracja aplikacji wyłączona z powodu braku bezpiecznego połączenia', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Authentication': 'Uwierzytelnienie', 'Available Databases and Tables': 'Dostępne bazy danych i tabele', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Nie może być puste', 'Change Password': 'Zmień hasło', 'change password': 'change password', 'Check to delete': 'Zaznacz aby usunąć', 'Check to delete:': 'Zaznacz aby usunąć:', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'IP klienta', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Kontroler', 'Copyright': 'Copyright', 'Current request': 'Aktualne żądanie', 'Current response': 'Aktualna odpowiedź', 'Current session': 'Aktualna sesja', 'customize me!': 'dostosuj mnie!', 'data uploaded': 'dane wysłane', 'Database': 'baza danych', 'Database %s select': 'wybór z bazy danych %s', 'db': 'baza danych', 'DB Model': 'Model bazy danych', 'Delete:': 'Usuń:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Opis', 'design': 'projektuj', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'zrobione!', 'Download': 'Download', 'E-mail': 'Adres e-mail', 'Edit': 'Edycja', 'Edit current record': 'Edytuj obecny rekord', 'edit profile': 'edit profile', 'Edit Profile': 'Edytuj profil', 'Edit This App': 'Edytuj tę aplikację', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'eksportuj jako plik csv', 'FAQ': 'FAQ', 'First name': 'Imię', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Function disabled': 'Funkcja wyłączona', 'Group ID': 'ID grupy', 'Groups': 'Groups', 'Hello World': 'Witaj Świecie', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Importuj/eksportuj', 'Index': 'Indeks', 'insert new': 'wstaw nowy rekord tabeli', 'insert new %s': 'wstaw nowy rekord do tabeli %s', 'Internal State': 'Stan wewnętrzny', 'Introduction': 'Introduction', 'Invalid email': 'Błędny adres email', 'Invalid Query': 'Błędne zapytanie', 'invalid request': 'Błędne żądanie', 'Key': 'Key', 'Last name': 'Nazwisko', 'Layout': 'Układ', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'login': 'login', 'Login': 'Zaloguj', 'logout': 'logout', 'Logout': 'Wyloguj', 'Lost Password': 'Przypomnij hasło', 'Main Menu': 'Menu główne', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Model menu', 'My Sites': 'My Sites', 'Name': 'Nazwa', 'New Record': 'Nowy rekord', 'new record inserted': 'nowy rekord został wstawiony', 'next 100 rows': 'następne 100 wierszy', 'No databases in this application': 'Brak baz danych w tej aplikacji', 'Online examples': 'Kliknij aby przejść do interaktywnych przykładów', 'or import from csv file': 'lub zaimportuj z pliku csv', 'Origin': 'Źródło', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Hasło', "Password fields don't match": 'Pola hasła nie są zgodne ze sobą', 'Plugins': 'Plugins', 'Powered by': 'Zasilane przez', 'Preface': 'Preface', 'previous 100 rows': 'poprzednie 100 wierszy', 'Python': 'Python', 'Query:': 'Zapytanie:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'rekord', 'record does not exist': 'rekord nie istnieje', 'Record ID': 'ID rekordu', 'Record id': 'id rekordu', 'Register': 'Zarejestruj', 'register': 'register', 'Registration key': 'Klucz rejestracji', 'Role': 'Rola', 'Rows in Table': 'Wiersze w tabeli', 'Rows selected': 'Wybrane wiersze', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'stan', 'Statistics': 'Statistics', 'Stylesheet': 'Arkusz stylów', 'submit': 'submit', 'Submit': 'Wyślij', 'Support': 'Support', 'Sure you want to delete this object?': 'Czy na pewno chcesz usunąć ten obiekt?', 'Table': 'tabela', 'Table name': 'Nazwa tabeli', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Zapytanie" jest warunkiem postaci "db.tabela1.pole1==\'wartość\'". Takie coś jak "db.tabela1.pole1==db.tabela2.pole2" oznacza SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Znacznik czasu', 'Twitter': 'Twitter', 'unable to parse csv file': 'nie można sparsować pliku csv', 'Update:': 'Uaktualnij:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Użyj (...)&(...) jako AND, (...)|(...) jako OR oraz ~(...) jako NOT do tworzenia bardziej skomplikowanych zapytań.', 'User %(id)s Registered': 'Użytkownik %(id)s został zarejestrowany', 'User ID': 'ID użytkownika', 'Verify Password': 'Potwierdź hasło', 'Videos': 'Videos', 'View': 'Widok', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Witaj w web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'vteřina': ['vteřiny', 'vteřin'], 'vteřinou': ['vteřinami', 'vteřinami'], 'minuta': ['minuty', 'minut'], 'minutou': ['minutami', 'minutami'], 'hodina': ['hodiny','hodin'], 'hodinou': ['hodinami','hodinami'], 'den': ['dny','dnů'], 'dnem': ['dny','dny'], 'týden': ['týdny','týdnů'], 'týdnem': ['týdny','týdny'], 'měsíc': ['měsíce','měsíců'], 'měsícem': ['měsíci','měsíci'], 'rok': ['roky','let'], 'rokem': ['roky','lety'], 'záznam': ['záznamy', 'záznamů'], 'soubor': ['soubory', 'souborů'] }
Python
# coding: utf8 { '!langcode!': 'ru', '!langname!': 'Русский', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"Изменить" - необязательное выражение вида "field1=\'новое значение\'". Результаты операции JOIN нельзя изменить или удалить.', '%d days ago': '%d %%{день} тому', '%d hours ago': '%d %%{час} тому', '%d minutes ago': '%d %%{минуту} тому', '%d months ago': '%d %%{месяц} тому', '%d seconds ago': '%d %%{секунду} тому', '%d weeks ago': '%d %%{неделю} тому', '%d years ago': '%d %%{год} тому', '%s %%{row} deleted': '%%{!удалена[0]} %s %%{строка[0]}', '%s %%{row} updated': '%%{!изменена[0]} %s %%{строка[0]}', '%s selected': '%%{!выбрана[0]} %s %%{запись[0]}', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '1 day ago': '1 день тому', '1 hour ago': '1 час тому', '1 minute ago': '1 минуту тому', '1 month ago': '1 месяц тому', '1 second ago': '1 секунду тому', '1 week ago': '1 неделю тому', '1 year ago': '1 год тому', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'административный интерфейс', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'appadmin is disabled because insecure channel', 'Are you sure you want to delete this object?': 'Вы уверены, что хотите удалить этот объект?', 'Available Databases and Tables': 'Базы данных и таблицы', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Пустое значение недопустимо', 'Change Password': 'Смените пароль', 'Check to delete': 'Удалить', 'Check to delete:': 'Удалить:', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'Client IP', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Текущий запрос', 'Current response': 'Текущий ответ', 'Current session': 'Текущая сессия', 'customize me!': 'настройте внешний вид!', 'data uploaded': 'данные загружены', 'Database': 'Database', 'Database %s select': 'выбор базы данных %s', 'db': 'БД', 'DB Model': 'DB Model', 'Delete:': 'Удалить:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Описание', 'design': 'дизайн', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'готово!', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit current record': 'Редактировать текущую запись', 'Edit Profile': 'Редактировать профиль', 'Email and SMS': 'Email and SMS', 'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g', 'Errors': 'Errors', 'export as csv file': 'экспорт в csv-файл', 'FAQ': 'FAQ', 'First name': 'Имя', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group ID': 'Group ID', 'Groups': 'Groups', 'Hello World': 'Заработало!', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Импорт/экспорт', 'insert new': 'добавить', 'insert new %s': 'добавить %s', 'Internal State': 'Внутренне состояние', 'Introduction': 'Introduction', 'Invalid email': 'Неверный email', 'Invalid login': 'Неверный логин', 'Invalid password': 'Неверный пароль', 'Invalid Query': 'Неверный запрос', 'invalid request': 'неверный запрос', 'Key': 'Key', 'Last name': 'Фамилия', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Logged in': 'Вход выполнен', 'Logged out': 'Выход выполнен', 'login': 'вход', 'Login': 'Вход', 'logout': 'выход', 'Logout': 'Выход', 'Lost Password': 'Забыли пароль?', 'Lost password?': 'Lost password?', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu Model', 'My Sites': 'My Sites', 'Name': 'Name', 'New password': 'Новый пароль', 'New Record': 'Новая запись', 'new record inserted': 'новая запись добавлена', 'next 100 rows': 'следующие 100 строк', 'No databases in this application': 'В приложении нет баз данных', 'now': 'сейчас', 'Object or table name': 'Object or table name', 'Old password': 'Старый пароль', 'Online examples': 'примеры он-лайн', 'or import from csv file': 'или импорт из csv-файла', 'Origin': 'Происхождение', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Пароль', 'password': 'пароль', "Password fields don't match": 'Пароли не совпадают', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': 'предыдущие 100 строк', 'profile': 'профиль', 'Python': 'Python', 'Query:': 'Запрос:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'Record', 'record does not exist': 'запись не найдена', 'Record ID': 'ID записи', 'Record id': 'id записи', 'Register': 'Зарегистрироваться', 'Registration identifier': 'Registration identifier', 'Registration key': 'Ключ регистрации', 'Remember me (for 30 days)': 'Запомнить меня (на 30 дней)', 'Reset Password key': 'Сбросить ключ пароля', 'Role': 'Роль', 'Rows in Table': 'Строк в таблице', 'Rows selected': 'Выделено строк', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'состояние', 'Statistics': 'Statistics', 'Stylesheet': 'Stylesheet', 'submit': 'submit', 'Submit': 'Отправить', 'Support': 'Support', 'Sure you want to delete this object?': 'Подтвердите удаление объекта', 'Table': 'таблица', 'Table name': 'Имя таблицы', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Запрос" - это условие вида "db.table1.field1==\'значение\'". Выражение вида "db.table1.field1==db.table2.field2" формирует SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Отметка времени', 'Twitter': 'Twitter', 'unable to parse csv file': 'нечитаемый csv-файл', 'Update:': 'Изменить:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Для построение сложных запросов используйте операторы "И": (...)&(...), "ИЛИ": (...)|(...), "НЕ": ~(...).', 'User %(id)s Logged-in': 'Пользователь %(id)s вошёл', 'User %(id)s Logged-out': 'Пользователь %(id)s вышел', 'User %(id)s Password changed': 'Пользователь %(id)s сменил пароль', 'User %(id)s Profile updated': 'Пользователь %(id)s обновил профиль', 'User %(id)s Registered': 'Пользователь %(id)s зарегистрировался', 'User ID': 'ID пользователя', 'Verify Password': 'Повторите пароль', 'Videos': 'Videos', 'View': 'View', 'Welcome': 'Welcome', 'Welcome to web2py': 'Добро пожаловать в web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!langcode!': 'pt', '!langname!': 'Português', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "field1=\'newvalue\'". Não pode actualizar ou eliminar os resultados de um JOIN', '%s %%{row} deleted': '%s linhas eliminadas', '%s %%{row} updated': '%s linhas actualizadas', '%s selected': '%s seleccionado(s)', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'Painel administrativo', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'appadmin está desactivada pois o canal é inseguro', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Author Reference Auth User': 'Author Reference Auth User', 'Author Reference Auth User.username': 'Author Reference Auth User.username', 'Available Databases and Tables': 'bases de dados e tabelas disponíveis', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'não pode ser vazio', 'Category Create': 'Category Create', 'Category Select': 'Category Select', 'change password': 'alterar palavra-chave', 'Check to delete': 'seleccione para eliminar', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Comment Create': 'Comment Create', 'Comment Select': 'Comment Select', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Content': 'Content', 'Controller': 'Controlador', 'Copyright': 'Direitos de cópia', 'create new category': 'create new category', 'create new comment': 'create new comment', 'create new post': 'create new post', 'Created By': 'Created By', 'Created On': 'Created On', 'Current request': 'pedido currente', 'Current response': 'resposta currente', 'Current session': 'sessão currente', 'customize me!': 'Personaliza-me!', 'data uploaded': 'informação enviada', 'Database': 'base de dados', 'Database %s select': 'selecção de base de dados %s', 'db': 'bd', 'DB Model': 'Modelo de BD', 'Delete:': 'Eliminar:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'design': 'design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'concluído!', 'Download': 'Download', 'Edit': 'Editar', 'edit category': 'edit category', 'edit comment': 'edit comment', 'Edit current record': 'Edição de registo currente', 'edit post': 'edit post', 'edit profile': 'Editar perfil', 'Edit This App': 'Edite esta aplicação', 'Email': 'Email', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'exportar como ficheiro csv', 'FAQ': 'FAQ', 'First Name': 'First Name', 'For %s #%s': 'For %s #%s', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Groups': 'Groups', 'Hello World': 'Olá Mundo', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Importar/Exportar', 'Index': 'Índice', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'Internal State': 'Estado interno', 'Introduction': 'Introduction', 'Invalid Query': 'Consulta Inválida', 'invalid request': 'Pedido Inválido', 'Key': 'Key', 'Last Name': 'Last Name', 'Layout': 'Esboço', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'login': 'login', 'logout': 'logout', 'Lost Password': 'Lost Password', 'Main Menu': 'Menu Principal', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu do Modelo', 'Modified By': 'Modified By', 'Modified On': 'Modified On', 'My Sites': 'My Sites', 'Name': 'Name', 'New Record': 'Novo Registo', 'new record inserted': 'novo registo inserido', 'next 100 rows': 'próximas 100 linhas', 'No Data': 'No Data', 'No databases in this application': 'Não há bases de dados nesta aplicação', 'Online examples': 'Exemplos online', 'or import from csv file': 'ou importe a partir de ficheiro csv', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', 'Plugins': 'Plugins', 'Post Create': 'Post Create', 'Post Select': 'Post Select', 'Powered by': 'Suportado por', 'Preface': 'Preface', 'previous 100 rows': '100 linhas anteriores', 'Python': 'Python', 'Query:': 'Interrogação:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'registo', 'record does not exist': 'registo inexistente', 'Record id': 'id de registo', 'Register': 'Register', 'register': 'register', 'Replyto Reference Post': 'Replyto Reference Post', 'Rows in Table': 'Linhas numa tabela', 'Rows selected': 'Linhas seleccionadas', 'search category': 'search category', 'search comment': 'search comment', 'search post': 'search post', 'select category': 'select category', 'select comment': 'select comment', 'select post': 'select post', 'Semantic': 'Semantic', 'Services': 'Services', 'show category': 'show category', 'show comment': 'show comment', 'show post': 'show post', 'Size of cache:': 'Size of cache:', 'state': 'estado', 'Statistics': 'Statistics', 'Stylesheet': 'Folha de estilo', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'Tem a certeza que deseja eliminar este objecto?', 'Table': 'tabela', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'A "query" é uma condição do tipo "db.table1.field1==\'value\'". Algo como "db.table1.field1==db.table2.field2" resultaria num SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Title': 'Title', 'Twitter': 'Twitter', 'unable to parse csv file': 'não foi possível carregar ficheiro csv', 'Update:': 'Actualização:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Utilize (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir interrogações mais complexas.', 'Username': 'Username', 'Videos': 'Videos', 'View': 'Vista', 'Welcome %s': 'Bem-vindo(a) %s', 'Welcome to Gluonization': 'Bem vindo ao Web2py', 'Welcome to web2py': 'Bem-vindo(a) ao web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'When': 'When', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!langcode!': 'hi-in', '!langname!': 'हिन्दी', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%s %%{row} deleted': '%s पंक्तियाँ मिटाएँ', '%s %%{row} updated': '%s पंक्तियाँ अद्यतन', '%s selected': '%s चुना हुआ', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'प्रशासनिक इंटरफेस के लिए यहाँ क्लिक करें', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'अप आडमिन (appadmin) अक्षम है क्योंकि असुरक्षित चैनल', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available Databases and Tables': 'उपलब्ध डेटाबेस और तालिका', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'खाली नहीं हो सकता', 'Change Password': 'पासवर्ड बदलें', 'change password': 'change password', 'Check to delete': 'हटाने के लिए चुनें', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'वर्तमान अनुरोध', 'Current response': 'वर्तमान प्रतिक्रिया', 'Current session': 'वर्तमान सेशन', 'customize me!': 'मुझे अनुकूलित (कस्टमाइज़) करें!', 'data uploaded': 'डाटा अपलोड सम्पन्न ', 'Database': 'डेटाबेस', 'Database %s select': 'डेटाबेस %s चुनी हुई', 'db': 'db', 'DB Model': 'DB Model', 'Delete:': 'मिटाना:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'design': 'रचना करें', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'हो गया!', 'Download': 'Download', 'Edit': 'Edit', 'Edit current record': 'वर्तमान रेकॉर्ड संपादित करें ', 'edit profile': 'edit profile', 'Edit Profile': 'प्रोफ़ाइल संपादित करें', 'Edit This App': 'Edit This App', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'csv फ़ाइल के रूप में निर्यात', 'FAQ': 'FAQ', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Groups': 'Groups', 'Hello from MyApp': 'Hello from MyApp', 'Hello World': 'Hello World', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'आयात / निर्यात', 'Index': 'Index', 'insert new': 'नया डालें', 'insert new %s': 'नया %s डालें', 'Internal State': 'आंतरिक स्थिति', 'Introduction': 'Introduction', 'Invalid Query': 'अमान्य प्रश्न', 'invalid request': 'अवैध अनुरोध', 'Key': 'Key', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'login': 'login', 'Login': 'लॉग इन', 'logout': 'logout', 'Logout': 'लॉग आउट', 'Lost Password': 'पासवर्ड खो गया', 'Main Menu': 'Main Menu', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu Model', 'My Sites': 'My Sites', 'New Record': 'नया रेकॉर्ड', 'new record inserted': 'नया रेकॉर्ड डाला', 'next 100 rows': 'अगले 100 पंक्तियाँ', 'No databases in this application': 'इस अनुप्रयोग में कोई डेटाबेस नहीं हैं', 'Online examples': 'ऑनलाइन उदाहरण के लिए यहाँ क्लिक करें', 'or import from csv file': 'या csv फ़ाइल से आयात', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': 'पिछले 100 पंक्तियाँ', 'Python': 'Python', 'Query:': 'प्रश्न:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'Record', 'record does not exist': 'रिकॉर्ड मौजूद नहीं है', 'Record id': 'रिकॉर्ड पहचानकर्ता (आईडी)', 'Register': 'पंजीकृत (रजिस्टर) करना ', 'register': 'register', 'Rows in Table': 'तालिका में पंक्तियाँ ', 'Rows selected': 'चयनित (चुने गये) पंक्तियाँ ', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'स्थिति', 'Statistics': 'Statistics', 'Stylesheet': 'Stylesheet', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'सुनिश्चित हैं कि आप इस वस्तु को हटाना चाहते हैं?', 'Table': 'तालिका', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Twitter': 'Twitter', 'unable to parse csv file': 'csv फ़ाइल पार्स करने में असमर्थ', 'Update:': 'अद्यतन करना:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'Videos': 'Videos', 'View': 'View', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'वेब२पाइ (web2py) में आपका स्वागत है', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!langcode!': 'hu', '!langname!': 'Magyar', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%s %%{row} deleted': '%s sorok törlődtek', '%s %%{row} updated': '%s sorok frissítődtek', '%s selected': '%s kiválasztott', '%Y-%m-%d': '%Y.%m.%d.', '%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'az adminisztrációs felületért kattints ide', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'az appadmin a biztonságtalan csatorna miatt letiltva', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available Databases and Tables': 'Elérhető adatbázisok és táblák', 'Buy this book': 'Buy this book', 'cache': 'gyorsítótár', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Nem lehet üres', 'change password': 'jelszó megváltoztatása', 'Check to delete': 'Törléshez válaszd ki', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'Client IP', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Current request': 'Jelenlegi lekérdezés', 'Current response': 'Jelenlegi válasz', 'Current session': 'Jelenlegi folyamat', 'customize me!': 'változtass meg!', 'data uploaded': 'adat feltöltve', 'Database': 'adatbázis', 'Database %s select': 'adatbázis %s kiválasztás', 'db': 'db', 'DB Model': 'DB Model', 'Delete:': 'Töröl:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Description', 'design': 'design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'kész!', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit': 'Szerkeszt', 'Edit current record': 'Aktuális bejegyzés szerkesztése', 'edit profile': 'profil szerkesztése', 'Edit This App': 'Alkalmazást szerkeszt', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'exportál csv fájlba', 'FAQ': 'FAQ', 'First name': 'First name', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group ID': 'Group ID', 'Groups': 'Groups', 'Hello World': 'Hello Világ', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Import/Export', 'Index': 'Index', 'insert new': 'új beillesztése', 'insert new %s': 'új beillesztése %s', 'Internal State': 'Internal State', 'Introduction': 'Introduction', 'Invalid email': 'Invalid email', 'Invalid Query': 'Hibás lekérdezés', 'invalid request': 'hibás kérés', 'Key': 'Key', 'Last name': 'Last name', 'Layout': 'Szerkezet', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'login': 'belép', 'logout': 'kilép', 'lost password': 'elveszett jelszó', 'Lost Password': 'Lost Password', 'Main Menu': 'Főmenü', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menü model', 'My Sites': 'My Sites', 'Name': 'Name', 'New Record': 'Új bejegyzés', 'new record inserted': 'új bejegyzés felvéve', 'next 100 rows': 'következő 100 sor', 'No databases in this application': 'Nincs adatbázis ebben az alkalmazásban', 'Online examples': 'online példákért kattints ide', 'or import from csv file': 'vagy betöltés csv fájlból', 'Origin': 'Origin', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': 'előző 100 sor', 'Python': 'Python', 'Query:': 'Lekérdezés:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'bejegyzés', 'record does not exist': 'bejegyzés nem létezik', 'Record ID': 'Record ID', 'Record id': 'bejegyzés id', 'Register': 'Register', 'register': 'regisztráció', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Role': 'Role', 'Rows in Table': 'Sorok a táblában', 'Rows selected': 'Kiválasztott sorok', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'állapot', 'Statistics': 'Statistics', 'Stylesheet': 'Stylesheet', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'Biztos törli ezt az objektumot?', 'Table': 'tábla', 'Table name': 'Table name', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Timestamp', 'Twitter': 'Twitter', 'unable to parse csv file': 'nem lehet a csv fájlt beolvasni', 'Update:': 'Frissít:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.', 'User ID': 'User ID', 'Videos': 'Videos', 'View': 'Nézet', 'Welcome %s': 'Welcome %s', 'Welcome to web2py': 'Isten hozott a web2py-ban', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
#!/usr/bin/env python { # "singular form (0)": ["first plural form (1)", "second plural form (2)", ...], 'байт': ['байти','байтів'], 'годину': ['години','годин'], 'елемент': ['елементи','елементів'], 'запис': ['записи','записів'], 'поцілювання': ['поцілювання','поцілювань'], 'рядок': ['рядки','рядків'], 'секунду': ['секунди','секунд'], 'схибнення': ['схибнення','схибнень'], 'хвилину': ['хвилини','хвилин'], 'день': ['дні', 'днів'], 'місяць': ['місяці','місяців'], 'тиждень': ['тижні','тижнів'], 'рік': ['роки','років'], }
Python
# coding: utf8 { '!langcode!': 'pt-br', '!langname!': 'Português (do Brasil)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" é uma expressão opcional como "campo1=\'novovalor\'". Você não pode atualizar ou apagar os resultados de um JOIN', '%s %%{row} deleted': '%s linhas apagadas', '%s %%{row} updated': '%s linhas atualizadas', '%s selected': '%s selecionado', '%Y-%m-%d': '%d-%m-%Y', '%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Administrative interface': 'Interface administrativa', 'Ajax Recipes': 'Ajax Recipes', 'appadmin is disabled because insecure channel': 'Administração desativada devido ao canal inseguro', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Available Databases and Tables': 'Bancos de dados e tabelas disponíveis', 'Buy this book': 'Buy this book', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Não pode ser vazio', 'change password': 'modificar senha', 'Check to delete': 'Marque para apagar', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'Client IP', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controlador', 'Copyright': 'Copyright', 'Current request': 'Requisição atual', 'Current response': 'Resposta atual', 'Current session': 'Sessão atual', 'customize me!': 'Personalize-me!', 'data uploaded': 'dados enviados', 'Database': 'banco de dados', 'Database %s select': 'Selecionar banco de dados %s', 'db': 'bd', 'DB Model': 'Modelo BD', 'Delete:': 'Apagar:', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Description', 'design': 'design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'concluído!', 'Download': 'Download', 'E-mail': 'E-mail', 'Edit': 'Editar', 'Edit current record': 'Editar o registro atual', 'edit profile': 'editar perfil', 'Edit This App': 'Edit This App', 'Email and SMS': 'Email and SMS', 'Errors': 'Errors', 'export as csv file': 'exportar como um arquivo csv', 'FAQ': 'FAQ', 'First name': 'First name', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group ID': 'Group ID', 'Groups': 'Groups', 'Hello World': 'Olá Mundo', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Importar/Exportar', 'Index': 'Início', 'insert new': 'inserir novo', 'insert new %s': 'inserir novo %s', 'Internal State': 'Estado Interno', 'Introduction': 'Introduction', 'Invalid email': 'Invalid email', 'Invalid Query': 'Consulta Inválida', 'invalid request': 'requisição inválida', 'Key': 'Key', 'Last name': 'Last name', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live chat': 'Live chat', 'Live Chat': 'Live Chat', 'login': 'Entrar', 'Login': 'Autentique-se', 'logout': 'Sair', 'Lost Password': 'Esqueceu sua senha?', 'lost password?': 'lost password?', 'Main Menu': 'Menu Principal', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Modelo de Menu', 'My Sites': 'My Sites', 'Name': 'Name', 'New Record': 'Novo Registro', 'new record inserted': 'novo registro inserido', 'next 100 rows': 'próximas 100 linhas', 'No databases in this application': 'Sem bancos de dados nesta aplicação', 'Online examples': 'Alguns exemplos', 'or import from csv file': 'ou importar de um arquivo csv', 'Origin': 'Origin', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'previous 100 rows': '100 linhas anteriores', 'Python': 'Python', 'Query:': 'Consulta:', 'Quick Examples': 'Quick Examples', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Recipes', 'Record': 'registro', 'record does not exist': 'registro não existe', 'Record ID': 'Record ID', 'Record id': 'id do registro', 'Register': 'Registre-se', 'register': 'Registre-se', 'Registration key': 'Registration key', 'Reset Password key': 'Reset Password key', 'Resources': 'Resources', 'Role': 'Role', 'Rows in Table': 'Linhas na tabela', 'Rows selected': 'Linhas selecionadas', 'Semantic': 'Semantic', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'estado', 'Statistics': 'Statistics', 'Stylesheet': 'Stylesheet', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'Está certo(a) que deseja apagar esse objeto ?', 'Table': 'tabela', 'Table name': 'Table name', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'Uma "consulta" é uma condição como "db.tabela1.campo1==\'valor\'". Expressões como "db.tabela1.campo1==db.tabela2.campo2" resultam em um JOIN SQL.', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'This is a copy of the scaffolding application': 'This is a copy of the scaffolding application', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Timestamp', 'Twitter': 'Twitter', 'unable to parse csv file': 'não foi possível analisar arquivo csv', 'Update:': 'Atualizar:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Use (...)&(...) para AND, (...)|(...) para OR, e ~(...) para NOT para construir consultas mais complexas.', 'User ID': 'User ID', 'User Voice': 'User Voice', 'Videos': 'Videos', 'View': 'Visualização', 'Web2py': 'Web2py', 'Welcome': 'Welcome', 'Welcome %s': 'Vem vindo %s', 'Welcome to web2py': 'Bem vindo ao web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You are successfully running web2py.': 'You are successfully running web2py.', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!langcode!': 'fr', '!langname!': 'Français', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN', '%s %%{row} deleted': '%s lignes supprimées', '%s %%{row} updated': '%s lignes mises à jour', '%s selected': '%s sélectionné', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'About': 'À propos', 'Access Control': "Contrôle d'accès", 'Administrative Interface': "Interface d'administration", 'Administrative interface': "Interface d'administration", 'Ajax Recipes': 'Recettes Ajax', 'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé", 'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Authentication': 'Authentification', 'Available Databases and Tables': 'Bases de données et tables disponibles', 'Buy this book': 'Acheter ce livre', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Clés de cache', 'Cannot be empty': 'Ne peut pas être vide', 'change password': 'changer le mot de passe', 'Check to delete': 'Cliquez pour supprimer', 'Check to delete:': 'Cliquez pour supprimer:', 'Clear CACHE?': 'Vider le CACHE?', 'Clear DISK': 'Vider le DISQUE', 'Clear RAM': 'Vider la RAM', 'Client IP': 'IP client', 'Community': 'Communauté', 'Components and Plugins': 'Composants et Plugins', 'Controller': 'Contrôleur', 'Copyright': 'Copyright', 'Created By': 'Créé par', 'Created On': 'Créé le', 'Current request': 'Demande actuelle', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'customize me!': 'personnalisez-moi!', 'data uploaded': 'données téléchargées', 'Database': 'base de données', 'Database %s select': 'base de données %s selectionnée', 'db': 'bdd', 'DB Model': 'Modèle BDD', 'Delete:': 'Supprimer:', 'Demo': 'Démo', 'Deployment Recipes': 'Recettes de déploiement', 'Description': 'Description', 'design': 'design', 'DISK': 'DISQUE', 'Disk Cache Keys': 'Clés de cache du disque', 'Disk Cleared': 'Disque vidé', 'Documentation': 'Documentation', "Don't know what to do?": 'Vous ne savez pas quoi faire?', 'done!': 'fait!', 'Download': 'Téléchargement', 'E-mail': 'E-mail', 'Edit': 'Éditer', 'Edit current record': "Modifier l'enregistrement courant", 'edit profile': 'modifier le profil', 'Edit This App': 'Modifier cette application', 'Email and SMS': 'Email et SMS', 'enter an integer between %(min)g and %(max)g': 'entrez un entier entre %(min)g et %(max)g', 'Errors': 'Erreurs', 'export as csv file': 'exporter sous forme de fichier csv', 'FAQ': 'FAQ', 'First name': 'Prénom', 'Forms and Validators': 'Formulaires et Validateurs', 'Free Applications': 'Applications gratuites', 'Function disabled': 'Fonction désactivée', 'Group ID': 'Groupe ID', 'Groups': 'Groupes', 'Hello World': 'Bonjour le monde', 'Home': 'Accueil', 'How did you get here?': 'Comment êtes-vous arrivé ici?', 'import': 'import', 'Import/Export': 'Importer/Exporter', 'Index': 'Index', 'insert new': 'insérer un nouveau', 'insert new %s': 'insérer un nouveau %s', 'Internal State': 'État interne', 'Introduction': 'Introduction', 'Invalid email': 'E-mail invalide', 'Invalid Query': 'Requête Invalide', 'invalid request': 'requête invalide', 'Is Active': 'Est actif', 'Key': 'Clé', 'Last name': 'Nom', 'Layout': 'Mise en page', 'Layout Plugins': 'Plugins de mise en page', 'Layouts': 'Mises en page', 'Live chat': 'Chat en direct', 'Live Chat': 'Chat en direct', 'login': 'connectez-vous', 'Login': 'Connectez-vous', 'logout': 'déconnectez-vous', 'lost password': 'mot de passe perdu', 'Lost Password': 'Mot de passe perdu', 'Lost password?': 'Mot de passe perdu?', 'lost password?': 'mot de passe perdu?', 'Main Menu': 'Menu principal', 'Manage Cache': 'Gérer le Cache', 'Menu Model': 'Menu modèle', 'Modified By': 'Modifié par', 'Modified On': 'Modifié le', 'My Sites': 'Mes sites', 'Name': 'Nom', 'New Record': 'Nouvel enregistrement', 'new record inserted': 'nouvel enregistrement inséré', 'next 100 rows': '100 prochaines lignes', 'No databases in this application': "Cette application n'a pas de bases de données", 'Object or table name': 'Objet ou nom de table', 'Online examples': 'Exemples en ligne', 'or import from csv file': "ou importer d'un fichier CSV", 'Origin': 'Origine', 'Other Plugins': 'Autres Plugins', 'Other Recipes': 'Autres recettes', 'Overview': 'Présentation', 'Password': 'Mot de passe', "Password fields don't match": 'Les mots de passe ne correspondent pas', 'Plugins': 'Plugins', 'Powered by': 'Alimenté par', 'Preface': 'Préface', 'previous 100 rows': '100 lignes précédentes', 'Python': 'Python', 'Query:': 'Requête:', 'Quick Examples': 'Exemples Rapides', 'RAM': 'RAM', 'RAM Cache Keys': 'Clés de cache de la RAM', 'Ram Cleared': 'Ram vidée', 'Readme': 'Lisez-moi', 'Recipes': 'Recettes', 'Record': 'enregistrement', 'record does not exist': "l'archive n'existe pas", 'Record ID': "ID d'enregistrement", 'Record id': "id d'enregistrement", 'Register': "S'inscrire", 'register': "s'inscrire", 'Registration identifier': "Identifiant d'enregistrement", 'Registration key': "Clé d'enregistrement", 'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)', 'Request reset password': 'Demande de réinitialiser le mot clé', 'Reset Password key': 'Réinitialiser le mot clé', 'Resources': 'Ressources', 'Role': 'Rôle', 'Rows in Table': 'Lignes du tableau', 'Rows selected': 'Lignes sélectionnées', 'Semantic': 'Sémantique', 'Services': 'Services', 'Size of cache:': 'Taille du cache:', 'state': 'état', 'Statistics': 'Statistiques', 'Stylesheet': 'Feuille de style', 'submit': 'soumettre', 'Submit': 'Soumettre', 'Support': 'Support', 'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Table': 'tableau', 'Table name': 'Nom du tableau', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "requête" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.', 'The Core': 'Le noyau', 'The output of the file is a dictionary that was rendered by the view %s': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue %s', 'The Views': 'Les Vues', 'This App': 'Cette Appli', 'This is a copy of the scaffolding application': "Ceci est une copie de l'application échafaudage", 'Time in Cache (h:m:s)': 'Temps en Cache (h:m:s)', 'Timestamp': 'Horodatage', 'Twitter': 'Twitter', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'Update:': 'Mise à jour:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT afin de construire des requêtes plus complexes.', 'User %(id)s Logged-in': 'Utilisateur %(id)s connecté', 'User %(id)s Registered': 'Utilisateur %(id)s enregistré', 'User ID': 'ID utilisateur', 'User Voice': "Voix de l'utilisateur", 'Verify Password': 'Vérifiez le mot de passe', 'Videos': 'Vidéos', 'View': 'Présentation', 'Web2py': 'Web2py', 'Welcome': 'Bienvenue', 'Welcome %s': 'Bienvenue %s', 'Welcome to web2py': 'Bienvenue à web2py', 'Welcome to web2py!': 'Bienvenue à web2py!', 'Which called the function %s located in the file %s': 'Qui a appelé la fonction %s se trouvant dans le fichier %s', 'You are successfully running web2py': 'Vous exécutez avec succès web2py', 'You can modify this application and adapt it to your needs': "Vous pouvez modifier cette application et l'adapter à vos besoins", 'You visited the url %s': "Vous avez visité l'URL %s", }
Python
# coding: utf8 { '!langcode!': 'fr-ca', '!langname!': 'Français (Canadien)', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats d\'un JOIN', '%s %%{row} deleted': '%s rangées supprimées', '%s %%{row} updated': '%s rangées mises à jour', '%s selected': '%s sélectionné', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', 'about': 'à propos', 'About': 'À propos', 'Access Control': "Contrôle d'accès", 'Administrative Interface': 'Administrative Interface', 'Administrative interface': "Interface d'administration", 'Ajax Recipes': 'Recettes Ajax', 'appadmin is disabled because insecure channel': "appadmin est désactivée parce que le canal n'est pas sécurisé", 'Are you sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Authentication': 'Authentification', 'Available Databases and Tables': 'Bases de données et tables disponibles', 'Buy this book': 'Acheter ce livre', 'cache': 'cache', 'Cache': 'Cache', 'Cache Keys': 'Cache Keys', 'Cannot be empty': 'Ne peut pas être vide', 'change password': 'changer le mot de passe', 'Check to delete': 'Cliquez pour supprimer', 'Check to delete:': 'Cliquez pour supprimer:', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'Client IP': 'IP client', 'Community': 'Communauté', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Contrôleur', 'Copyright': "Droit d'auteur", 'Current request': 'Demande actuelle', 'Current response': 'Réponse actuelle', 'Current session': 'Session en cours', 'customize me!': 'personnalisez-moi!', 'data uploaded': 'données téléchargées', 'Database': 'base de données', 'Database %s select': 'base de données %s select', 'db': 'db', 'DB Model': 'Modèle DB', 'Delete:': 'Supprimer:', 'Demo': 'Démo', 'Deployment Recipes': 'Recettes de déploiement ', 'Description': 'Descriptif', 'design': 'design', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'done!': 'fait!', 'Download': 'Téléchargement', 'E-mail': 'Courriel', 'Edit': 'Éditer', 'Edit current record': "Modifier l'enregistrement courant", 'edit profile': 'modifier le profil', 'Edit This App': 'Modifier cette application', 'Email and SMS': 'Email and SMS', 'enter an integer between %(min)g and %(max)g': 'entrer un entier compris entre %(min)g et %(max)g', 'Errors': 'Erreurs', 'export as csv file': 'exporter sous forme de fichier csv', 'FAQ': 'faq', 'First name': 'Prénom', 'Forms and Validators': 'Formulaires et Validateurs', 'Free Applications': 'Applications gratuites', 'Function disabled': 'Fonction désactivée', 'Group %(group_id)s created': '%(group_id)s groupe créé', 'Group ID': 'Groupe ID', 'Group uniquely assigned to user %(id)s': "Groupe unique attribué à l'utilisateur %(id)s", 'Groups': 'Groupes', 'Hello World': 'Bonjour le monde', 'Home': 'Accueil', 'How did you get here?': 'How did you get here?', 'import': 'import', 'Import/Export': 'Importer/Exporter', 'Index': 'Index', 'insert new': 'insérer un nouveau', 'insert new %s': 'insérer un nouveau %s', 'Internal State': 'État interne', 'Introduction': 'Présentation', 'Invalid email': 'Courriel invalide', 'Invalid Query': 'Requête Invalide', 'invalid request': 'requête invalide', 'Key': 'Key', 'Last name': 'Nom', 'Layout': 'Mise en page', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'layouts', 'Live chat': 'Clavardage en direct', 'Live Chat': 'Live Chat', 'Logged in': 'Connecté', 'login': 'connectez-vous', 'Login': 'Connectez-vous', 'logout': 'déconnectez-vous', 'lost password': 'mot de passe perdu', 'Lost Password': 'Mot de passe perdu', 'lost password?': 'mot de passe perdu?', 'Main Menu': 'Menu principal', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Menu modèle', 'My Sites': 'My Sites', 'Name': 'Nom', 'New Record': 'Nouvel enregistrement', 'new record inserted': 'nouvel enregistrement inséré', 'next 100 rows': '100 prochaines lignes', 'No databases in this application': "Cette application n'a pas de bases de données", 'Online examples': 'Exemples en ligne', 'or import from csv file': "ou importer d'un fichier CSV", 'Origin': 'Origine', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Autres recettes', 'Overview': 'Présentation', 'password': 'mot de passe', 'Password': 'Mot de passe', "Password fields don't match": 'Les mots de passe ne correspondent pas', 'please input your password again': "S'il vous plaît entrer votre mot de passe", 'Plugins': 'Plugiciels', 'Powered by': 'Alimenté par', 'Preface': 'Préface', 'previous 100 rows': '100 lignes précédentes', 'profile': 'profile', 'Python': 'Python', 'Query:': 'Requête:', 'Quick Examples': 'Examples Rapides', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Cleared', 'Readme': 'Lisez-moi', 'Recipes': 'Recettes', 'Record': 'enregistrement', 'Record %(id)s created': 'Record %(id)s created', 'Record %(id)s updated': 'Record %(id)s updated', 'Record Created': 'Record Created', 'record does not exist': "l'archive n'existe pas", 'Record ID': "ID d'enregistrement", 'Record id': "id d'enregistrement", 'Record Updated': 'Record Updated', 'Register': "S'inscrire", 'register': "s'inscrire", 'Registration key': "Clé d'enregistrement", 'Registration successful': 'Inscription réussie', 'Remember me (for 30 days)': 'Se souvenir de moi (pendant 30 jours)', 'Request reset password': 'Demande de réinitialiser le mot clé', 'Reset Password key': 'Réinitialiser le mot clé', 'Resources': 'Ressources', 'Role': 'Rôle', 'Rows in Table': 'Lignes du tableau', 'Rows selected': 'Lignes sélectionnées', 'Semantic': 'Sémantique', 'Services': 'Services', 'Size of cache:': 'Size of cache:', 'state': 'état', 'Statistics': 'Statistics', 'Stylesheet': 'Feuille de style', 'submit': 'submit', 'Submit': 'Soumettre', 'Support': 'Soutien', 'Sure you want to delete this object?': 'Êtes-vous sûr de vouloir supprimer cet objet?', 'Table': 'tableau', 'Table name': 'Nom du tableau', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'La "query" est une condition comme "db.table1.champ1==\'valeur\'". Quelque chose comme "db.table1.champ1==db.table2.champ2" résulte en un JOIN SQL.', 'The Core': 'Le noyau', 'The output of the file is a dictionary that was rendered by the view %s': 'La sortie de ce fichier est un dictionnaire qui été restitué par la vue %s', 'The Views': 'Les Vues', 'This App': 'Cette Appli', 'This is a copy of the scaffolding application': "Ceci est une copie de l'application échafaudage", 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Horodatage', 'Twitter': 'Twitter', 'unable to parse csv file': "incapable d'analyser le fichier cvs", 'Update:': 'Mise à jour:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Employez (...)&(...) pour AND, (...)|(...) pour OR, and ~(...) pour NOT pour construire des requêtes plus complexes.', 'User %(id)s Logged-in': 'Utilisateur %(id)s connecté', 'User %(id)s Registered': 'Utilisateur %(id)s enregistré', 'User ID': 'ID utilisateur', 'User Voice': 'User Voice', 'value already in database or empty': 'valeur déjà dans la base ou vide', 'Verify Password': 'Vérifiez le mot de passe', 'Videos': 'Vidéos', 'View': 'Présentation', 'Web2py': 'Web2py', 'Welcome': 'Bienvenu', 'Welcome %s': 'Bienvenue %s', 'Welcome to web2py': 'Bienvenue à web2py', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Qui a appelé la fonction %s se trouvant dans le fichier %s', 'You are successfully running web2py': 'Vous roulez avec succès web2py', 'You can modify this application and adapt it to your needs': "Vous pouvez modifier cette application et l'adapter à vos besoins", 'You visited the url %s': "Vous avez visité l'URL %s", }
Python
# coding: utf8 { '!langcode!': 'nl', '!langname!': 'Nederlands', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN', '%(nrows)s records found': '%(nrows)s records gevonden', '%d days ago': '%d dagen geleden', '%d weeks ago': '%d weken gelden', '%s %%{row} deleted': '%s rijen verwijderd', '%s %%{row} updated': '%s rijen geupdate', '%s selected': '%s geselecteerd', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(zoiets als "nl-nl")', '1 day ago': '1 dag geleden', '1 week ago': '1 week gelden', '<': '<', '<=': '<=', '=': '=', '>': '>', '>=': '>=', 'A new version of web2py is available': 'Een nieuwe versie van web2py is beschikbaar', 'A new version of web2py is available: %s': 'Een nieuwe versie van web2py is beschikbaar: %s', 'About': 'Over', 'about': 'over', 'About application': 'Over applicatie', 'Access Control': 'Toegangscontrole', 'Add': 'Toevoegen', 'additional code for your application': 'additionele code voor je applicatie', 'admin disabled because no admin password': 'admin is uitgezet omdat er geen admin wachtwoord is', 'admin disabled because not supported on google app engine': 'admin is uitgezet omdat dit niet ondersteund wordt op google app engine', 'admin disabled because unable to access password file': 'admin is uitgezet omdat het wachtwoordbestand niet geopend kan worden', 'Admin is disabled because insecure channel': 'Admin is uitgezet om het kanaal onveilig is', 'Admin is disabled because unsecure channel': 'Admin is uitgezet om het kanaal onveilig is', 'Administration': 'Administratie', 'Administrative Interface': 'Administratieve Interface', 'Administrator Password:': 'Administrator Wachtwoord', 'Ajax Recipes': 'Ajax Recepten', 'And': 'En', 'and rename it (required):': 'en hernoem deze (vereist)', 'and rename it:': 'en hernoem:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin is uitgezet vanwege een onveilig kanaal', 'application "%s" uninstalled': 'applicatie "%s" gedeïnstalleerd', 'application compiled': 'applicatie gecompileerd', 'application is compiled and cannot be designed': 'applicatie is gecompileerd en kan niet worden ontworpen', 'Are you sure you want to delete file "%s"?': 'Weet je zeker dat je bestand "%s" wilt verwijderen?', 'Are you sure you want to delete this object?': 'Weet je zeker dat je dit object wilt verwijderen?', 'Are you sure you want to uninstall application "%s"?': 'Weet je zeker dat je applicatie "%s" wilt deïnstalleren?', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'LET OP: Login vereist een beveiligde (HTTPS) connectie of moet draaien op localhost.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'LET OP: TESTEN IS NIET THREAD SAFE, PROBEER NIET GELIJKTIJDIG MEERDERE TESTS TE DOEN.', 'ATTENTION: you cannot edit the running application!': 'LET OP: je kan de applicatie die nu draait niet editen!', 'Authentication': 'Authenticatie', 'Available Databases and Tables': 'Beschikbare databases en tabellen', 'Back': 'Terug', 'Buy this book': 'Koop dit boek', 'Cache': 'Cache', 'cache': 'cache', 'Cache Keys': 'Cache Keys', 'cache, errors and sessions cleaned': 'cache, errors en sessies geleegd', 'Cannot be empty': 'Mag niet leeg zijn', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Kan niet compileren: er bevinden zich fouten in je app. Debug, corrigeer de fouten en probeer opnieuw.', 'cannot create file': 'kan bestand niet maken', 'cannot upload file "%(filename)s"': 'kan bestand "%(filename)s" niet uploaden', 'Change Password': 'Wijzig wachtwoord', 'Change password': 'Wijzig Wachtwoord', 'change password': 'wijzig wachtwoord', 'check all': 'vink alles aan', 'Check to delete': 'Vink aan om te verwijderen', 'clean': 'leeg', 'Clear': 'Leeg', 'Clear CACHE?': 'Leeg CACHE?', 'Clear DISK': 'Leeg DISK', 'Clear RAM': 'Clear RAM', 'click to check for upgrades': 'Klik om voor upgrades te controleren', 'Client IP': 'Client IP', 'Community': 'Community', 'compile': 'compileren', 'compiled application removed': 'gecompileerde applicatie verwijderd', 'Components and Plugins': 'Components en Plugins', 'contains': 'bevat', 'Controller': 'Controller', 'Controllers': 'Controllers', 'controllers': 'controllers', 'Copyright': 'Copyright', 'create file with filename:': 'maak bestand met de naam:', 'Create new application': 'Maak nieuwe applicatie:', 'create new application:': 'maak nieuwe applicatie', 'Created By': 'Gemaakt Door', 'Created On': 'Gemaakt Op', 'crontab': 'crontab', 'Current request': 'Huidige request', 'Current response': 'Huidige response', 'Current session': 'Huidige sessie', 'currently saved or': 'op het moment opgeslagen of', 'customize me!': 'pas me aan!', 'data uploaded': 'data geupload', 'Database': 'Database', 'Database %s select': 'Database %s select', 'database administration': 'database administratie', 'Date and Time': 'Datum en Tijd', 'db': 'db', 'DB Model': 'DB Model', 'defines tables': 'definieer tabellen', 'Delete': 'Verwijder', 'delete': 'verwijder', 'delete all checked': 'verwijder alle aangevinkten', 'Delete:': 'Verwijder:', 'Demo': 'Demo', 'Deploy on Google App Engine': 'Deploy op Google App Engine', 'Deployment Recipes': 'Deployment Recepten', 'Description': 'Beschrijving', 'design': 'design', 'DESIGN': 'DESIGN', 'Design for': 'Design voor', 'DISK': 'DISK', 'Disk Cache Keys': 'Disk Cache Keys', 'Disk Cleared': 'Disk Geleegd', 'Documentation': 'Documentatie', "Don't know what to do?": 'Weet je niet wat je moet doen?', 'done!': 'gereed!', 'Download': 'Download', 'E-mail': 'E-mail', 'E-mail invalid': 'E-mail ongeldig', 'edit': 'bewerk', 'EDIT': 'BEWERK', 'Edit': 'Bewerk', 'Edit application': 'Bewerk applicatie', 'edit controller': 'bewerk controller', 'Edit current record': 'Bewerk huidig record', 'Edit Profile': 'Bewerk Profiel', 'edit profile': 'bewerk profiel', 'Edit This App': 'Bewerk Deze App', 'Editing file': 'Bewerk bestand', 'Editing file "%s"': 'Bewerk bestand "%s"', 'Email and SMS': 'E-mail en SMS', 'enter a number between %(min)g and %(max)g': 'geef een getal tussen %(min)g en %(max)g', 'enter an integer between %(min)g and %(max)g': 'geef een integer tussen %(min)g en %(max)g', 'Error logs for "%(app)s"': 'Error logs voor "%(app)s"', 'errors': 'errors', 'Errors': 'Errors', 'Export': 'Export', 'export as csv file': 'exporteer als csv-bestand', 'exposes': 'stelt bloot', 'extends': 'extends', 'failed to reload module': 'niet gelukt om module te herladen', 'False': 'Onwaar', 'FAQ': 'FAQ', 'file "%(filename)s" created': 'bestand "%(filename)s" gemaakt', 'file "%(filename)s" deleted': 'bestand "%(filename)s" verwijderd', 'file "%(filename)s" uploaded': 'bestand "%(filename)s" geupload', 'file "%(filename)s" was not deleted': 'bestand "%(filename)s" was niet verwijderd', 'file "%s" of %s restored': 'bestand "%s" van %s hersteld', 'file changed on disk': 'bestand aangepast op schijf', 'file does not exist': 'bestand bestaat niet', 'file saved on %(time)s': 'bestand bewaard op %(time)s', 'file saved on %s': 'bestand bewaard op %s', 'First name': 'Voornaam', 'Forbidden': 'Verboden', 'Forms and Validators': 'Formulieren en Validators', 'Free Applications': 'Gratis Applicaties', 'Functions with no doctests will result in [passed] tests.': 'Functies zonder doctests zullen resulteren in [passed] tests.', 'Group %(group_id)s created': 'Groep %(group_id)s gemaakt', 'Group ID': 'Groep ID', 'Group uniquely assigned to user %(id)s': 'Groep is uniek toegekend aan gebruiker %(id)s', 'Groups': 'Groepen', 'Hello World': 'Hallo Wereld', 'help': 'help', 'Home': 'Home', 'How did you get here?': 'Hoe ben je hier gekomen?', 'htmledit': 'Bewerk HTML', 'import': 'import', 'Import/Export': 'Import/Export', 'includes': 'includes', 'Index': 'Index', 'insert new': 'voeg nieuwe', 'insert new %s': 'voeg nieuwe %s', 'Installed applications': 'Geïnstalleerde applicaties', 'internal error': 'interne error', 'Internal State': 'Interne State', 'Introduction': 'Introductie', 'Invalid action': 'Ongeldige actie', 'Invalid email': 'Ongeldig emailadres', 'invalid password': 'ongeldig wachtwoord', 'Invalid password': 'Ongeldig wachtwoord', 'Invalid Query': 'Ongeldige Query', 'invalid request': 'ongeldige request', 'invalid ticket': 'ongeldige ticket', 'Is Active': 'Is Actief', 'Key': 'Key', 'language file "%(filename)s" created/updated': 'taalbestand "%(filename)s" gemaakt/geupdate', 'Language files (static strings) updated': 'Taalbestanden (statische strings) geupdate', 'languages': 'talen', 'Languages': 'Talen', 'languages updated': 'talen geupdate', 'Last name': 'Achternaam', 'Last saved on:': 'Laatst bewaard op:', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'License for': 'Licentie voor', 'Live Chat': 'Live Chat', 'loading...': 'laden...', 'Logged in': 'Ingelogd', 'Logged out': 'Uitgelogd', 'Login': 'Login', 'login': 'login', 'Login to the Administrative Interface': 'Inloggen op de Administratieve Interface', 'logout': 'logout', 'Logout': 'Logout', 'Lost Password': 'Wachtwoord Kwijt', 'Lost password?': 'Wachtwoord kwijt?', 'Main Menu': 'Hoofdmenu', 'Manage Cache': 'Beheer Cache', 'Menu Model': 'Menu Model', 'merge': 'samenvoegen', 'Models': 'Modellen', 'models': 'modellen', 'Modified By': 'Aangepast Door', 'Modified On': 'Aangepast Op', 'Modules': 'Modules', 'modules': 'modules', 'My Sites': 'Mijn Sites', 'Name': 'Naam', 'New': 'Nieuw', 'new application "%s" created': 'nieuwe applicatie "%s" gemaakt', 'New password': 'Nieuw wachtwoord', 'New Record': 'Nieuw Record', 'new record inserted': 'nieuw record ingevoegd', 'next 100 rows': 'volgende 100 rijen', 'NO': 'NEE', 'No databases in this application': 'Geen database in deze applicatie', 'Object or table name': 'Object of tabelnaam', 'Old password': 'Oude wachtwoord', 'Online examples': 'Online voorbeelden', 'Or': 'Of', 'or import from csv file': 'of importeer van csv-bestand', 'or provide application url:': 'of geef een applicatie url:', 'Origin': 'Bron', 'Original/Translation': 'Oorspronkelijk/Vertaling', 'Other Plugins': 'Andere Plugins', 'Other Recipes': 'Andere Recepten', 'Overview': 'Overzicht', 'pack all': 'pack all', 'pack compiled': 'pack compiled', 'Password': 'Wachtwoord', "Password fields don't match": 'Wachtwoordvelden komen niet overeen', 'Peeking at file': 'Naar bestand aan het gluren', 'please input your password again': 'geef alstublieft nogmaals uw wachtwoord', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Inleiding', 'previous 100 rows': 'vorige 100 rijen', 'Profile': 'Profiel', 'Python': 'Python', 'Query': 'Query', 'Query:': 'Query:', 'Quick Examples': 'Snelle Voorbeelden', 'RAM': 'RAM', 'RAM Cache Keys': 'RAM Cache Keys', 'Ram Cleared': 'Ram Geleegd', 'Recipes': 'Recepten', 'Record': 'Record', 'record does not exist': 'record bestaat niet', 'Record ID': 'Record ID', 'Record id': 'Record id', 'register': 'registreer', 'Register': 'Registreer', 'Registration identifier': 'Registratie identifier', 'Registration key': 'Registratie sleutel', 'Registration successful': 'Registratie succesvol', 'Remember me (for 30 days)': 'Onthoudt mij (voor 30 dagen)', 'remove compiled': 'verwijder gecompileerde', 'Request reset password': 'Vraag een wachtwoord reset aan', 'Reset Password key': 'Reset Wachtwoord sleutel', 'Resolve Conflict file': 'Los Conflictbestand op', 'restore': 'herstel', 'revert': 'herstel', 'Role': 'Rol', 'Rows in Table': 'Rijen in tabel', 'Rows selected': 'Rijen geselecteerd', 'save': 'bewaar', 'Save profile': 'Bewaar profiel', 'Saved file hash:': 'Opgeslagen file hash:', 'Search': 'Zoek', 'Semantic': 'Semantisch', 'Services': 'Services', 'session expired': 'sessie verlopen', 'shell': 'shell', 'site': 'site', 'Size of cache:': 'Grootte van cache:', 'some files could not be removed': 'sommige bestanden konden niet worden verwijderd', 'starts with': 'begint met', 'state': 'state', 'static': 'statisch', 'Static files': 'Statische bestanden', 'Statistics': 'Statistieken', 'Stylesheet': 'Stylesheet', 'Submit': 'Submit', 'submit': 'submit', 'Support': 'Support', 'Sure you want to delete this object?': 'Weet je zeker dat je dit object wilt verwijderen?', 'Table': 'Tabel', 'Table name': 'Tabelnaam', 'test': 'test', 'Testing application': 'Applicatie testen', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': 'De "query" is een conditie zoals "db.tabel1.veld1==\'waarde\'". Zoiets als "db.tabel1.veld1==db.tabel2.veld2" resulteert in een SQL JOIN.', 'the application logic, each URL path is mapped in one exposed function in the controller': 'the applicatie logica, elk URL pad is gemapped in een blootgestelde functie in de controller', 'The Core': 'De Core', 'the data representation, define database tables and sets': 'de data representatie, definieert database tabellen en sets', 'The output of the file is a dictionary that was rendered by the view %s': 'De output van het bestand is een dictionary die gerenderd werd door de view %s', 'the presentations layer, views are also known as templates': 'de presentatie laag, views zijn ook bekend als templates', 'The Views': 'De Views', 'There are no controllers': 'Er zijn geen controllers', 'There are no models': 'Er zijn geen modellen', 'There are no modules': 'Er zijn geen modules', 'There are no static files': 'Er zijn geen statische bestanden', 'There are no translators, only default language is supported': 'Er zijn geen vertalingen, alleen de standaard taal wordt ondersteund.', 'There are no views': 'Er zijn geen views', 'these files are served without processing, your images go here': 'Deze bestanden worden geserveerd zonder verdere verwerking, je afbeeldingen horen hier', 'This App': 'Deze App', 'This is a copy of the scaffolding application': 'Dit is een kopie van de steiger-applicatie', 'This is the %(filename)s template': 'Dit is de %(filename)s template', 'Ticket': 'Ticket', 'Time in Cache (h:m:s)': 'Tijd in Cache (h:m:s)', 'Timestamp': 'Timestamp (timestamp)', 'to previous version.': 'naar vorige versie.', 'too short': 'te kort', 'translation strings for the application': 'vertaalstrings voor de applicatie', 'True': 'Waar', 'try': 'probeer', 'try something like': 'probeer zoiets als', 'Twitter': 'Twitter', 'Unable to check for upgrades': 'Niet mogelijk om te controleren voor upgrades', 'unable to create application "%s"': 'niet mogelijk om applicatie "%s" te maken', 'unable to delete file "%(filename)s"': 'niet mogelijk om bestand "%(filename)s" te verwijderen', 'Unable to download': 'Niet mogelijk om te downloaden', 'Unable to download app': 'Niet mogelijk om app te downloaden', 'unable to parse csv file': 'niet mogelijk om csv-bestand te parsen', 'unable to uninstall "%s"': 'niet mogelijk om "%s" te deïnstalleren', 'uncheck all': 'vink alles uit', 'uninstall': ' deïnstalleer', 'update': 'update', 'update all languages': 'update alle talen', 'Update:': 'Update:', 'upload application:': 'upload applicatie:', 'Upload existing application': 'Upload bestaande applicatie', 'upload file:': 'upload bestand', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Gebruik (...)&(...) voor AND, (...)|(...) voor OR, en ~(...) voor NOT om meer complexe queries te maken.', 'User %(id)s Logged-in': 'Gebruiker %(id)s Logged-in', 'User %(id)s Logged-out': 'Gebruiker %(id)s Logged-out', 'User %(id)s Password changed': 'Wachtwoord van gebruiker %(id)s is veranderd', 'User %(id)s Password reset': 'Wachtwoord van gebruiker %(id)s is gereset', 'User %(id)s Profile updated': 'Profiel van Gebruiker %(id)s geupdate', 'User %(id)s Registered': 'Gebruiker %(id)s Geregistreerd', 'User ID': 'User ID', 'value already in database or empty': 'waarde al in database of leeg', 'Verify Password': 'Verifieer Wachtwoord', 'versioning': 'versionering', 'Videos': 'Videos', 'View': 'View', 'view': 'view', 'Views': 'Vieuws', 'views': 'vieuws', 'web2py is up to date': 'web2py is up to date', 'web2py Recent Tweets': 'web2py Recente Tweets', 'Welcome': 'Welkom', 'Welcome %s': 'Welkom %s', 'Welcome to web2py': 'Welkom bij web2py', 'Welcome to web2py!': 'Welkom bij web2py!', 'Which called the function %s located in the file %s': 'Die functie %s aanriep en zich bevindt in het bestand %s', 'YES': 'JA', 'You are successfully running web2py': 'Je draait web2py succesvol', 'You can modify this application and adapt it to your needs': 'Je kan deze applicatie aanpassen naar je eigen behoeften', 'You visited the url %s': 'Je bezocht de url %s', }
Python
# coding: utf8 { '!langcode!': 'en-us', '!langname!': 'English (US)', '%s %%(shop)': '%s %%(shop)', '%s %%(shop[0])': '%s %%(shop[0])', '%s %%{quark[0]}': '%s %%{quark[0]}', '%s %%{shop[0]}': '%s %%{shop[0]}', '%s %%{shop}': '%s %%{shop}', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '@markmin\x01**Hello World**': '**Hello World**', 'About': 'About', 'Access Control': 'Access Control', 'Administrative Interface': 'Administrative Interface', 'Ajax Recipes': 'Ajax Recipes', 'Are you sure you want to delete this object?': 'Are you sure you want to delete this object?', 'Buy this book': 'Buy this book', 'Cannot be empty': 'Cannot be empty', 'Check to delete': 'Check to delete', 'Client IP': 'Client IP', 'Community': 'Community', 'Components and Plugins': 'Components and Plugins', 'Controller': 'Controller', 'Copyright': 'Copyright', 'Created By': 'Created By', 'Created On': 'Created On', 'customize me!': 'customize me!', 'Database': 'Database', 'DB Model': 'DB Model', 'Demo': 'Demo', 'Deployment Recipes': 'Deployment Recipes', 'Description': 'Description', 'Documentation': 'Documentation', "Don't know what to do?": "Don't know what to do?", 'Download': 'Download', 'E-mail': 'E-mail', 'Email and SMS': 'Email and SMS', 'enter an integer between %(min)g and %(max)g': 'enter an integer between %(min)g and %(max)g', 'enter date and time as %(format)s': 'enter date and time as %(format)s', 'Errors': 'Errors', 'FAQ': 'FAQ', 'First name': 'First name', 'Forms and Validators': 'Forms and Validators', 'Free Applications': 'Free Applications', 'Group %(group_id)s created': 'Group %(group_id)s created', 'Group ID': 'Group ID', 'Group uniquely assigned to user %(id)s': 'Group uniquely assigned to user %(id)s', 'Groups': 'Groups', 'Hello World': 'Hello World', 'Hello World ## comment': 'Hello World ', 'Hello World## comment': 'Hello World', 'Home': 'Home', 'How did you get here?': 'How did you get here?', 'Introduction': 'Introduction', 'Invalid email': 'Invalid email', 'Is Active': 'Is Active', 'Last name': 'Last name', 'Layout': 'Layout', 'Layout Plugins': 'Layout Plugins', 'Layouts': 'Layouts', 'Live Chat': 'Live Chat', 'Logged in': 'Logged in', 'Logged out': 'Logged out', 'Login': 'Login', 'Logout': 'Logout', 'Lost Password': 'Lost Password', 'Lost password?': 'Lost password?', 'Menu Model': 'Menu Model', 'Modified By': 'Modified By', 'Modified On': 'Modified On', 'My Sites': 'My Sites', 'Name': 'Name', 'Object or table name': 'Object or table name', 'Online examples': 'Online examples', 'Origin': 'Origin', 'Other Plugins': 'Other Plugins', 'Other Recipes': 'Other Recipes', 'Overview': 'Overview', 'Password': 'Password', "Password fields don't match": "Password fields don't match", 'please input your password again': 'please input your password again', 'Plugins': 'Plugins', 'Powered by': 'Powered by', 'Preface': 'Preface', 'Profile': 'Profile', 'Python': 'Python', 'Quick Examples': 'Quick Examples', 'Recipes': 'Recipes', 'Record ID': 'Record ID', 'Register': 'Register', 'Registration identifier': 'Registration identifier', 'Registration key': 'Registration key', 'Registration successful': 'Registration successful', 'Remember me (for 30 days)': 'Remember me (for 30 days)', 'Reset Password key': 'Reset Password key', 'Role': 'Role', 'Semantic': 'Semantic', 'Services': 'Services', 'Stylesheet': 'Stylesheet', 'Support': 'Support', 'The Core': 'The Core', 'The output of the file is a dictionary that was rendered by the view %s': 'The output of the file is a dictionary that was rendered by the view %s', 'The Views': 'The Views', 'This App': 'This App', 'Timestamp': 'Timestamp', 'Twitter': 'Twitter', 'User %(id)s Logged-in': 'User %(id)s Logged-in', 'User %(id)s Logged-out': 'User %(id)s Logged-out', 'User %(id)s Registered': 'User %(id)s Registered', 'User ID': 'User ID', 'value already in database or empty': 'value already in database or empty', 'Verify Password': 'Verify Password', 'Videos': 'Videos', 'View': 'View', 'Welcome': 'Welcome', 'Welcome to web2py!': 'Welcome to web2py!', 'Which called the function %s located in the file %s': 'Which called the function %s located in the file %s', 'You are successfully running web2py': 'You are successfully running web2py', 'You can modify this application and adapt it to your needs': 'You can modify this application and adapt it to your needs', 'You visited the url %s': 'You visited the url %s', }
Python
# coding: utf8 { '!=': '!=', '!langcode!': 'ro', '!langname!': 'Română', '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" (actualizează) este o expresie opțională precum "câmp1=\'valoare_nouă\'". Nu puteți actualiza sau șterge rezultatele unui JOIN', '%(nrows)s records found': '%(nrows)s înregistrări găsite', '%d days ago': '%d days ago', '%d weeks ago': '%d weeks ago', '%s %%{row} deleted': '%s linii șterse', '%s %%{row} updated': '%s linii actualizate', '%s selected': '%s selectat(e)', '%Y-%m-%d': '%Y-%m-%d', '%Y-%m-%d %H:%M:%S': '%Y-%m-%d %H:%M:%S', '(something like "it-it")': '(ceva ce seamănă cu "it-it")', '1 day ago': '1 day ago', '1 week ago': '1 week ago', '<': '<', '<=': '<=', '=': '=', '>': '>', '>=': '>=', 'A new version of web2py is available': 'O nouă versiune de web2py este disponibilă', 'A new version of web2py is available: %s': 'O nouă versiune de web2py este disponibilă: %s', 'About': 'Despre', 'about': 'despre', 'About application': 'Despre aplicație', 'Access Control': 'Control acces', 'Add': 'Adaugă', 'additional code for your application': 'cod suplimentar pentru aplicația dvs.', 'admin disabled because no admin password': 'administrare dezactivată deoarece parola de administrator nu a fost furnizată', 'admin disabled because not supported on google app engine': 'administrare dezactivată deoarece funcționalitatea nu e suportat pe Google App Engine', 'admin disabled because unable to access password file': 'administrare dezactivată deoarece nu există acces la fișierul cu parole', 'Admin is disabled because insecure channel': 'Adminstrarea este dezactivată deoarece conexiunea nu este sigură', 'Admin is disabled because unsecure channel': 'Administrarea este dezactivată deoarece conexiunea nu este securizată', 'Administration': 'Administrare', 'Administrative Interface': 'Interfață administrare', 'Administrator Password:': 'Parolă administrator:', 'Ajax Recipes': 'Rețete Ajax', 'And': 'Și', 'and rename it (required):': 'și renumiți (obligatoriu):', 'and rename it:': ' și renumiți:', 'appadmin': 'appadmin', 'appadmin is disabled because insecure channel': 'appadmin dezactivat deoarece conexiunea nu e sigură', 'application "%s" uninstalled': 'aplicația "%s" a fost dezinstalată', 'application compiled': 'aplicația a fost compilată', 'application is compiled and cannot be designed': 'aplicația este compilată și nu poate fi editată', 'Are you sure you want to delete file "%s"?': 'Sigur ștergeți fișierul "%s"?', 'Are you sure you want to delete this object?': 'Sigur ștergeți acest obiect?', 'Are you sure you want to uninstall application "%s"': 'Sigur dezinstalați aplicația "%s"', 'Are you sure you want to uninstall application "%s"?': 'Sigur dezinstalați aplicația "%s"?', 'ATTENTION: Login requires a secure (HTTPS) connection or running on localhost.': 'ATENȚIE: Nu vă puteți conecta decât utilizând o conexiune securizată (HTTPS) sau rulând aplicația pe computerul local.', 'ATTENTION: TESTING IS NOT THREAD SAFE SO DO NOT PERFORM MULTIPLE TESTS CONCURRENTLY.': 'ATENȚIE: Nu puteți efectua mai multe teste o dată deoarece lansarea în execuție a mai multor subpocese nu este sigură.', 'ATTENTION: you cannot edit the running application!': 'ATENȚIE: nu puteți edita o aplicație în curs de execuție!', 'Authentication': 'Autentificare', 'Available Databases and Tables': 'Baze de date și tabele disponibile', 'Back': 'Înapoi', 'Buy this book': 'Cumpără această carte', 'Cache': 'Cache', 'cache': 'cache', 'Cache Keys': 'Chei cache', 'cache, errors and sessions cleaned': 'cache, erori și sesiuni golite', 'Cannot be empty': 'Nu poate fi vid', 'Cannot compile: there are errors in your app. Debug it, correct errors and try again.': 'Compilare imposibilă: aplicația conține erori. Debogați aplicația și încercați din nou.', 'cannot create file': 'fișier imposibil de creat', 'cannot upload file "%(filename)s"': 'imposibil de încărcat fișierul "%(filename)s"', 'Change Password': 'Schimbare parolă', 'Change password': 'Schimbare parolă', 'change password': 'schimbare parolă', 'check all': 'coșați tot', 'Check to delete': 'Coșați pentru a șterge', 'clean': 'golire', 'Clear': 'Golește', 'Clear CACHE?': 'Clear CACHE?', 'Clear DISK': 'Clear DISK', 'Clear RAM': 'Clear RAM', 'click to check for upgrades': 'Clic pentru a verifica dacă există upgrade-uri', 'Client IP': 'IP client', 'Community': 'Comunitate', 'compile': 'compilare', 'compiled application removed': 'aplicația compilată a fost ștearsă', 'Components and Plugins': 'Componente și plugin-uri', 'contains': 'conține', 'Controller': 'Controlor', 'Controllers': 'Controlori', 'controllers': 'controlori', 'Copyright': 'Drepturi de autor', 'create file with filename:': 'crează fișier cu numele:', 'Create new application': 'Creați aplicație nouă', 'create new application:': 'crează aplicație nouă:', 'crontab': 'crontab', 'Current request': 'Cerere curentă', 'Current response': 'Răspuns curent', 'Current session': 'Sesiune curentă', 'currently saved or': 'în prezent salvat sau', 'customize me!': 'Personalizează-mă!', 'data uploaded': 'date încărcate', 'Database': 'bază de date', 'Database %s select': 'selectare bază de date %s', 'database administration': 'administrare bază de date', 'Date and Time': 'Data și ora', 'db': 'db', 'DB Model': 'Model bază de date', 'defines tables': 'definire tabele', 'Delete': 'Șterge', 'delete': 'șterge', 'delete all checked': 'șterge tot ce e coșat', 'Delete:': 'Șterge:', 'Demo': 'Demo', 'Deploy on Google App Engine': 'Instalare pe Google App Engine', 'Deployment Recipes': 'Rețete de instalare', 'Description': 'Descriere', 'design': 'design', 'DESIGN': 'DESIGN', 'Design for': 'Design pentru', 'DISK': 'DISK', 'Disk Cache Keys': 'Chei cache de disc', 'Disk Cleared': 'Disk Cleared', 'Documentation': 'Documentație', "Don't know what to do?": 'Nu știți ce să faceți?', 'done!': 'gata!', 'Download': 'Descărcare', 'E-mail': 'E-mail', 'E-mail invalid': 'E-mail invalid', 'edit': 'editare', 'EDIT': 'EDITARE', 'Edit': 'Editare', 'Edit application': 'Editare aplicație', 'edit controller': 'editare controlor', 'Edit current record': 'Editare înregistrare curentă', 'Edit Profile': 'Editare profil', 'edit profile': 'editare profil', 'Edit This App': 'Editați această aplicație', 'Editing file': 'Editare fișier', 'Editing file "%s"': 'Editare fișier "%s"', 'Email and SMS': 'E-mail și SMS', 'enter a number between %(min)g and %(max)g': 'introduceți un număr între %(min)g și %(max)g', 'enter an integer between %(min)g and %(max)g': 'introduceți un întreg între %(min)g și %(max)g', 'Error logs for "%(app)s"': 'Log erori pentru "%(app)s"', 'errors': 'erori', 'Errors': 'Erori', 'Export': 'Export', 'export as csv file': 'exportă ca fișier csv', 'exposes': 'expune', 'extends': 'extinde', 'failed to reload module': 'reîncarcare modul nereușită', 'False': 'Neadevărat', 'FAQ': 'Întrebări frecvente', 'file "%(filename)s" created': 'fișier "%(filename)s" creat', 'file "%(filename)s" deleted': 'fișier "%(filename)s" șters', 'file "%(filename)s" uploaded': 'fișier "%(filename)s" încărcat', 'file "%(filename)s" was not deleted': 'fișierul "%(filename)s" n-a fost șters', 'file "%s" of %s restored': 'fișier "%s" de %s restaurat', 'file changed on disk': 'fișier modificat pe disc', 'file does not exist': 'fișier inexistent', 'file saved on %(time)s': 'fișier salvat %(time)s', 'file saved on %s': 'fișier salvat pe %s', 'First name': 'Prenume', 'Forbidden': 'Interzis', 'Forms and Validators': 'Formulare și validatori', 'Free Applications': 'Aplicații gratuite', 'Functions with no doctests will result in [passed] tests.': 'Funcțiile fără doctests vor genera teste [trecute].', 'Group %(group_id)s created': 'Grup %(group_id)s creat', 'Group ID': 'ID grup', 'Group uniquely assigned to user %(id)s': 'Grup asociat în mod unic utilizatorului %(id)s', 'Groups': 'Grupuri', 'Hello World': 'Salutare lume', 'help': 'ajutor', 'Home': 'Acasă', 'How did you get here?': 'Cum ați ajuns aici?', 'htmledit': 'editare html', 'import': 'import', 'Import/Export': 'Import/Export', 'includes': 'include', 'Index': 'Index', 'insert new': 'adaugă nou', 'insert new %s': 'adaugă nou %s', 'Installed applications': 'Aplicații instalate', 'internal error': 'eroare internă', 'Internal State': 'Stare internă', 'Introduction': 'Introducere', 'Invalid action': 'Acțiune invalidă', 'Invalid email': 'E-mail invalid', 'invalid password': 'parolă invalidă', 'Invalid password': 'Parolă invalidă', 'Invalid Query': 'Interogare invalidă', 'invalid request': 'cerere invalidă', 'invalid ticket': 'tichet invalid', 'Key': 'Key', 'language file "%(filename)s" created/updated': 'fișier de limbă "%(filename)s" creat/actualizat', 'Language files (static strings) updated': 'Fișierele de limbă (șirurile statice de caractere) actualizate', 'languages': 'limbi', 'Languages': 'Limbi', 'languages updated': 'limbi actualizate', 'Last name': 'Nume', 'Last saved on:': 'Ultima salvare:', 'Layout': 'Șablon', 'Layout Plugins': 'Șablon plugin-uri', 'Layouts': 'Șabloane', 'License for': 'Licență pentru', 'Live Chat': 'Chat live', 'loading...': 'încarc...', 'Logged in': 'Logat', 'Logged out': 'Delogat', 'Login': 'Autentificare', 'login': 'autentificare', 'Login to the Administrative Interface': 'Logare interfață de administrare', 'logout': 'ieșire', 'Logout': 'Ieșire', 'Lost Password': 'Parolă pierdută', 'Lost password?': 'Parolă pierdută?', 'Main Menu': 'Meniu principal', 'Manage Cache': 'Manage Cache', 'Menu Model': 'Model meniu', 'merge': 'unește', 'Models': 'Modele', 'models': 'modele', 'Modules': 'Module', 'modules': 'module', 'My Sites': 'Site-urile mele', 'Name': 'Nume', 'New': 'Nou', 'new application "%s" created': 'aplicația nouă "%s" a fost creată', 'New password': 'Parola nouă', 'New Record': 'Înregistrare nouă', 'new record inserted': 'înregistrare nouă adăugată', 'next 100 rows': 'următoarele 100 de linii', 'NO': 'NU', 'No databases in this application': 'Aplicație fără bază de date', 'Object or table name': 'Obiect sau nume de tabel', 'Old password': 'Parola veche', 'Online examples': 'Exemple online', 'Or': 'Sau', 'or import from csv file': 'sau importă din fișier csv', 'or provide application url:': 'sau furnizează adresă url:', 'Origin': 'Origine', 'Original/Translation': 'Original/Traducere', 'Other Plugins': 'Alte plugin-uri', 'Other Recipes': 'Alte rețete', 'Overview': 'Prezentare de ansamblu', 'pack all': 'împachetează toate', 'pack compiled': 'pachet compilat', 'Password': 'Parola', "Password fields don't match": 'Câmpurile de parolă nu se potrivesc', 'Peeking at file': 'Vizualizare fișier', 'please input your password again': 'introduceți parola din nou', 'Plugins': 'Plugin-uri', 'Powered by': 'Pus în mișcare de', 'Preface': 'Prefață', 'previous 100 rows': '100 de linii anterioare', 'Profile': 'Profil', 'Python': 'Python', 'Query': 'Interogare', 'Query:': 'Interogare:', 'Quick Examples': 'Exemple rapide', 'RAM': 'RAM', 'RAM Cache Keys': 'Chei cache RAM', 'Ram Cleared': 'Ram Cleared', 'Recipes': 'Rețete', 'Record': 'înregistrare', 'record does not exist': 'înregistrare inexistentă', 'Record ID': 'ID înregistrare', 'Record id': 'id înregistrare', 'register': 'înregistrare', 'Register': 'Înregistrare', 'Registration identifier': 'Identificator de autentificare', 'Registration key': 'Cheie înregistrare', 'Registration successful': 'Autentificare reușită', 'Remember me (for 30 days)': 'Ține-mă minte (timp de 30 de zile)', 'remove compiled': 'șterge compilate', 'Request reset password': 'Cerere resetare parolă', 'Reset Password key': 'Cheie restare parolă', 'Resolve Conflict file': 'Fișier rezolvare conflict', 'restore': 'restaurare', 'revert': 'revenire', 'Role': 'Rol', 'Rows in Table': 'Linii în tabel', 'Rows selected': 'Linii selectate', 'save': 'salvare', 'Save profile': 'Salvează profil', 'Saved file hash:': 'Hash fișier salvat:', 'Search': 'Căutare', 'Semantic': 'Semantică', 'Services': 'Servicii', 'session expired': 'sesiune expirată', 'shell': 'line de commandă', 'site': 'site', 'Size of cache:': 'Size of cache:', 'some files could not be removed': 'anumite fișiere n-au putut fi șterse', 'starts with': 'începe cu', 'state': 'stare', 'static': 'static', 'Static files': 'Fișiere statice', 'Statistics': 'Statistics', 'Stylesheet': 'Foaie de stiluri', 'Submit': 'Înregistrează', 'submit': 'submit', 'Support': 'Suport', 'Sure you want to delete this object?': 'Sigur ștergeți acest obiect?', 'Table': 'tabel', 'Table name': 'Nume tabel', 'test': 'test', 'Testing application': 'Testare aplicație', 'The "query" is a condition like "db.table1.field1==\'value\'". Something like "db.table1.field1==db.table2.field2" results in a SQL JOIN.': '"Interogarea (query)" este o condiție de tipul "db.tabel1.câmp1==\'valoare\'". Ceva de genul "db.tabel1.câmp1==db.tabel2.câmp2" generează un JOIN SQL.', 'the application logic, each URL path is mapped in one exposed function in the controller': 'logica aplicației, fiecare rută URL este mapată într-o funcție expusă de controlor', 'The Core': 'Nucleul', 'the data representation, define database tables and sets': 'reprezentarea datelor, definește tabelele bazei de date și seturile (de date)', 'The output of the file is a dictionary that was rendered by the view %s': 'Fișierul produce un dicționar care a fost prelucrat de vederea %s', 'the presentations layer, views are also known as templates': 'nivelul de prezentare, vederile sunt de asemenea numite și șabloane', 'The Views': 'Vederile', 'There are no controllers': 'Nu există controlori', 'There are no models': 'Nu există modele', 'There are no modules': 'Nu există module', 'There are no static files': 'Nu există fișiere statice', 'There are no translators, only default language is supported': 'Nu există traduceri, doar limba implicită este suportată', 'There are no views': 'Nu există vederi', 'these files are served without processing, your images go here': 'aceste fișiere sunt servite fără procesare, imaginea se plasează acolo', 'This App': 'Această aplicație', 'This is a copy of the scaffolding application': 'Aceasta este o copie a aplicației schelet', 'This is the %(filename)s template': 'Aceasta este șablonul fișierului %(filename)s', 'Ticket': 'Tichet', 'Time in Cache (h:m:s)': 'Time in Cache (h:m:s)', 'Timestamp': 'Moment în timp (timestamp)', 'to previous version.': 'la versiunea anterioară.', 'too short': 'prea scurt', 'translation strings for the application': 'șiruri de caractere folosite la traducerea aplicației', 'True': 'Adevărat', 'try': 'încearcă', 'try something like': 'încearcă ceva de genul', 'Twitter': 'Twitter', 'Unable to check for upgrades': 'Imposibil de verificat dacă există actualizări', 'unable to create application "%s"': 'imposibil de creat aplicația "%s"', 'unable to delete file "%(filename)s"': 'imposibil de șters fișierul "%(filename)s"', 'Unable to download': 'Imposibil de descărcat', 'Unable to download app': 'Imposibil de descărcat aplicația', 'unable to parse csv file': 'imposibil de analizat fișierul csv', 'unable to uninstall "%s"': 'imposibil de dezinstalat "%s"', 'uncheck all': 'decoșează tot', 'uninstall': 'dezinstalează', 'update': 'actualizează', 'update all languages': 'actualizează toate limbile', 'Update:': 'Actualizare:', 'upload application:': 'incarcă aplicația:', 'Upload existing application': 'Încarcă aplicația existentă', 'upload file:': 'încarcă fișier:', 'Use (...)&(...) for AND, (...)|(...) for OR, and ~(...) for NOT to build more complex queries.': 'Folosiți (...)&(...) pentru AND, (...)|(...) pentru OR, și ~(...) pentru NOT, pentru a crea interogări complexe.', 'User %(id)s Logged-in': 'Utilizator %(id)s autentificat', 'User %(id)s Logged-out': 'Utilizator %(id)s delogat', 'User %(id)s Password changed': 'Parola utilizatorului %(id)s a fost schimbată', 'User %(id)s Password reset': 'Resetare parola utilizator %(id)s', 'User %(id)s Profile updated': 'Profil utilizator %(id)s actualizat', 'User %(id)s Registered': 'Utilizator %(id)s înregistrat', 'User ID': 'ID utilizator', 'value already in database or empty': 'Valoare existentă în baza de date sau vidă', 'Verify Password': 'Verifică parola', 'versioning': 'versiuni', 'Videos': 'Video-uri', 'View': 'Vedere', 'view': 'vedere', 'Views': 'Vederi', 'views': 'vederi', 'web2py is up to date': 'web2py este la zi', 'web2py Recent Tweets': 'Ultimele tweet-uri web2py', 'Welcome': 'Bine ați venit', 'Welcome %s': 'Bine ați venit %s', 'Welcome to web2py': 'Bun venit la web2py', 'Welcome to web2py!': 'Bun venit la web2py!', 'Which called the function %s located in the file %s': 'Care a apelat funcția %s prezentă în fișierul %s', 'YES': 'DA', 'You are successfully running web2py': 'Rulați cu succes web2py', 'You can modify this application and adapt it to your needs': 'Puteți modifica și adapta aplicația nevoilor dvs.', 'You visited the url %s': 'Ați vizitat adresa %s', }
Python
# coding: utf8 { '!langcode!': 'id', '!langname!': 'Indonesian', '%d days ago': '%d hari yang lalu', '%d hours ago': '%d jam yang lalu', '%d minutes ago': '%d menit yang lalu', '%d months ago': '%d bulan yang lalu', '%d seconds ago': '%d detik yang lalu', '%d seconds from now': '%d detik dari sekarang', '%d weeks ago': '%d minggu yang lalu', '%d years ago': '%d tahun yang lalu', '%s %%{row} deleted': '%s %%{row} dihapus', '%s %%{row} updated': '%s %%{row} diperbarui', '%s selected': '%s dipilih', '%Y-%m-%d': '%d-%m-%Y', '%Y-%m-%d %H:%M:%S': '%d-%m-%Y %H:%M:%S', '(requires internet access, experimental)': '(membutuhkan akses internet, eksperimental)', '(something like "it-it")': '(sesuatu seperti "it-it")', '1 day ago': '1 hari yang lalu', '1 hour ago': '1 jam yang lalu', '1 minute ago': '1 menit yang lalu', '1 month ago': '1 bulan yang lalu', '1 second ago': '1 detik yang lalu', '1 week ago': '1 minggu yang lalu', '1 year ago': '1 tahun yang lalu', '< Previous': '< Sebelumnya', 'About': 'Tentang', 'About application': 'Tentang Aplikasi', 'Add': 'Tambah', 'Additional code for your application': 'Tambahan kode untuk aplikasi Anda', 'Address': 'Alamat', 'Admin language': 'Bahasa Admin', 'administrative interface': 'antarmuka administrative', 'Administrator Password:': 'Administrator Kata Sandi:', 'Ajax Recipes': 'Resep Ajax', 'An error occured, please %s the page': 'Terjadi kesalahan, silakan %s halaman', 'And': 'Dan', 'and rename it:': 'dan memberi nama baru itu:', 'Answer': 'Jawaban', 'appadmin is disabled because insecure channel': 'AppAdmin dinonaktifkan karena kanal tidak aman', 'application "%s" uninstalled': 'applikasi "%s" dihapus', 'application compiled': 'aplikasi dikompilasi', 'Application name:': 'Nama Applikasi:', 'are not used yet': 'tidak digunakan lagi', 'Are you sure you want to delete this object?': 'Apakah Anda yakin ingin menghapus ini?', 'Are you sure you want to uninstall application "%s"?': 'Apakah Anda yakin ingin menghapus aplikasi "%s"?', 'Available Databases and Tables': 'Database dan Tabel yang tersedia', 'Back': 'Kembali', 'Buy this book': 'Beli buku ini', 'cache, errors and sessions cleaned': 'cache, kesalahan dan sesi dibersihkan', 'can be a git repo': 'bisa menjadi repo git', 'Cancel': 'Batalkan', 'Cannot be empty': 'Tidak boleh kosong', 'Change admin password': 'Ubah kata sandi admin', 'Change password': 'Ubah kata sandi', 'Check for upgrades': 'Periksa upgrade', 'Check to delete': 'Centang untuk menghapus', 'Checking for upgrades...': 'Memeriksa untuk upgrade...', 'Clean': 'Bersih', 'Clear': 'Hapus', 'Clear CACHE?': 'Hapus CACHE?', 'Clear DISK': 'Hapus DISK', 'Clear RAM': 'Hapus RAM', 'Click row to expand traceback': 'Klik baris untuk memperluas traceback', 'Close': 'Tutup', 'collapse/expand all': 'kempis / memperluas semua', 'Community': 'Komunitas', 'Compile': 'Kompilasi', 'compiled application removed': 'aplikasi yang dikompilasi dihapus', 'Components and Plugins': 'Komponen dan Plugin', 'contains': 'mengandung', 'Controllers': 'Kontrolir', 'controllers': 'kontrolir', 'Copyright': 'Hak Cipta', 'Count': 'Hitung', 'Create': 'Buat', 'create file with filename:': 'buat file dengan nama:', 'created by': 'dibuat oleh', 'CSV (hidden cols)': 'CSV (kolom tersembunyi)', 'currently running': 'sedang berjalan', 'data uploaded': 'data diunggah', 'Database %s select': 'Memilih Database %s', 'database administration': 'administrasi database', 'defines tables': 'mendefinisikan tabel', 'Delete': 'Hapus', 'delete all checked': 'menghapus semua yang di centang', 'Delete this file (you will be asked to confirm deletion)': 'Hapus file ini (Anda akan diminta untuk mengkonfirmasi penghapusan)', 'Delete:': 'Hapus:', 'Description': 'Keterangan', 'design': 'disain', 'direction: ltr': 'petunjuk: ltr', 'Disk Cleared': 'Disk Dihapus', 'Documentation': 'Dokumentasi', "Don't know what to do?": 'Tidak tahu apa yang harus dilakukan?', 'done!': 'selesai!', 'Download': 'Unduh', 'Download .w2p': 'Unduh .w2p', 'download layouts': 'unduh layouts', 'download plugins': 'unduh plugins', 'Duration': 'Durasi', 'Edit': 'Mengedit', 'Edit application': 'Mengedit Aplikasi', 'Email sent': 'Email dikirim', 'enter a valid email address': 'masukkan alamat email yang benar', 'enter a valid URL': 'masukkan URL yang benar', 'enter a value': 'masukkan data', 'Error': 'Kesalahan', 'Error logs for "%(app)s"': 'Catatan kesalahan untuk "%(app)s"', 'Errors': 'Kesalahan', 'export as csv file': 'ekspor sebagai file csv', 'Export:': 'Ekspor:', 'exposes': 'menghadapkan', 'extends': 'meluaskan', 'filter': 'menyaring', 'First Name': 'Nama Depan', 'Forgot username?': 'Lupa nama pengguna?', 'Free Applications': 'Aplikasi Gratis', 'Gender': 'Jenis Kelamin', 'Group %(group_id)s created': 'Grup %(group_id)s dibuat', 'Group uniquely assigned to user %(id)s': 'Grup unik yang diberikan kepada pengguna %(id)s', 'Groups': 'Grup', 'Guest': 'Tamu', 'Hello World': 'Halo Dunia', 'Help': 'Bantuan', 'Home': 'Halaman Utama', 'How did you get here?': 'Bagaimana kamu bisa di sini?', 'Image': 'Gambar', 'import': 'impor', 'Import/Export': 'Impor/Ekspor', 'includes': 'termasuk', 'Install': 'Memasang', 'Installation': 'Instalasi', 'Installed applications': 'Aplikasi yang diinstal', 'Introduction': 'Pengenalan', 'Invalid email': 'Email tidak benar', 'Language': 'Bahasa', 'languages': 'bahasa', 'Languages': 'Bahasa', 'Last Name': 'Nama Belakang', 'License for': 'Lisensi untuk', 'loading...': 'sedang memuat...', 'Logged in': 'Masuk', 'Logged out': 'Keluar', 'Login': 'Masuk', 'Login to the Administrative Interface': 'Masuk ke antarmuka Administrasi', 'Logout': 'Keluar', 'Lost Password': 'Lupa Kata Sandi', 'Lost password?': 'Lupa kata sandi?', 'Maintenance': 'Pemeliharaan', 'Manage': 'Mengelola', 'Manage Cache': 'Mengelola Cache', 'models': 'model', 'Models': 'Model', 'Modules': 'Modul', 'modules': 'modul', 'My Sites': 'Situs Saya', 'New': 'Baru', 'new application "%s" created': 'aplikasi baru "%s" dibuat', 'New password': 'Kata sandi baru', 'New simple application': 'Aplikasi baru sederhana', 'News': 'Berita', 'next 100 rows': '100 baris berikutnya', 'Next >': 'Berikutnya >', 'Next Page': 'Halaman Berikutnya', 'No databases in this application': 'Tidak ada database dalam aplikasi ini', 'No ticket_storage.txt found under /private folder': 'Tidak ditemukan ticket_storage.txt dalam folder /private', 'not a Zip Code': 'bukan Kode Pos', 'Note': 'Catatan', 'Old password': 'Kata sandi lama', 'Online examples': 'Contoh Online', 'Or': 'Atau', 'or alternatively': 'atau alternatif', 'Or Get from URL:': 'Atau Dapatkan dari URL:', 'or import from csv file': 'atau impor dari file csv', 'Other Plugins': 'Plugin Lainnya', 'Other Recipes': 'Resep Lainnya', 'Overview': 'Ikhtisar', 'Overwrite installed app': 'Ikhtisar app yang terinstall', 'Pack all': 'Pak semua', 'Pack compiled': 'Pak yang telah dikompilasi', 'Pack custom': 'Pak secara kustomisasi', 'Password': 'Kata sandi', 'Password changed': 'Kata sandi berubah', "Password fields don't match": 'Kata sandi tidak sama', 'please input your password again': 'silahkan masukan kata sandi anda lagi', 'plugins': 'plugin', 'Plugins': 'Plugin', 'Plural-Forms:': 'Bentuk-Jamak:', 'Powered by': 'Didukung oleh', 'Preface': 'Pendahuluan', 'previous 100 rows': '100 baris sebelumnya', 'Previous Page': 'Halaman Sebelumnya', 'private files': 'file pribadi', 'Private files': 'File pribadi', 'Profile': 'Profil', 'Profile updated': 'Profil diperbarui', 'Project Progress': 'Perkembangan Proyek', 'Quick Examples': 'Contoh Cepat', 'Ram Cleared': 'Ram Dihapus', 'Recipes': 'Resep', 'Register': 'Daftar', 'Registration successful': 'Pendaftaran berhasil', 'reload': 'memuat kembali', 'Reload routes': 'Memuat rute kembali', 'Remember me (for 30 days)': 'Ingat saya (selama 30 hari)', 'Remove compiled': 'Hapus Kompilasi', 'Request reset password': 'Meminta reset kata sandi', 'Rows in Table': 'Baris dalam Tabel', 'Rows selected': 'Baris dipilih', "Run tests in this file (to run all files, you may also use the button labelled 'test')": "Jalankan tes di file ini (untuk menjalankan semua file, Anda juga dapat menggunakan tombol berlabel 'test')", 'Running on %s': 'Berjalan di %s', 'Save model as...': 'Simpan model sebagai ...', 'Save profile': 'Simpan profil', 'Search': 'Cari', 'Select Files to Package': 'Pilih Berkas untuk Paket', 'Send Email': 'Kirim Email', 'Service': 'Layanan', 'Site': 'Situs', 'Size of cache:': 'Ukuran cache:', 'starts with': 'dimulai dengan', 'static': 'statis', 'Static': 'Statis', 'Statistics': 'Statistik', 'Support': 'Mendukung', 'Table': 'Tabel', 'test': 'tes', 'The application logic, each URL path is mapped in one exposed function in the controller': 'Logika aplikasi, setiap jalur URL dipetakan dalam satu fungsi terpapar di kontrolir', 'The data representation, define database tables and sets': 'Representasi data, mendefinisikan tabel database dan set', 'There are no plugins': 'Tidak ada plugin', 'There are no private files': 'Tidak ada file pribadi', 'These files are not served, they are only available from within your app': 'File-file ini tidak dilayani, mereka hanya tersedia dari dalam aplikasi Anda', 'These files are served without processing, your images go here': 'File-file ini disajikan tanpa pengolahan, gambar Anda di sini', 'This App': 'App Ini', 'Time in Cache (h:m:s)': 'Waktu di Cache (h: m: s)', 'To create a plugin, name a file/folder plugin_[name]': 'Untuk membuat sebuah plugin, nama file / folder plugin_ [nama]', 'too short': 'terlalu pendek', 'Translation strings for the application': 'Terjemahan string untuk aplikasi', 'Try the mobile interface': 'Coba antarmuka ponsel', 'Unable to download because:': 'Tidak dapat mengunduh karena:', 'unable to parse csv file': 'tidak mampu mengurai file csv', 'update all languages': 'memperbarui semua bahasa', 'Update:': 'Perbarui:', 'Upload': 'Unggah', 'Upload a package:': 'Unggah sebuah paket:', 'Upload and install packed application': 'Upload dan pasang aplikasi yang dikemas', 'upload file:': 'unggah file:', 'upload plugin file:': 'unggah file plugin:', 'User %(id)s Logged-in': 'Pengguna %(id)s Masuk', 'User %(id)s Logged-out': 'Pengguna %(id)s Keluar', 'User %(id)s Password changed': 'Pengguna %(id)s Kata Sandi berubah', 'User %(id)s Password reset': 'Pengguna %(id)s Kata Sandi telah direset', 'User %(id)s Profile updated': 'Pengguna %(id)s Profil diperbarui', 'User %(id)s Registered': 'Pengguna %(id)s Terdaftar', 'value already in database or empty': 'data sudah ada dalam database atau kosong', 'value not allowed': 'data tidak benar', 'value not in database': 'data tidak ada dalam database', 'Verify Password': 'Verifikasi Kata Sandi', 'Version': 'Versi', 'View': 'Lihat', 'Views': 'Lihat', 'views': 'lihat', 'Web Framework': 'Kerangka Web', 'web2py is up to date': 'web2py terbaru', 'web2py Recent Tweets': 'Tweet web2py terbaru', 'Website': 'Situs Web', 'Welcome': 'Selamat Datang', 'Welcome to web2py!': 'Selamat Datang di web2py!', 'You are successfully running web2py': 'Anda berhasil menjalankan web2py', 'You can modify this application and adapt it to your needs': 'Anda dapat memodifikasi aplikasi ini dan menyesuaikan dengan kebutuhan Anda', 'You visited the url %s': 'Anda mengunjungi url %s', }
Python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A(B('web',SPAN(2),'py'),XML('&trade;&nbsp;'), _class="brand",_href="http://www.web2py.com/") response.title = request.application.replace('_',' ').title() response.subtitle = T('customize me!') ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Your Name <you@example.com>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### response.menu = [ (T('Home'), False, URL('default', 'index'), []) ] DEVELOPMENT_MENU = True ######################################################################### ## provide shortcuts for development. remove in production ######################################################################### def _(): # shortcuts app = request.application ctr = request.controller # useful links to internal and external resources response.menu += [ (SPAN('web2py', _class='highlighted'), False, 'http://web2py.com', [ (T('My Sites'), False, URL('admin', 'default', 'site')), (T('This App'), False, URL('admin', 'default', 'design/%s' % app), [ (T('Controller'), False, URL( 'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (T('View'), False, URL( 'admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (T('Layout'), False, URL( 'admin', 'default', 'edit/%s/views/layout.html' % app)), (T('Stylesheet'), False, URL( 'admin', 'default', 'edit/%s/static/css/web2py.css' % app)), (T('DB Model'), False, URL( 'admin', 'default', 'edit/%s/models/db.py' % app)), (T('Menu Model'), False, URL( 'admin', 'default', 'edit/%s/models/menu.py' % app)), (T('Database'), False, URL(app, 'appadmin', 'index')), (T('Errors'), False, URL( 'admin', 'default', 'errors/' + app)), (T('About'), False, URL( 'admin', 'default', 'about/' + app)), ]), ('web2py.com', False, 'http://www.web2py.com', [ (T('Download'), False, 'http://www.web2py.com/examples/default/download'), (T('Support'), False, 'http://www.web2py.com/examples/default/support'), (T('Demo'), False, 'http://web2py.com/demo_admin'), (T('Quick Examples'), False, 'http://web2py.com/examples/default/examples'), (T('FAQ'), False, 'http://web2py.com/AlterEgo'), (T('Videos'), False, 'http://www.web2py.com/examples/default/videos/'), (T('Free Applications'), False, 'http://web2py.com/appliances'), (T('Plugins'), False, 'http://web2py.com/plugins'), (T('Layouts'), False, 'http://web2py.com/layouts'), (T('Recipes'), False, 'http://web2pyslices.com/'), (T('Semantic'), False, 'http://web2py.com/semantic'), ]), (T('Documentation'), False, 'http://www.web2py.com/book', [ (T('Preface'), False, 'http://www.web2py.com/book/default/chapter/00'), (T('Introduction'), False, 'http://www.web2py.com/book/default/chapter/01'), (T('Python'), False, 'http://www.web2py.com/book/default/chapter/02'), (T('Overview'), False, 'http://www.web2py.com/book/default/chapter/03'), (T('The Core'), False, 'http://www.web2py.com/book/default/chapter/04'), (T('The Views'), False, 'http://www.web2py.com/book/default/chapter/05'), (T('Database'), False, 'http://www.web2py.com/book/default/chapter/06'), (T('Forms and Validators'), False, 'http://www.web2py.com/book/default/chapter/07'), (T('Email and SMS'), False, 'http://www.web2py.com/book/default/chapter/08'), (T('Access Control'), False, 'http://www.web2py.com/book/default/chapter/09'), (T('Services'), False, 'http://www.web2py.com/book/default/chapter/10'), (T('Ajax Recipes'), False, 'http://www.web2py.com/book/default/chapter/11'), (T('Components and Plugins'), False, 'http://www.web2py.com/book/default/chapter/12'), (T('Deployment Recipes'), False, 'http://www.web2py.com/book/default/chapter/13'), (T('Other Recipes'), False, 'http://www.web2py.com/book/default/chapter/14'), (T('Buy this book'), False, 'http://stores.lulu.com/web2py'), ]), (T('Community'), False, None, [ (T('Groups'), False, 'http://www.web2py.com/examples/default/usergroups'), (T('Twitter'), False, 'http://twitter.com/web2py'), (T('Live Chat'), False, 'http://webchat.freenode.net/?channels=web2py'), ]), (T('Plugins'), False, None, [ ('plugin_wiki', False, 'http://web2py.com/examples/default/download'), (T('Other Plugins'), False, 'http://web2py.com/plugins'), (T('Layout Plugins'), False, 'http://web2py.com/layouts'), ]) ] )] if DEVELOPMENT_MENU: _() if "auth" in locals(): auth.wikimenu()
Python
# -*- coding: utf-8 -*- ######################################################################### ## This scaffolding model makes your app work on Google App Engine too ## File is released under public domain and you can use without limitations ######################################################################### ## if SSL/HTTPS is properly configured and you want all HTTP requests to ## be redirected to HTTPS, uncomment the line below: # request.requires_https() if not request.env.web2py_runtime_gae: ## if NOT running on Google App Engine use SQLite or other DB db = DAL('sqlite://storage.sqlite',pool_size=1,check_reserved=['all']) else: ## connect to Google BigTable (optional 'google:datastore://namespace') db = DAL('google:datastore') ## store sessions and tickets there session.connect(request, response, db=db) ## or store session in Memcache, Redis, etc. ## from gluon.contrib.memdb import MEMDB ## from google.appengine.api.memcache import Client ## session.connect(request, response, db = MEMDB(Client())) ## by default give a view/generic.extension to all actions from localhost ## none otherwise. a pattern can be 'controller/function.extension' response.generic_patterns = ['*'] if request.is_local else [] ## (optional) optimize handling of static files # response.optimize_css = 'concat,minify,inline' # response.optimize_js = 'concat,minify,inline' ######################################################################### ## Here is sample code if you need for ## - email capabilities ## - authentication (registration, login, logout, ... ) ## - authorization (role based authorization) ## - services (xml, csv, json, xmlrpc, jsonrpc, amf, rss) ## - old style crud actions ## (more options discussed in gluon/tools.py) ######################################################################### from gluon.tools import Auth, Crud, Service, PluginManager, prettydate auth = Auth(db) crud, service, plugins = Crud(db), Service(), PluginManager() ## create all tables needed by auth if not custom tables auth.define_tables(username=False, signature=False) ## configure email mail = auth.settings.mailer mail.settings.server = 'logging' or 'smtp.gmail.com:587' mail.settings.sender = 'you@gmail.com' mail.settings.login = 'username:password' ## configure auth policy auth.settings.registration_requires_verification = False auth.settings.registration_requires_approval = False auth.settings.reset_password_requires_verification = True ## if you need to use OpenID, Facebook, MySpace, Twitter, Linkedin, etc. ## register with janrain.com, write your domain:api_key in private/janrain.key from gluon.contrib.login_methods.rpx_account import use_janrain use_janrain(auth, filename='private/janrain.key') ######################################################################### ## Define your tables below (or better in another model file) for example ## ## >>> db.define_table('mytable',Field('myfield','string')) ## ## Fields can be 'string','text','password','integer','double','boolean' ## 'date','time','datetime','blob','upload', 'reference TABLENAME' ## There is an implicit 'id integer autoincrement' field ## Consult manual for more options, validators, etc. ## ## More API examples for controllers: ## ## >>> db.mytable.insert(myfield='value') ## >>> rows=db(db.mytable.myfield=='value').select(db.mytable.ALL) ## >>> for row in rows: print row.id, row.myfield ######################################################################### ## after defining tables, uncomment below to enable auditing # auth.enable_record_versioning(db)
Python
# -*- coding: utf-8 -*- # ########################################################## # ## make sure administrator is on localhost # ########################################################### import os import socket import datetime import copy import gluon.contenttype import gluon.fileutils try: import pygraphviz as pgv except ImportError: pgv = None response.subtitle = 'Database Administration (appadmin)' # ## critical --- make a copy of the environment global_env = copy.copy(globals()) global_env['datetime'] = datetime http_host = request.env.http_host.split(':')[0] remote_addr = request.env.remote_addr try: hosts = (http_host, socket.gethostname(), socket.gethostbyname(http_host), '::1', '127.0.0.1', '::ffff:127.0.0.1') except: hosts = (http_host, ) if request.env.http_x_forwarded_for or request.is_https: session.secure() elif (remote_addr not in hosts) and (remote_addr != "127.0.0.1"): raise HTTP(200, T('appadmin is disabled because insecure channel')) if (request.application == 'admin' and not session.authorized) or \ (request.application != 'admin' and not gluon.fileutils.check_credentials(request)): redirect(URL('admin', 'default', 'index', vars=dict(send=URL(args=request.args, vars=request.vars)))) ignore_rw = True response.view = 'appadmin.html' response.menu = [[T('design'), False, URL('admin', 'default', 'design', args=[request.application])], [T('db'), False, URL('index')], [T('state'), False, URL('state')], [T('cache'), False, URL('ccache')]] # ########################################################## # ## auxiliary functions # ########################################################### if False and request.tickets_db: from gluon.restricted import TicketStorage ts = TicketStorage() ts._get_table(request.tickets_db, ts.tablename, request.application) def get_databases(request): dbs = {} for (key, value) in global_env.items(): cond = False try: cond = isinstance(value, GQLDB) except: cond = isinstance(value, SQLDB) if cond: dbs[key] = value return dbs databases = get_databases(None) def eval_in_global_env(text): exec ('_ret=%s' % text, {}, global_env) return global_env['_ret'] def get_database(request): if request.args and request.args[0] in databases: return eval_in_global_env(request.args[0]) else: session.flash = T('invalid request') redirect(URL('index')) def get_table(request): db = get_database(request) if len(request.args) > 1 and request.args[1] in db.tables: return (db, request.args[1]) else: session.flash = T('invalid request') redirect(URL('index')) def get_query(request): try: return eval_in_global_env(request.vars.query) except Exception: return None def query_by_table_type(tablename, db, request=request): keyed = hasattr(db[tablename], '_primarykey') if keyed: firstkey = db[tablename][db[tablename]._primarykey[0]] cond = '>0' if firstkey.type in ['string', 'text']: cond = '!=""' qry = '%s.%s.%s%s' % ( request.args[0], request.args[1], firstkey.name, cond) else: qry = '%s.%s.id>0' % tuple(request.args[:2]) return qry # ########################################################## # ## list all databases and tables # ########################################################### def index(): return dict(databases=databases) # ########################################################## # ## insert a new record # ########################################################### def insert(): (db, table) = get_table(request) form = SQLFORM(db[table], ignore_rw=ignore_rw) if form.accepts(request.vars, session): response.flash = T('new record inserted') return dict(form=form, table=db[table]) # ########################################################## # ## list all records in table and insert new record # ########################################################### def download(): import os db = get_database(request) return response.download(request, db) def csv(): import gluon.contenttype response.headers['Content-Type'] = \ gluon.contenttype.contenttype('.csv') db = get_database(request) query = get_query(request) if not query: return None response.headers['Content-disposition'] = 'attachment; filename=%s_%s.csv'\ % tuple(request.vars.query.split('.')[:2]) return str(db(query, ignore_common_filters=True).select()) def import_csv(table, file): table.import_from_csv_file(file) def select(): import re db = get_database(request) dbname = request.args[0] regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>\d+)') if len(request.args) > 1 and hasattr(db[request.args[1]], '_primarykey'): regex = re.compile('(?P<table>\w+)\.(?P<field>\w+)=(?P<value>.+)') if request.vars.query: match = regex.match(request.vars.query) if match: request.vars.query = '%s.%s.%s==%s' % (request.args[0], match.group('table'), match.group('field'), match.group('value')) else: request.vars.query = session.last_query query = get_query(request) if request.vars.start: start = int(request.vars.start) else: start = 0 nrows = 0 stop = start + 100 table = None rows = [] orderby = request.vars.orderby if orderby: orderby = dbname + '.' + orderby if orderby == session.last_orderby: if orderby[0] == '~': orderby = orderby[1:] else: orderby = '~' + orderby session.last_orderby = orderby session.last_query = request.vars.query form = FORM(TABLE(TR(T('Query:'), '', INPUT(_style='width:400px', _name='query', _value=request.vars.query or '', requires=IS_NOT_EMPTY( error_message=T("Cannot be empty")))), TR(T('Update:'), INPUT(_name='update_check', _type='checkbox', value=False), INPUT(_style='width:400px', _name='update_fields', _value=request.vars.update_fields or '')), TR(T('Delete:'), INPUT(_name='delete_check', _class='delete', _type='checkbox', value=False), ''), TR('', '', INPUT(_type='submit', _value=T('submit')))), _action=URL(r=request, args=request.args)) tb = None if form.accepts(request.vars, formname=None): regex = re.compile(request.args[0] + '\.(?P<table>\w+)\..+') match = regex.match(form.vars.query.strip()) if match: table = match.group('table') try: nrows = db(query).count() if form.vars.update_check and form.vars.update_fields: db(query).update(**eval_in_global_env('dict(%s)' % form.vars.update_fields)) response.flash = T('%s %%{row} updated', nrows) elif form.vars.delete_check: db(query).delete() response.flash = T('%s %%{row} deleted', nrows) nrows = db(query).count() if orderby: rows = db(query, ignore_common_filters=True).select(limitby=( start, stop), orderby=eval_in_global_env(orderby)) else: rows = db(query, ignore_common_filters=True).select( limitby=(start, stop)) except Exception, e: import traceback tb = traceback.format_exc() (rows, nrows) = ([], 0) response.flash = DIV(T('Invalid Query'), PRE(str(e))) # begin handle upload csv csv_table = table or request.vars.table if csv_table: formcsv = FORM(str(T('or import from csv file')) + " ", INPUT(_type='file', _name='csvfile'), INPUT(_type='hidden', _value=csv_table, _name='table'), INPUT(_type='submit', _value=T('import'))) else: formcsv = None if formcsv and formcsv.process().accepted: try: import_csv(db[request.vars.table], request.vars.csvfile.file) response.flash = T('data uploaded') except Exception, e: response.flash = DIV(T('unable to parse csv file'), PRE(str(e))) # end handle upload csv return dict( form=form, table=table, start=start, stop=stop, nrows=nrows, rows=rows, query=request.vars.query, formcsv=formcsv, tb=tb, ) # ########################################################## # ## edit delete one record # ########################################################### def update(): (db, table) = get_table(request) keyed = hasattr(db[table], '_primarykey') record = None db[table]._common_filter = None if keyed: key = [f for f in request.vars if f in db[table]._primarykey] if key: record = db(db[table][key[0]] == request.vars[key[ 0]]).select().first() else: record = db(db[table].id == request.args( 2)).select().first() if not record: qry = query_by_table_type(table, db) session.flash = T('record does not exist') redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) if keyed: for k in db[table]._primarykey: db[table][k].writable = False form = SQLFORM( db[table], record, deletable=True, delete_label=T('Check to delete'), ignore_rw=ignore_rw and not keyed, linkto=URL('select', args=request.args[:1]), upload=URL(r=request, f='download', args=request.args[:1])) if form.accepts(request.vars, session): session.flash = T('done!') qry = query_by_table_type(table, db) redirect(URL('select', args=request.args[:1], vars=dict(query=qry))) return dict(form=form, table=db[table]) # ########################################################## # ## get global variables # ########################################################### def state(): return dict() def ccache(): cache.ram.initialize() cache.disk.initialize() form = FORM( P(TAG.BUTTON( T("Clear CACHE?"), _type="submit", _name="yes", _value="yes")), P(TAG.BUTTON( T("Clear RAM"), _type="submit", _name="ram", _value="ram")), P(TAG.BUTTON( T("Clear DISK"), _type="submit", _name="disk", _value="disk")), ) if form.accepts(request.vars, session): clear_ram = False clear_disk = False session.flash = "" if request.vars.yes: clear_ram = clear_disk = True if request.vars.ram: clear_ram = True if request.vars.disk: clear_disk = True if clear_ram: cache.ram.clear() session.flash += T("Ram Cleared") if clear_disk: cache.disk.clear() session.flash += T("Disk Cleared") redirect(URL(r=request)) try: from guppy import hpy hp = hpy() except ImportError: hp = False import shelve import os import copy import time import math from gluon import portalocker ram = { 'entries': 0, 'bytes': 0, 'objects': 0, 'hits': 0, 'misses': 0, 'ratio': 0, 'oldest': time.time(), 'keys': [] } disk = copy.copy(ram) total = copy.copy(ram) disk['keys'] = [] total['keys'] = [] def GetInHMS(seconds): hours = math.floor(seconds / 3600) seconds -= hours * 3600 minutes = math.floor(seconds / 60) seconds -= minutes * 60 seconds = math.floor(seconds) return (hours, minutes, seconds) for key, value in cache.ram.storage.iteritems(): if isinstance(value, dict): ram['hits'] = value['hit_total'] - value['misses'] ram['misses'] = value['misses'] try: ram['ratio'] = ram['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): ram['ratio'] = 0 else: if hp: ram['bytes'] += hp.iso(value[1]).size ram['objects'] += hp.iso(value[1]).count ram['entries'] += 1 if value[0] < ram['oldest']: ram['oldest'] = value[0] ram['keys'].append((key, GetInHMS(time.time() - value[0]))) folder = os.path.join(request.folder,'cache') if not os.path.exists(folder): os.mkdir(folder) locker = open(os.path.join(folder, 'cache.lock'), 'a') portalocker.lock(locker, portalocker.LOCK_EX) disk_storage = shelve.open( os.path.join(folder, 'cache.shelve')) try: for key, value in disk_storage.items(): if isinstance(value, dict): disk['hits'] = value['hit_total'] - value['misses'] disk['misses'] = value['misses'] try: disk['ratio'] = disk['hits'] * 100 / value['hit_total'] except (KeyError, ZeroDivisionError): disk['ratio'] = 0 else: if hp: disk['bytes'] += hp.iso(value[1]).size disk['objects'] += hp.iso(value[1]).count disk['entries'] += 1 if value[0] < disk['oldest']: disk['oldest'] = value[0] disk['keys'].append((key, GetInHMS(time.time() - value[0]))) finally: portalocker.unlock(locker) locker.close() disk_storage.close() total['entries'] = ram['entries'] + disk['entries'] total['bytes'] = ram['bytes'] + disk['bytes'] total['objects'] = ram['objects'] + disk['objects'] total['hits'] = ram['hits'] + disk['hits'] total['misses'] = ram['misses'] + disk['misses'] total['keys'] = ram['keys'] + disk['keys'] try: total['ratio'] = total['hits'] * 100 / (total['hits'] + total['misses']) except (KeyError, ZeroDivisionError): total['ratio'] = 0 if disk['oldest'] < ram['oldest']: total['oldest'] = disk['oldest'] else: total['oldest'] = ram['oldest'] ram['oldest'] = GetInHMS(time.time() - ram['oldest']) disk['oldest'] = GetInHMS(time.time() - disk['oldest']) total['oldest'] = GetInHMS(time.time() - total['oldest']) def key_table(keys): return TABLE( TR(TD(B(T('Key'))), TD(B(T('Time in Cache (h:m:s)')))), *[TR(TD(k[0]), TD('%02d:%02d:%02d' % k[1])) for k in keys], **dict(_class='cache-keys', _style="border-collapse: separate; border-spacing: .5em;")) ram['keys'] = key_table(ram['keys']) disk['keys'] = key_table(disk['keys']) total['keys'] = key_table(total['keys']) return dict(form=form, total=total, ram=ram, disk=disk, object_stats=hp != False) def table_template(table): from gluon.html import TR, TD, TABLE, TAG def FONT(*args, **kwargs): return TAG.font(*args, **kwargs) def types(field): f_type = field.type if not isinstance(f_type,str): return ' ' elif f_type == 'string': return field.length elif f_type == 'id': return B('pk') elif f_type.startswith('reference') or \ f_type.startswith('list:reference'): return B('fk') else: return ' ' # This is horribe HTML but the only one graphiz understands rows = [] cellpadding = 4 color = "#000000" bgcolor = "#FFFFFF" face = "Helvetica" face_bold = "Helvetica Bold" border = 0 rows.append(TR(TD(FONT(table, _face=face_bold, _color=bgcolor), _colspan=3, _cellpadding=cellpadding, _align="center", _bgcolor=color))) for row in db[table]: rows.append(TR(TD(FONT(row.name, _color=color, _face=face_bold), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(row.type, _color=color, _face=face), _align="left", _cellpadding=cellpadding, _border=border), TD(FONT(types(row), _color=color, _face=face), _align="center", _cellpadding=cellpadding, _border=border))) return "< %s >" % TABLE(*rows, **dict(_bgcolor=bgcolor, _border=1, _cellborder=0, _cellspacing=0) ).xml() def bg_graph_model(): graph = pgv.AGraph(layout='dot', directed=True, strict=False, rankdir='LR') subgraphs = dict() for tablename in db.tables: if hasattr(db[tablename],'_meta_graphmodel'): meta_graphmodel = db[tablename]._meta_graphmodel else: meta_graphmodel = dict(group='Undefined', color='#ECECEC') group = meta_graphmodel['group'].replace(' ', '') if not subgraphs.has_key(group): subgraphs[group] = dict(meta=meta_graphmodel, tables=[]) subgraphs[group]['tables'].append(tablename) else: subgraphs[group]['tables'].append(tablename) graph.add_node(tablename, name=tablename, shape='plaintext', label=table_template(tablename)) for n, key in enumerate(subgraphs.iterkeys()): graph.subgraph(nbunch=subgraphs[key]['tables'], name='cluster%d' % n, style='filled', color=subgraphs[key]['meta']['color'], label=subgraphs[key]['meta']['group']) for tablename in db.tables: for field in db[tablename]: f_type = field.type if isinstance(f_type,str) and ( f_type.startswith('reference') or f_type.startswith('list:reference')): referenced_table = f_type.split()[1].split('.')[0] n1 = graph.get_node(tablename) n2 = graph.get_node(referenced_table) graph.add_edge(n1, n2, color="#4C4C4C", label='') graph.layout() #return graph.draw(format='png', prog='dot') if not request.args: return graph.draw(format='png', prog='dot') else: response.headers['Content-Disposition']='attachment;filename=graph.%s'%request.args(0) if request.args(0) == 'dot': return graph.string() else: return graph.draw(format=request.args(0), prog='dot') def graph_model(): return dict(databases=databases, pgv=pgv)
Python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization ## - download is for downloading files uploaded in the db (does streaming) ## - call exposes all registered services (none by default) ######################################################################### def index(): """ example action using the internationalization operator T and flash rendered by views/default/index.html or views/generic.html if you need a simple wiki simple replace the two lines below with: return auth.wiki() """ response.flash = T("Welcome to web2py!") return dict(message=T('Hello World')) def user(): """ exposes: http://..../[app]/default/user/login http://..../[app]/default/user/logout http://..../[app]/default/user/register http://..../[app]/default/user/profile http://..../[app]/default/user/retrieve_password http://..../[app]/default/user/change_password use @auth.requires_login() @auth.requires_membership('group name') @auth.requires_permission('read','table name',record_id) to decorate functions that need access control """ return dict(form=auth()) @cache.action() def download(): """ allows downloading of uploaded files http://..../[app]/default/download/[filename] """ return response.download(request, db) def call(): """ exposes services. for example: http://..../[app]/default/call/jsonrpc decorate with @services.jsonrpc the functions to expose supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv """ return service() @auth.requires_signature() def data(): """ http://..../[app]/default/data/tables http://..../[app]/default/data/create/[table] http://..../[app]/default/data/read/[table]/[id] http://..../[app]/default/data/update/[table]/[id] http://..../[app]/default/data/delete/[table]/[id] http://..../[app]/default/data/select/[table] http://..../[app]/default/data/search/[table] but URLs must be signed, i.e. linked with A('table',_href=URL('data/tables',user_signature=True)) or with the signed load operator LOAD('default','data.load',args='tables',ajax=True,user_signature=True) """ return dict(form=crud())
Python
# -*- coding: utf-8 -*- # This is an app-specific example router # # This simple router is used for setting languages from app/languages directory # as a part of the application path: app/<lang>/controller/function # Language from default.py or 'en' (if the file is not found) is used as # a default_language # # See <web2py-root-dir>/router.example.py for parameter's detail #------------------------------------------------------------------------------------- # To enable this route file you must do the steps: # # 1. rename <web2py-root-dir>/router.example.py to routes.py # 2. rename this APP/routes.example.py to APP/routes.py # (where APP - is your application directory) # 3. restart web2py (or reload routes in web2py admin interfase) # # YOU CAN COPY THIS FILE TO ANY APLLICATION'S ROOT DIRECTORY WITHOUT CHANGES! from fileutils import abspath from languages import read_possible_languages possible_languages = read_possible_languages(abspath('applications', app)) #NOTE! app - is an application based router's parameter with name of an # application. E.g.'welcome' routers = { app: dict( default_language = possible_languages['default'][0], languages = [lang for lang in possible_languages if lang != 'default'] ) } #NOTE! To change language in your application using these rules add this line #in one of your models files: # if request.uri_language: T.force(request.uri_language)
Python
#!/usr/bin/env python from setuptools import setup from gluon.fileutils import tar, untar, read_file, write_file import tarfile import sys def tar(file, filelist, expression='^.+$'): """ tars dir/files into file, only tars file that match expression """ tar = tarfile.TarFile(file, 'w') try: for element in filelist: try: for file in listdir(element, expression, add_dirs=True): tar.add(os.path.join(element, file), file, False) except: tar.add(element) finally: tar.close() def start(): if 'sdist' in sys.argv: tar('gluon/env.tar', ['applications', 'VERSION', 'splashlogo.gif']) setup(name='web2py', version=read_file("VERSION").split()[1], description="""full-stack framework for rapid development and prototyping of secure database-driven web-based applications, written and programmable in Python.""", long_description=""" Everything in one package with no dependencies. Development, deployment, debugging, testing, database administration and maintenance of applications can be done via the provided web interface. web2py has no configuration files, requires no installation, can run off a USB drive. web2py uses Python for the Model, the Views and the Controllers, has a built-in ticketing system to manage errors, an internationalization engine, works with SQLite, PostgreSQL, MySQL, MSSQL, FireBird, Oracle, IBM DB2, Informix, Ingres, sybase and Google App Engine via a Database Abstraction Layer. web2py includes libraries to handle HTML/XML, RSS, ATOM, CSV, RTF, JSON, AJAX, XMLRPC, WIKI markup. Production ready, capable of upload/download streaming of very large files, and always backward compatible. """, author='Massimo Di Pierro', author_email='mdipierro@cs.depaul.edu', license='http://web2py.com/examples/default/license', classifiers=["Development Status :: 5 - Production/Stable"], url='http://web2py.com', platforms='Windows, Linux, Mac, Unix,Windows Mobile', packages=['gluon', 'gluon/contrib', 'gluon/contrib/gateways', 'gluon/contrib/login_methods', 'gluon/contrib/markdown', 'gluon/contrib/markmin', 'gluon/contrib/memcache', 'gluon/contrib/fpdf', 'gluon/contrib/pymysql', 'gluon/contrib/pyrtf', 'gluon/contrib/pysimplesoap', 'gluon/contrib/simplejson', 'gluon/tests', ], package_data={'gluon': ['env.tar']}, scripts=['w2p_apps', 'w2p_run', 'w2p_clone'], ) if __name__ == '__main__': #print "web2py does not require installation and" #print "you should just start it with:" #print #print "$ python web2py.py" #print #print "are you sure you want to install it anyway (y/n)?" #s = raw_input('>') #if s.lower()[:1]=='y': start()
Python
""" web2py handler for isapi-wsgi for IIS. Requires: http://code.google.com/p/isapi-wsgi/ """ # The entry point for the ISAPI extension. def __ExtensionFactory__(): import os import sys path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main import isapi_wsgi application = gluon.main.wsgibase return isapi_wsgi.ISAPIThreadPoolHandler(application) # ISAPI installation: if __name__ == '__main__': import sys if len(sys.argv) < 2: print "USAGE: python isapiwsgihandler.py install --server=Sitename" sys.exit(0) from isapi.install import ISAPIParameters from isapi.install import ScriptMapParams from isapi.install import VirtualDirParameters from isapi.install import HandleCommandLine params = ISAPIParameters() sm = [ScriptMapParams(Extension="*", Flags=0)] vd = VirtualDirParameters(Name="appname", Description="Web2py in Python", ScriptMaps=sm, ScriptMapUpdate="replace") params.VirtualDirs = [vd] HandleCommandLine(params)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) This is a CGI handler for Apache Requires apache+[mod_cgi or mod_cgid]. In httpd.conf put something like: LoadModule cgi_module modules/mod_cgi.so ScriptAlias / /path/to/cgihandler.py/ Example of httpd.conf ------------ <VirtualHost *:80> ServerName web2py.example.com ScriptAlias / /users/www-data/web2py/cgihandler.py/ <Directory /users/www-data/web2py> AllowOverride None Order Allow,Deny Deny from all <Files cgihandler.py> Allow from all </Files> </Directory> AliasMatch ^/([^/]+)/static/(.*) \ /users/www-data/web2py/applications/$1/static/$2 <Directory /users/www-data/web2py/applications/*/static/> Order Allow,Deny Allow from all </Directory> <Location /admin> Deny from all </Location> <LocationMatch ^/([^/]+)/appadmin> Deny from all </LocationMatch> CustomLog /private/var/log/apache2/access.log common ErrorLog /private/var/log/apache2/error.log </VirtualHost> ---------------------------------- """ import os import sys import wsgiref.handlers path = os.path.dirname(os.path.abspath(__file__)) os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] import gluon.main wsgiref.handlers.CGIHandler().run(gluon.main.wsgibase)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
Python
"""Convert a FAQ (AlterEgo) markdown dump into ReSt documents using pandoc **Todo** #. add titles #. add logging #. add CLI with optparse """ import os import sys import glob import subprocess import logging indir = 'faq_markdown' outdir = 'faq_rst' inpath = os.path.join('.', indir) outpath = os.path.join('.', outdir) pattern = inpath + '/*.txt' out_ext = 'rst' for file in glob.glob(pattern): infile = file file_basename = os.path.basename(file) outfile_name = os.path.splitext(file_basename)[0] + '.' + out_ext outfile = os.path.join(outpath, outfile_name) # pandoc -s -w rst --toc README -o example6.text logging.info("converting file %s to format <%s>" % (file_basename, out_ext)) convert_call = ["pandoc", "-s", "-w", out_ext, infile, "-o", outfile ] p = subprocess.call(convert_call) logging.info("Finshed!")
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(package, module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s.%s\n' % (package, module) for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, package, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(package, module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ package_name = os.path.split(path)[-1] print 'package name', package_name toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, package_name, module, opts) if not check_for_code(os.path.join(path, module+'.py')): # don't build the file if there's no code in it pass else: toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) # FIXME: HERE THE __init__.py should go into the toc only if it contains # code! if not check_for_code(subroot): # don't build the file if there's no code in it continue toc.append(subroot) print 'here' elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) print 'hello' # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # Sropulpof # Copyright (C) 2008 Société des arts technologiques (SAT) # http://www.sat.qc.ca # All rights reserved. # # This file is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 2 of the License, or # (at your option) any later version. # # Sropulpof is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sropulpof. If not, see <http:#www.gnu.org/licenses/>. """ This script parse a directory tree looking for python modules and packages and create ReST files appropriately to create code documentation with Sphinx. It also create a modules index. """ import os import optparse # automodule options options = ['members', 'undoc-members', # 'inherited-members', # disable because there's a bug in sphinx 'show-inheritance'] def create_file_name(base, opts): """Create file name from base name, path and suffix""" return os.path.join(opts.destdir, "%s.%s" % (base, opts.suffix)) def write_directive(module): """Create the automodule directive and add the options""" directive = '.. automodule:: %s\n' % module for option in options: directive += ' :%s:\n' % option return directive def write_heading(module, kind='Module'): """Create the page heading.""" module = module.title() heading = title_line(module + ' Documentation', '=') heading += 'This page contains the %s %s documentation.\n\n' % (module, kind) return heading def write_sub(module, kind='Module'): """Create the module subtitle""" sub = title_line('The :mod:`%s` %s' % (module, kind), '-') return sub def title_line(title, char): """ Underline the title with the character pass, with the right length.""" return '%s\n%s\n\n' % (title, len(title) * char) def create_module_file(root, module, opts): """Build the text of the file and write the file.""" name = create_file_name(module, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name elif check_for_code('%s/%s.py' % (root, module)): # don't build the file if there's no code in it print 'Creating file %s for module.' % name text = write_heading(module) text += write_sub(module) text += write_directive(module) # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def create_package_file(root, subroot, py_files, opts, subs=None): """Build the text of the file and write the file.""" package = root.rpartition('/')[2].lower() name = create_file_name(subroot, opts) if not opts.force and os.path.isfile(name): print 'File %s already exists.' % name else: print 'Creating file %s for package.' % name text = write_heading(package, 'Package') if subs == None: subs = [] else: # build a list of directories that are package (they contain an __init_.py file) subs = [sub for sub in subs if os.path.isfile('%s/%s/__init__.py' % (root, sub))] # if there's some package directories, add a TOC for theses subpackages if subs: text += title_line('Subpackages', '-') text += '.. toctree::\n\n' for sub in subs: text += ' %s.%s\n' % (subroot, sub) text += '\n' # add each package's module for py_file in py_files: if not check_for_code('%s/%s' % (root, py_file)): # don't build the file if there's no code in it continue py_file = py_file[:-3] py_path = '%s.%s' % (subroot, py_file) kind = "Module" if py_file == '__init__': kind = "Package" text += write_sub(kind == 'Package' and package or py_file, kind) text += write_directive(kind == "Package" and subroot or py_path) text += '\n' # write the file if not opts.dryrun: fd = open(name, 'w') fd.write(text) fd.close() def check_for_code(module): """ Check if there's at least one class or one function in the module. """ fd = open(module, 'r') for line in fd: if line.startswith('def ') or line.startswith('class '): fd.close() return True fd.close() return False def recurse_tree(path, excludes, opts): """ Look for every file in the directory tree and create the corresponding ReST files. """ toc = [] excludes = format_excludes(path, excludes) tree = os.walk(path, False) for root, subs, files in tree: # keep only the Python script files py_files = check_py_file(files) # remove hidden ('.') and private ('_') directories subs = [sub for sub in subs if sub[0] not in ['.', '_']] # check if there's valid files to process if "/." in root or "/_" in root \ or not py_files \ or check_excludes(root, excludes): continue subroot = root[len(path):].lstrip('/').replace('/', '.') if root == path: # we are at the root level so we create only modules for py_file in py_files: module = py_file[:-3] create_module_file(root, module, opts) toc.append(module) elif not subs and "__init__.py" in py_files: # we are in a package without sub package create_package_file(root, subroot, py_files, opts=opts) toc.append(subroot) elif "__init__.py" in py_files: # we are in package with subpackage(s) create_package_file(root, subroot, py_files, opts, subs) toc.append(subroot) # create the module's index if not opts.notoc: modules_toc(toc, opts) def modules_toc(modules, opts, name='modules'): """ Create the module's index. """ fname = create_file_name(name, opts) if not opts.force and os.path.exists(fname): print "File %s already exists." % name return print "Creating module's index modules.txt." text = write_heading(opts.header, 'Modules') text += title_line('Modules:', '-') text += '.. toctree::\n' text += ' :maxdepth: %s\n\n' % opts.maxdepth modules.sort() prev_module = '' for module in modules: # look if the module is a subpackage and, if yes, ignore it if module.startswith(prev_module + '.'): continue prev_module = module text += ' %s\n' % module # write the file if not opts.dryrun: fd = open(fname, 'w') fd.write(text) fd.close() def format_excludes(path, excludes): """ Format the excluded directory list. (verify that the path is not from the root of the volume or the root of the package) """ f_excludes = [] for exclude in excludes: if exclude[0] != '/' and exclude[:len(path)] != path: exclude = '%s/%s' % (path, exclude) # remove trailing slash f_excludes.append(exclude.rstrip('/')) return f_excludes def check_excludes(root, excludes): """ Check if the directory is in the exclude list. """ for exclude in excludes: if root[:len(exclude)] == exclude: return True return False def check_py_file(files): """ Return a list with only the python scripts (remove all other files). """ py_files = [fich for fich in files if fich[-3:] == '.py'] return py_files if __name__ == '__main__': parser = optparse.OptionParser(usage="""usage: %prog [options] <package path> [exclude paths, ...] Note: By default this script will not overwrite already created files.""") parser.add_option("-n", "--doc-header", action="store", dest="header", help="Documentation Header (default=Project)", default="Project") parser.add_option("-d", "--dest-dir", action="store", dest="destdir", help="Output destination directory", default="") parser.add_option("-s", "--suffix", action="store", dest="suffix", help="module suffix (default=txt)", default="txt") parser.add_option("-m", "--maxdepth", action="store", dest="maxdepth", help="Maximum depth of submodules to show in the TOC (default=4)", type="int", default=4) parser.add_option("-r", "--dry-run", action="store_true", dest="dryrun", help="Run the script without creating the files") parser.add_option("-f", "--force", action="store_true", dest="force", help="Overwrite all the files") parser.add_option("-t", "--no-toc", action="store_true", dest="notoc", help="Don't create the table of content file") (opts, args) = parser.parse_args() if len(args) < 1: parser.error("package path is required.") else: if os.path.isdir(args[0]): # if there's some exclude arguments, build the list of excludes excludes = args[1:] recurse_tree(args[0], excludes, opts) else: print '%s is not a valid directory.' % args
Python
import os import subprocess import codecs #--- BZR: changelog information def write_changelog_bzr(repo_path, output_dir, output_file='bzr_revision_log.txt', target_encoding='utf-8'): """Write the bzr changelog to a file which can then be included in the documentation """ bzr_logfile_path = os.path.join(output_dir, output_file) bzr_logfile = codecs.open(bzr_logfile_path, 'w', encoding=target_encoding) try: p_log = subprocess.Popen(('bzr log --short'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_log.communicate() bzr_logfile.write(stdout) finally: bzr_logfile.close() #UnicodeDecodeError: 'ascii' codec can't decode byte 0x81 in position 2871: ordinal not in range(128) # like bzr version-info --format python > vers_test.py #--- BZR: version info def write_version_info_bzr(repo_path, output_dir, output_file='_version.py'): """Write the version information from BZR repository into a version file. Parameters ---------- repo_path : string Path to the BZR repository root repo_path : string Path to the output directory where the version info is saved detail, e.g. ``(N,) ndarray`` or ``array_like``. output_file : string output file name Returns ------- p_info : subprocess_obj contents of the `func:`suprocess.Popen` returns """ bzr_version_filepath = os.path.join(output_dir, output_file) bzr_version_file = open(bzr_version_filepath, 'w') p_info = subprocess.Popen(('bzr version-info --format python'), stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=-1) (stdout, stderr) = p_info.communicate() bzr_version_file.write(stdout) bzr_version_file.close() return p_info #--- auto generate documentation def autogenerate_package_doc(script_path, dest_dir, package_dir, doc_header, suffix='rst', overwrite=False): """Autogenerate package API ReSt documents """ print script_path if overwrite: force = '--force' p_apidoc = subprocess.Popen(('python', script_path, '--dest-dir='+dest_dir, '--suffix='+suffix, '--doc-header='+doc_header, force, package_dir), bufsize=-1) 'sphinxext\local\generate_modules_modif.py --dest-dir=source\contents\lib\auxilary\generated --suffix=rst --force --doc-header=Auxilary ..\..\modules_local\auxilary' return p_apidoc if __name__ == "__main__": repo_path = os.path.join('..', '.') output_dir = os.path.join('.') write_changelog_bzr(repo_path, output_dir, output_file='changelog.txt')
Python
""" A special directive for generating a matplotlib plot. .. warning:: This is a hacked version of plot_directive.py from Matplotlib. It's very much subject to change! Usage ----- Can be used like this:: .. plot:: examples/example.py .. plot:: import matplotlib.pyplot as plt plt.plot([1,2,3], [4,5,6]) .. plot:: A plotting example: >>> import matplotlib.pyplot as plt >>> plt.plot([1,2,3], [4,5,6]) The content is interpreted as doctest formatted if it has a line starting with ``>>>``. The ``plot`` directive supports the options format : {'python', 'doctest'} Specify the format of the input include-source : bool Whether to display the source code. Default can be changed in conf.py and the ``image`` directive options ``alt``, ``height``, ``width``, ``scale``, ``align``, ``class``. Configuration options --------------------- The plot directive has the following configuration options: plot_output_dir Directory (relative to config file) where to store plot output. Should be inside the static directory. (Default: 'static') plot_pre_code Code that should be executed before each plot. plot_rcparams Dictionary of Matplotlib rc-parameter overrides. Has 'sane' defaults. plot_include_source Default value for the include-source option plot_formats The set of files to generate. Default: ['png', 'pdf', 'hires.png'], ie. everything. TODO ---- * Don't put temp files to _static directory, but do function in the way the pngmath directive works, and plot figures only during output writing. * Refactor Latex output; now it's plain images, but it would be nice to make them appear side-by-side, or in floats. """ import sys, os, glob, shutil, imp, warnings, cStringIO, re, textwrap import warnings warnings.warn("A plot_directive module is also available under " "matplotlib.sphinxext; expect this numpydoc.plot_directive " "module to be deprecated after relevant features have been " "integrated there.", FutureWarning, stacklevel=2) def setup(app): setup.app = app setup.config = app.config setup.confdir = app.confdir static_path = '_static' if hasattr(app.config, 'html_static_path') and app.config.html_static_path: static_path = app.config.html_static_path[0] app.add_config_value('plot_output_dir', static_path, True) app.add_config_value('plot_pre_code', '', True) app.add_config_value('plot_rcparams', sane_rcparameters, True) app.add_config_value('plot_include_source', False, True) app.add_config_value('plot_formats', ['png', 'hires.png', 'pdf'], True) app.add_directive('plot', plot_directive, True, (0, 1, False), **plot_directive_options) sane_rcparameters = { 'font.size': 9, 'axes.titlesize': 9, 'axes.labelsize': 9, 'xtick.labelsize': 9, 'ytick.labelsize': 9, 'legend.fontsize': 9, 'figure.figsize': (4, 3), } #------------------------------------------------------------------------------ # Run code and capture figures #------------------------------------------------------------------------------ import matplotlib import matplotlib.cbook as cbook matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.image as image from matplotlib import _pylab_helpers def contains_doctest(text): r = re.compile(r'^\s*>>>', re.M) m = r.match(text) return bool(m) def unescape_doctest(text): """ Extract code from a piece of text, which contains either Python code or doctests. """ if not contains_doctest(text): return text code = "" for line in text.split("\n"): m = re.match(r'^\s*(>>>|...) (.*)$', line) if m: code += m.group(2) + "\n" elif line.strip(): code += "# " + line.strip() + "\n" else: code += "\n" return code def run_code(code, code_path): # Change the working directory to the directory of the example, so # it can get at its data files, if any. pwd = os.getcwd() old_sys_path = list(sys.path) if code_path is not None: dirname = os.path.abspath(os.path.dirname(code_path)) os.chdir(dirname) sys.path.insert(0, dirname) # Redirect stdout stdout = sys.stdout sys.stdout = cStringIO.StringIO() try: code = unescape_doctest(code) ns = {} exec setup.config.plot_pre_code in ns exec code in ns finally: os.chdir(pwd) sys.path[:] = old_sys_path sys.stdout = stdout return ns #------------------------------------------------------------------------------ # Generating figures #------------------------------------------------------------------------------ def out_of_date(original, derived): """ Returns True if derivative is out-of-date wrt original, both of which are full file paths. """ return (not os.path.exists(derived) or os.stat(derived).st_mtime < os.stat(original).st_mtime) def makefig(code, code_path, output_dir, output_base, config): """ run a pyplot script and save the low and high res PNGs and a PDF in _static """ included_formats = config.plot_formats if type(included_formats) is str: included_formats = eval(included_formats) formats = [x for x in [('png', 80), ('hires.png', 200), ('pdf', 50)] if x[0] in config.plot_formats] all_exists = True # Look for single-figure output files first for format, dpi in formats: output_path = os.path.join(output_dir, '%s.%s' % (output_base, format)) if out_of_date(code_path, output_path): all_exists = False break if all_exists: return [output_base] # Then look for multi-figure output files image_names = [] for i in xrange(1000): image_names.append('%s_%02d' % (output_base, i)) for format, dpi in formats: output_path = os.path.join(output_dir, '%s.%s' % (image_names[-1], format)) if out_of_date(code_path, output_path): all_exists = False break if not all_exists: # assume that if we have one, we have them all all_exists = (i > 0) break if all_exists: return image_names # We didn't find the files, so build them print "-- Plotting figures %s" % output_base # Clear between runs plt.close('all') # Reset figure parameters matplotlib.rcdefaults() matplotlib.rcParams.update(config.plot_rcparams) # Run code run_code(code, code_path) # Collect images image_names = [] fig_managers = _pylab_helpers.Gcf.get_all_fig_managers() for i, figman in enumerate(fig_managers): if len(fig_managers) == 1: name = output_base else: name = "%s_%02d" % (output_base, i) image_names.append(name) for format, dpi in formats: path = os.path.join(output_dir, '%s.%s' % (name, format)) figman.canvas.figure.savefig(path, dpi=dpi) return image_names #------------------------------------------------------------------------------ # Generating output #------------------------------------------------------------------------------ from docutils import nodes, utils import jinja TEMPLATE = """ {{source_code}} .. htmlonly:: {% if source_code %} (`Source code <{{source_link}}>`__) {% endif %} .. admonition:: Output :class: plot-output {% for name in image_names %} .. figure:: {{link_dir}}/{{name}}.png {%- for option in options %} {{option}} {% endfor %} ( {%- if not source_code %}`Source code <{{source_link}}>`__, {% endif -%} `PNG <{{link_dir}}/{{name}}.hires.png>`__, `PDF <{{link_dir}}/{{name}}.pdf>`__) {% endfor %} .. latexonly:: {% for name in image_names %} .. image:: {{link_dir}}/{{name}}.pdf {% endfor %} """ def run(arguments, content, options, state_machine, state, lineno): if arguments and content: raise RuntimeError("plot:: directive can't have both args and content") document = state_machine.document config = document.settings.env.config options.setdefault('include-source', config.plot_include_source) if options['include-source'] is None: options['include-source'] = config.plot_include_source # determine input rst_file = document.attributes['source'] rst_dir = os.path.dirname(rst_file) if arguments: file_name = os.path.join(rst_dir, directives.uri(arguments[0])) code = open(file_name, 'r').read() output_base = os.path.basename(file_name) else: file_name = rst_file code = textwrap.dedent("\n".join(map(str, content))) counter = document.attributes.get('_plot_counter', 0) + 1 document.attributes['_plot_counter'] = counter output_base = '%d-%s' % (counter, os.path.basename(file_name)) rel_name = relpath(file_name, setup.confdir) base, ext = os.path.splitext(output_base) if ext in ('.py', '.rst', '.txt'): output_base = base # is it in doctest format? is_doctest = contains_doctest(code) if options.has_key('format'): if options['format'] == 'python': is_doctest = False else: is_doctest = True # determine output file_rel_dir = os.path.dirname(rel_name) while file_rel_dir.startswith(os.path.sep): file_rel_dir = file_rel_dir[1:] output_dir = os.path.join(setup.confdir, setup.config.plot_output_dir, file_rel_dir) if not os.path.exists(output_dir): cbook.mkdirs(output_dir) # copy script target_name = os.path.join(output_dir, output_base) f = open(target_name, 'w') f.write(unescape_doctest(code)) f.close() source_link = relpath(target_name, rst_dir) # determine relative reference link_dir = relpath(output_dir, rst_dir) # make figures try: image_names = makefig(code, file_name, output_dir, output_base, config) except RuntimeError, err: reporter = state.memo.reporter sm = reporter.system_message(3, "Exception occurred rendering plot", line=lineno) return [sm] # generate output if options['include-source']: if is_doctest: lines = [''] else: lines = ['.. code-block:: python', ''] lines += [' %s' % row.rstrip() for row in code.split('\n')] source_code = "\n".join(lines) else: source_code = "" opts = [':%s: %s' % (key, val) for key, val in options.items() if key in ('alt', 'height', 'width', 'scale', 'align', 'class')] result = jinja.from_string(TEMPLATE).render( link_dir=link_dir.replace(os.path.sep, '/'), source_link=source_link, options=opts, image_names=image_names, source_code=source_code) lines = result.split("\n") if len(lines): state_machine.insert_input( lines, state_machine.input_lines.source(0)) return [] if hasattr(os.path, 'relpath'): relpath = os.path.relpath else: def relpath(target, base=os.curdir): """ Return a relative path to the target from either the current dir or an optional base dir. Base can be a directory specified either as absolute or relative to current dir. """ if not os.path.exists(target): raise OSError, 'Target does not exist: '+target if not os.path.isdir(base): raise OSError, 'Base is not a directory or does not exist: '+base base_list = (os.path.abspath(base)).split(os.sep) target_list = (os.path.abspath(target)).split(os.sep) # On the windows platform the target may be on a completely # different drive from the base. if os.name in ['nt','dos','os2'] and base_list[0] <> target_list[0]: raise OSError, 'Target is on a different drive to base. Target: '+target_list[0].upper()+', base: '+base_list[0].upper() # Starting from the filepath root, work out how much of the # filepath is shared by base and target. for i in range(min(len(base_list), len(target_list))): if base_list[i] <> target_list[i]: break else: # If we broke out of the loop, i is pointing to the first # differing path elements. If we didn't break out of the # loop, i is pointing to identical path elements. # Increment i so that in all cases it points to the first # differing path elements. i+=1 rel_list = [os.pardir] * (len(base_list)-i) + target_list[i:] return os.path.join(*rel_list) #------------------------------------------------------------------------------ # plot:: directive registration etc. #------------------------------------------------------------------------------ from docutils.parsers.rst import directives try: # docutils 0.4 from docutils.parsers.rst.directives.images import align except ImportError: # docutils 0.5 from docutils.parsers.rst.directives.images import Image align = Image.align def plot_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(arguments, content, options, state_machine, state, lineno) plot_directive.__doc__ = __doc__ def _option_boolean(arg): if not arg or not arg.strip(): return None elif arg.strip().lower() in ('no', '0', 'false'): return False elif arg.strip().lower() in ('yes', '1', 'true'): return True else: raise ValueError('"%s" unknown boolean' % arg) def _option_format(arg): return directives.choice(arg, ('python', 'lisp')) plot_directive_options = {'alt': directives.unchanged, 'height': directives.length_or_unitless, 'width': directives.length_or_percentage_or_unitless, 'scale': directives.nonnegative_int, 'align': align, 'class': directives.class_option, 'include-source': _option_boolean, 'format': _option_format, }
Python
"""Extract reference documentation from the NumPy source tree. """ import inspect import textwrap import re import pydoc from StringIO import StringIO from warnings import warn 4 class Reader(object): """A line-based string reader. """ def __init__(self, data): """ Parameters ---------- data : str String with lines separated by '\n'. """ if isinstance(data,list): self._str = data else: self._str = data.split('\n') # store string as list of lines self.reset() def __getitem__(self, n): return self._str[n] def reset(self): self._l = 0 # current line nr def read(self): if not self.eof(): out = self[self._l] self._l += 1 return out else: return '' def seek_next_non_empty_line(self): for l in self[self._l:]: if l.strip(): break else: self._l += 1 def eof(self): return self._l >= len(self._str) def read_to_condition(self, condition_func): start = self._l for line in self[start:]: if condition_func(line): return self[start:self._l] self._l += 1 if self.eof(): return self[start:self._l+1] return [] def read_to_next_empty_line(self): self.seek_next_non_empty_line() def is_empty(line): return not line.strip() return self.read_to_condition(is_empty) def read_to_next_unindented_line(self): def is_unindented(line): return (line.strip() and (len(line.lstrip()) == len(line))) return self.read_to_condition(is_unindented) def peek(self,n=0): if self._l + n < len(self._str): return self[self._l + n] else: return '' def is_empty(self): return not ''.join(self._str).strip() class NumpyDocString(object): def __init__(self,docstring): docstring = textwrap.dedent(docstring).split('\n') self._doc = Reader(docstring) self._parsed_data = { 'Signature': '', 'Summary': [''], 'Extended Summary': [], 'Parameters': [], 'Returns': [], 'Raises': [], 'Warns': [], 'Other Parameters': [], 'Attributes': [], 'Methods': [], 'See Also': [], 'Notes': [], 'Warnings': [], 'References': '', 'Examples': '', 'index': {} } self._parse() def __getitem__(self,key): return self._parsed_data[key] def __setitem__(self,key,val): if not self._parsed_data.has_key(key): warn("Unknown section %s" % key) else: self._parsed_data[key] = val def _is_at_section(self): self._doc.seek_next_non_empty_line() if self._doc.eof(): return False l1 = self._doc.peek().strip() # e.g. Parameters if l1.startswith('.. index::'): return True l2 = self._doc.peek(1).strip() # ---------- or ========== return l2.startswith('-'*len(l1)) or l2.startswith('='*len(l1)) def _strip(self,doc): i = 0 j = 0 for i,line in enumerate(doc): if line.strip(): break for j,line in enumerate(doc[::-1]): if line.strip(): break return doc[i:len(doc)-j] def _read_to_next_section(self): section = self._doc.read_to_next_empty_line() while not self._is_at_section() and not self._doc.eof(): if not self._doc.peek(-1).strip(): # previous line was empty section += [''] section += self._doc.read_to_next_empty_line() return section def _read_sections(self): while not self._doc.eof(): data = self._read_to_next_section() name = data[0].strip() if name.startswith('..'): # index section yield name, data[1:] elif len(data) < 2: yield StopIteration else: yield name, self._strip(data[2:]) def _parse_param_list(self,content): r = Reader(content) params = [] while not r.eof(): header = r.read().strip() if ' : ' in header: arg_name, arg_type = header.split(' : ')[:2] else: arg_name, arg_type = header, '' desc = r.read_to_next_unindented_line() desc = dedent_lines(desc) params.append((arg_name,arg_type,desc)) return params _name_rgx = re.compile(r"^\s*(:(?P<role>\w+):`(?P<name>[a-zA-Z0-9_.-]+)`|" r" (?P<name2>[a-zA-Z0-9_.-]+))\s*", re.X) def _parse_see_also(self, content): """ func_name : Descriptive text continued text another_func_name : Descriptive text func_name1, func_name2, :meth:`func_name`, func_name3 """ items = [] def parse_item_name(text): """Match ':role:`name`' or 'name'""" m = self._name_rgx.match(text) if m: g = m.groups() if g[1] is None: return g[3], None else: return g[2], g[1] raise ValueError("%s is not a item name" % text) def push_item(name, rest): if not name: return name, role = parse_item_name(name) items.append((name, list(rest), role)) del rest[:] current_func = None rest = [] for line in content: if not line.strip(): continue m = self._name_rgx.match(line) if m and line[m.end():].strip().startswith(':'): push_item(current_func, rest) current_func, line = line[:m.end()], line[m.end():] rest = [line.split(':', 1)[1].strip()] if not rest[0]: rest = [] elif not line.startswith(' '): push_item(current_func, rest) current_func = None if ',' in line: for func in line.split(','): push_item(func, []) elif line.strip(): current_func = line elif current_func is not None: rest.append(line.strip()) push_item(current_func, rest) return items def _parse_index(self, section, content): """ .. index: default :refguide: something, else, and more """ def strip_each_in(lst): return [s.strip() for s in lst] out = {} section = section.split('::') if len(section) > 1: out['default'] = strip_each_in(section[1].split(','))[0] for line in content: line = line.split(':') if len(line) > 2: out[line[1]] = strip_each_in(line[2].split(',')) return out def _parse_summary(self): """Grab signature (if given) and summary""" if self._is_at_section(): return summary = self._doc.read_to_next_empty_line() summary_str = " ".join([s.strip() for s in summary]).strip() if re.compile('^([\w., ]+=)?\s*[\w\.]+\(.*\)$').match(summary_str): self['Signature'] = summary_str if not self._is_at_section(): self['Summary'] = self._doc.read_to_next_empty_line() else: self['Summary'] = summary if not self._is_at_section(): self['Extended Summary'] = self._read_to_next_section() def _parse(self): self._doc.reset() self._parse_summary() for (section,content) in self._read_sections(): if not section.startswith('..'): section = ' '.join([s.capitalize() for s in section.split(' ')]) if section in ('Parameters', 'Attributes', 'Methods', 'Returns', 'Raises', 'Warns'): self[section] = self._parse_param_list(content) elif section.startswith('.. index::'): self['index'] = self._parse_index(section, content) elif section == 'See Also': self['See Also'] = self._parse_see_also(content) else: self[section] = content # string conversion routines def _str_header(self, name, symbol='-'): return [name, len(name)*symbol] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): if self['Signature']: return [self['Signature'].replace('*','\*')] + [''] else: return [''] def _str_summary(self): if self['Summary']: return self['Summary'] + [''] else: return [] def _str_extended_summary(self): if self['Extended Summary']: return self['Extended Summary'] + [''] else: return [] def _str_param_list(self, name): out = [] if self[name]: out += self._str_header(name) for param,param_type,desc in self[name]: out += ['%s : %s' % (param, param_type)] out += self._str_indent(desc) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += self[name] out += [''] return out def _str_see_also(self, func_role): if not self['See Also']: return [] out = [] out += self._str_header("See Also") last_had_desc = True for func, desc, role in self['See Also']: if role: link = ':%s:`%s`' % (role, func) elif func_role: link = ':%s:`%s`' % (func_role, func) else: link = "`%s`_" % func if desc or last_had_desc: out += [''] out += [link] else: out[-1] += ", %s" % link if desc: out += self._str_indent([' '.join(desc)]) last_had_desc = True else: last_had_desc = False out += [''] return out def _str_index(self): idx = self['index'] out = [] out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue out += [' :%s: %s' % (section, ', '.join(references))] return out def __str__(self, func_role=''): out = [] out += self._str_signature() out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters','Returns','Raises'): out += self._str_param_list(param_list) out += self._str_section('Warnings') out += self._str_see_also(func_role) for s in ('Notes','References','Examples'): out += self._str_section(s) out += self._str_index() return '\n'.join(out) def indent(str,indent=4): indent_str = ' '*indent if str is None: return indent_str lines = str.split('\n') return '\n'.join(indent_str + l for l in lines) def dedent_lines(lines): """Deindent a list of lines maximally""" return textwrap.dedent("\n".join(lines)).split("\n") def header(text, style='-'): return text + '\n' + style*len(text) + '\n' class FunctionDoc(NumpyDocString): def __init__(self, func, role='func', doc=None): self._f = func self._role = role # e.g. "func" or "meth" if doc is None: doc = inspect.getdoc(func) or '' try: NumpyDocString.__init__(self, doc) except ValueError, e: print '*'*78 print "ERROR: '%s' while parsing `%s`" % (e, self._f) print '*'*78 #print "Docstring follows:" #print doclines #print '='*78 if not self['Signature']: func, func_name = self.get_func() try: # try to read signature argspec = inspect.getargspec(func) argspec = inspect.formatargspec(*argspec) argspec = argspec.replace('*','\*') signature = '%s%s' % (func_name, argspec) except TypeError, e: signature = '%s()' % func_name self['Signature'] = signature def get_func(self): func_name = getattr(self._f, '__name__', self.__class__.__name__) if inspect.isclass(self._f): func = getattr(self._f, '__call__', self._f.__init__) else: func = self._f return func, func_name def __str__(self): out = '' func, func_name = self.get_func() signature = self['Signature'].replace('*', '\*') roles = {'func': 'function', 'meth': 'method'} if self._role: if not roles.has_key(self._role): print "Warning: invalid role %s" % self._role out += '.. %s:: %s\n \n\n' % (roles.get(self._role,''), func_name) out += super(FunctionDoc, self).__str__(func_role=self._role) return out class ClassDoc(NumpyDocString): def __init__(self,cls,modulename='',func_doc=FunctionDoc,doc=None): if not inspect.isclass(cls): raise ValueError("Initialise using a class. Got %r" % cls) self._cls = cls if modulename and not modulename.endswith('.'): modulename += '.' self._mod = modulename self._name = cls.__name__ self._func_doc = func_doc if doc is None: doc = pydoc.getdoc(cls) NumpyDocString.__init__(self, doc) @property def methods(self): return [name for name,func in inspect.getmembers(self._cls) if not name.startswith('_') and callable(func)] def __str__(self): out = '' out += super(ClassDoc, self).__str__() out += "\n\n" #for m in self.methods: # print "Parsing `%s`" % m # out += str(self._func_doc(getattr(self._cls,m), 'meth')) + '\n\n' # out += '.. index::\n single: %s; %s\n\n' % (self._name, m) return out
Python
# # A pair of directives for inserting content that will only appear in # either html or latex. # from docutils.nodes import Body, Element from docutils.writers.html4css1 import HTMLTranslator try: from sphinx.latexwriter import LaTeXTranslator except ImportError: from sphinx.writers.latex import LaTeXTranslator import warnings warnings.warn("The numpydoc.only_directives module is deprecated;" "please use the only:: directive available in Sphinx >= 0.6", DeprecationWarning, stacklevel=2) from docutils.parsers.rst import directives class html_only(Body, Element): pass class latex_only(Body, Element): pass def run(content, node_class, state, content_offset): text = '\n'.join(content) node = node_class(text) state.nested_parse(content, content_offset, node) return [node] try: from docutils.parsers.rst import Directive except ImportError: from docutils.parsers.rst.directives import _directives def html_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, html_only, state, content_offset) def latex_only_directive(name, arguments, options, content, lineno, content_offset, block_text, state, state_machine): return run(content, latex_only, state, content_offset) for func in (html_only_directive, latex_only_directive): func.content = 1 func.options = {} func.arguments = None _directives['htmlonly'] = html_only_directive _directives['latexonly'] = latex_only_directive else: class OnlyDirective(Directive): has_content = True required_arguments = 0 optional_arguments = 0 final_argument_whitespace = True option_spec = {} def run(self): self.assert_has_content() return run(self.content, self.node_class, self.state, self.content_offset) class HtmlOnlyDirective(OnlyDirective): node_class = html_only class LatexOnlyDirective(OnlyDirective): node_class = latex_only directives.register_directive('htmlonly', HtmlOnlyDirective) directives.register_directive('latexonly', LatexOnlyDirective) def setup(app): app.add_node(html_only) app.add_node(latex_only) # Add visit/depart methods to HTML-Translator: def visit_perform(self, node): pass def depart_perform(self, node): pass def visit_ignore(self, node): node.children = [] def depart_ignore(self, node): node.children = [] HTMLTranslator.visit_html_only = visit_perform HTMLTranslator.depart_html_only = depart_perform HTMLTranslator.visit_latex_only = visit_ignore HTMLTranslator.depart_latex_only = depart_ignore LaTeXTranslator.visit_html_only = visit_ignore LaTeXTranslator.depart_html_only = depart_ignore LaTeXTranslator.visit_latex_only = visit_perform LaTeXTranslator.depart_latex_only = depart_perform
Python
from cStringIO import StringIO import compiler import inspect import textwrap import tokenize from compiler_unparse import unparse class Comment(object): """ A comment block. """ is_comment = True def __init__(self, start_lineno, end_lineno, text): # int : The first line number in the block. 1-indexed. self.start_lineno = start_lineno # int : The last line number. Inclusive! self.end_lineno = end_lineno # str : The text block including '#' character but not any leading spaces. self.text = text def add(self, string, start, end, line): """ Add a new comment line. """ self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) self.text += string def __repr__(self): return '%s(%r, %r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno, self.text) class NonComment(object): """ A non-comment block of code. """ is_comment = False def __init__(self, start_lineno, end_lineno): self.start_lineno = start_lineno self.end_lineno = end_lineno def add(self, string, start, end, line): """ Add lines to the block. """ if string.strip(): # Only add if not entirely whitespace. self.start_lineno = min(self.start_lineno, start[0]) self.end_lineno = max(self.end_lineno, end[0]) def __repr__(self): return '%s(%r, %r)' % (self.__class__.__name__, self.start_lineno, self.end_lineno) class CommentBlocker(object): """ Pull out contiguous comment blocks. """ def __init__(self): # Start with a dummy. self.current_block = NonComment(0, 0) # All of the blocks seen so far. self.blocks = [] # The index mapping lines of code to their associated comment blocks. self.index = {} def process_file(self, file): """ Process a file object. """ for token in tokenize.generate_tokens(file.next): self.process_token(*token) self.make_index() def process_token(self, kind, string, start, end, line): """ Process a single token. """ if self.current_block.is_comment: if kind == tokenize.COMMENT: self.current_block.add(string, start, end, line) else: self.new_noncomment(start[0], end[0]) else: if kind == tokenize.COMMENT: self.new_comment(string, start, end, line) else: self.current_block.add(string, start, end, line) def new_noncomment(self, start_lineno, end_lineno): """ We are transitioning from a noncomment to a comment. """ block = NonComment(start_lineno, end_lineno) self.blocks.append(block) self.current_block = block def new_comment(self, string, start, end, line): """ Possibly add a new comment. Only adds a new comment if this comment is the only thing on the line. Otherwise, it extends the noncomment block. """ prefix = line[:start[1]] if prefix.strip(): # Oops! Trailing comment, not a comment block. self.current_block.add(string, start, end, line) else: # A comment block. block = Comment(start[0], end[0], string) self.blocks.append(block) self.current_block = block def make_index(self): """ Make the index mapping lines of actual code to their associated prefix comments. """ for prev, block in zip(self.blocks[:-1], self.blocks[1:]): if not block.is_comment: self.index[block.start_lineno] = prev def search_for_comment(self, lineno, default=None): """ Find the comment block just before the given line number. Returns None (or the specified default) if there is no such block. """ if not self.index: self.make_index() block = self.index.get(lineno, None) text = getattr(block, 'text', default) return text def strip_comment_marker(text): """ Strip # markers at the front of a block of comment text. """ lines = [] for line in text.splitlines(): lines.append(line.lstrip('#')) text = textwrap.dedent('\n'.join(lines)) return text def get_class_traits(klass): """ Yield all of the documentation for trait definitions on a class object. """ # FIXME: gracefully handle errors here or in the caller? source = inspect.getsource(klass) cb = CommentBlocker() cb.process_file(StringIO(source)) mod_ast = compiler.parse(source) class_ast = mod_ast.node.nodes[0] for node in class_ast.code.nodes: # FIXME: handle other kinds of assignments? if isinstance(node, compiler.ast.Assign): name = node.nodes[0].name rhs = unparse(node.expr).strip() doc = strip_comment_marker(cb.search_for_comment(node.lineno, default='')) yield name, rhs, doc
Python
""" =========== autosummary =========== Sphinx extension that adds an autosummary:: directive, which can be used to generate function/method/attribute/etc. summary lists, similar to those output eg. by Epydoc and other API doc generation tools. An :autolink: role is also provided. autosummary directive --------------------- The autosummary directive has the form:: .. autosummary:: :nosignatures: :toctree: generated/ module.function_1 module.function_2 ... and it generates an output table (containing signatures, optionally) ======================== ============================================= module.function_1(args) Summary line from the docstring of function_1 module.function_2(args) Summary line from the docstring ... ======================== ============================================= If the :toctree: option is specified, files matching the function names are inserted to the toctree with the given prefix: generated/module.function_1 generated/module.function_2 ... Note: The file names contain the module:: or currentmodule:: prefixes. .. seealso:: autosummary_generate.py autolink role ------------- The autolink role functions as ``:obj:`` when the name referred can be resolved to a Python object, and otherwise it becomes simple emphasis. This can be used as the default role to make links 'smart'. """ import sys, os, posixpath, re from docutils.parsers.rst import directives from docutils.statemachine import ViewList from docutils import nodes import sphinx.addnodes, sphinx.roles from sphinx.util import patfilter from docscrape_sphinx import get_doc_object import warnings warnings.warn( "The numpydoc.autosummary extension can also be found as " "sphinx.ext.autosummary in Sphinx >= 0.6, and the version in " "Sphinx >= 0.7 is superior to the one in numpydoc. This numpydoc " "version of autosummary is no longer maintained.", DeprecationWarning, stacklevel=2) def setup(app): app.add_directive('autosummary', autosummary_directive, True, (0, 0, False), toctree=directives.unchanged, nosignatures=directives.flag) app.add_role('autolink', autolink_role) app.add_node(autosummary_toc, html=(autosummary_toc_visit_html, autosummary_toc_depart_noop), latex=(autosummary_toc_visit_latex, autosummary_toc_depart_noop)) app.connect('doctree-read', process_autosummary_toc) #------------------------------------------------------------------------------ # autosummary_toc node #------------------------------------------------------------------------------ class autosummary_toc(nodes.comment): pass def process_autosummary_toc(app, doctree): """ Insert items described in autosummary:: to the TOC tree, but do not generate the toctree:: list. """ env = app.builder.env crawled = {} def crawl_toc(node, depth=1): crawled[node] = True for j, subnode in enumerate(node): try: if (isinstance(subnode, autosummary_toc) and isinstance(subnode[0], sphinx.addnodes.toctree)): env.note_toctree(env.docname, subnode[0]) continue except IndexError: continue if not isinstance(subnode, nodes.section): continue if subnode not in crawled: crawl_toc(subnode, depth+1) crawl_toc(doctree) def autosummary_toc_visit_html(self, node): """Hide autosummary toctree list in HTML output""" raise nodes.SkipNode def autosummary_toc_visit_latex(self, node): """Show autosummary toctree (= put the referenced pages here) in Latex""" pass def autosummary_toc_depart_noop(self, node): pass #------------------------------------------------------------------------------ # .. autosummary:: #------------------------------------------------------------------------------ def autosummary_directive(dirname, arguments, options, content, lineno, content_offset, block_text, state, state_machine): """ Pretty table containing short signatures and summaries of functions etc. autosummary also generates a (hidden) toctree:: node. """ names = [] names += [x.strip().split()[0] for x in content if x.strip() and re.search(r'^[a-zA-Z_]', x.strip()[0])] table, warnings, real_names = get_autosummary(names, state, 'nosignatures' in options) node = table env = state.document.settings.env suffix = env.config.source_suffix all_docnames = env.found_docs.copy() dirname = posixpath.dirname(env.docname) if 'toctree' in options: tree_prefix = options['toctree'].strip() docnames = [] for name in names: name = real_names.get(name, name) docname = tree_prefix + name if docname.endswith(suffix): docname = docname[:-len(suffix)] docname = posixpath.normpath(posixpath.join(dirname, docname)) if docname not in env.found_docs: warnings.append(state.document.reporter.warning( 'toctree references unknown document %r' % docname, line=lineno)) docnames.append(docname) tocnode = sphinx.addnodes.toctree() tocnode['includefiles'] = docnames tocnode['maxdepth'] = -1 tocnode['glob'] = None tocnode['entries'] = [(None, docname) for docname in docnames] tocnode = autosummary_toc('', '', tocnode) return warnings + [node] + [tocnode] else: return warnings + [node] def get_autosummary(names, state, no_signatures=False): """ Generate a proper table node for autosummary:: directive. Parameters ---------- names : list of str Names of Python objects to be imported and added to the table. document : document Docutils document object """ document = state.document real_names = {} warnings = [] prefixes = [''] prefixes.insert(0, document.settings.env.currmodule) table = nodes.table('') group = nodes.tgroup('', cols=2) table.append(group) group.append(nodes.colspec('', colwidth=10)) group.append(nodes.colspec('', colwidth=90)) body = nodes.tbody('') group.append(body) def append_row(*column_texts): row = nodes.row('') for text in column_texts: node = nodes.paragraph('') vl = ViewList() vl.append(text, '<autosummary>') state.nested_parse(vl, 0, node) try: if isinstance(node[0], nodes.paragraph): node = node[0] except IndexError: pass row.append(nodes.entry('', node)) body.append(row) for name in names: try: obj, real_name = import_by_name(name, prefixes=prefixes) except ImportError: warnings.append(document.reporter.warning( 'failed to import %s' % name)) append_row(":obj:`%s`" % name, "") continue real_names[name] = real_name doc = get_doc_object(obj) if doc['Summary']: title = " ".join(doc['Summary']) else: title = "" col1 = u":obj:`%s <%s>`" % (name, real_name) if doc['Signature']: sig = re.sub('^[^(\[]*', '', doc['Signature'].strip()) if '=' in sig: # abbreviate optional arguments sig = re.sub(r', ([a-zA-Z0-9_]+)=', r'[, \1=', sig, count=1) sig = re.sub(r'\(([a-zA-Z0-9_]+)=', r'([\1=', sig, count=1) sig = re.sub(r'=[^,)]+,', ',', sig) sig = re.sub(r'=[^,)]+\)$', '])', sig) # shorten long strings sig = re.sub(r'(\[.{16,16}[^,]*?),.*?\]\)', r'\1, ...])', sig) else: sig = re.sub(r'(\(.{16,16}[^,]*?),.*?\)', r'\1, ...)', sig) # make signature contain non-breaking spaces col1 += u"\\ \u00a0" + unicode(sig).replace(u" ", u"\u00a0") col2 = title append_row(col1, col2) return table, warnings, real_names def import_by_name(name, prefixes=[None]): """ Import a Python object that has the given name, under one of the prefixes. Parameters ---------- name : str Name of a Python object, eg. 'numpy.ndarray.view' prefixes : list of (str or None), optional Prefixes to prepend to the name (None implies no prefix). The first prefixed name that results to successful import is used. Returns ------- obj The imported object name Name of the imported object (useful if `prefixes` was used) """ for prefix in prefixes: try: if prefix: prefixed_name = '.'.join([prefix, name]) else: prefixed_name = name return _import_by_name(prefixed_name), prefixed_name except ImportError: pass raise ImportError def _import_by_name(name): """Import a Python object given its full name""" try: # try first interpret `name` as MODNAME.OBJ name_parts = name.split('.') try: modname = '.'.join(name_parts[:-1]) __import__(modname) return getattr(sys.modules[modname], name_parts[-1]) except (ImportError, IndexError, AttributeError): pass # ... then as MODNAME, MODNAME.OBJ1, MODNAME.OBJ1.OBJ2, ... last_j = 0 modname = None for j in reversed(range(1, len(name_parts)+1)): last_j = j modname = '.'.join(name_parts[:j]) try: __import__(modname) except ImportError: continue if modname in sys.modules: break if last_j < len(name_parts): obj = sys.modules[modname] for obj_name in name_parts[last_j:]: obj = getattr(obj, obj_name) return obj else: return sys.modules[modname] except (ValueError, ImportError, AttributeError, KeyError), e: raise ImportError(e) #------------------------------------------------------------------------------ # :autolink: (smart default role) #------------------------------------------------------------------------------ def autolink_role(typ, rawtext, etext, lineno, inliner, options={}, content=[]): """ Smart linking role. Expands to ":obj:`text`" if `text` is an object that can be imported; otherwise expands to "*text*". """ r = sphinx.roles.xfileref_role('obj', rawtext, etext, lineno, inliner, options, content) pnode = r[0][0] prefixes = [None] #prefixes.insert(0, inliner.document.settings.env.currmodule) try: obj, name = import_by_name(pnode['reftarget'], prefixes) except ImportError: content = pnode[0] r[0][0] = nodes.emphasis(rawtext, content[0].astext(), classes=content['classes']) return r
Python
#!/usr/bin/env python r""" autosummary_generate.py OPTIONS FILES Generate automatic RST source files for items referred to in autosummary:: directives. Each generated RST file contains a single auto*:: directive which extracts the docstring of the referred item. Example Makefile rule:: generate: ./ext/autosummary_generate.py -o source/generated source/*.rst """ import glob, re, inspect, os, optparse, pydoc from autosummary import import_by_name try: from phantom_import import import_phantom_module except ImportError: import_phantom_module = lambda x: x def main(): p = optparse.OptionParser(__doc__.strip()) p.add_option("-p", "--phantom", action="store", type="string", dest="phantom", default=None, help="Phantom import modules from a file") p.add_option("-o", "--output-dir", action="store", type="string", dest="output_dir", default=None, help=("Write all output files to the given directory (instead " "of writing them as specified in the autosummary:: " "directives)")) options, args = p.parse_args() if len(args) == 0: p.error("wrong number of arguments") if options.phantom and os.path.isfile(options.phantom): import_phantom_module(options.phantom) # read names = {} for name, loc in get_documented(args).items(): for (filename, sec_title, keyword, toctree) in loc: if toctree is not None: path = os.path.join(os.path.dirname(filename), toctree) names[name] = os.path.abspath(path) # write for name, path in sorted(names.items()): if options.output_dir is not None: path = options.output_dir if not os.path.isdir(path): os.makedirs(path) try: obj, name = import_by_name(name) except ImportError, e: print "Failed to import '%s': %s" % (name, e) continue fn = os.path.join(path, '%s.rst' % name) if os.path.exists(fn): # skip continue f = open(fn, 'w') try: f.write('%s\n%s\n\n' % (name, '='*len(name))) if inspect.isclass(obj): if issubclass(obj, Exception): f.write(format_modulemember(name, 'autoexception')) else: f.write(format_modulemember(name, 'autoclass')) elif inspect.ismodule(obj): f.write(format_modulemember(name, 'automodule')) elif inspect.ismethod(obj) or inspect.ismethoddescriptor(obj): f.write(format_classmember(name, 'automethod')) elif callable(obj): f.write(format_modulemember(name, 'autofunction')) elif hasattr(obj, '__get__'): f.write(format_classmember(name, 'autoattribute')) else: f.write(format_modulemember(name, 'autofunction')) finally: f.close() def format_modulemember(name, directive): parts = name.split('.') mod, name = '.'.join(parts[:-1]), parts[-1] return ".. currentmodule:: %s\n\n.. %s:: %s\n" % (mod, directive, name) def format_classmember(name, directive): parts = name.split('.') mod, name = '.'.join(parts[:-2]), '.'.join(parts[-2:]) return ".. currentmodule:: %s\n\n.. %s:: %s\n" % (mod, directive, name) def get_documented(filenames): """ Find out what items are documented in source/*.rst See `get_documented_in_lines`. """ documented = {} for filename in filenames: f = open(filename, 'r') lines = f.read().splitlines() documented.update(get_documented_in_lines(lines, filename=filename)) f.close() return documented def get_documented_in_docstring(name, module=None, filename=None): """ Find out what items are documented in the given object's docstring. See `get_documented_in_lines`. """ try: obj, real_name = import_by_name(name) lines = pydoc.getdoc(obj).splitlines() return get_documented_in_lines(lines, module=name, filename=filename) except AttributeError: pass except ImportError, e: print "Failed to import '%s': %s" % (name, e) return {} def get_documented_in_lines(lines, module=None, filename=None): """ Find out what items are documented in the given lines Returns ------- documented : dict of list of (filename, title, keyword, toctree) Dictionary whose keys are documented names of objects. The value is a list of locations where the object was documented. Each location is a tuple of filename, the current section title, the name of the directive, and the value of the :toctree: argument (if present) of the directive. """ title_underline_re = re.compile("^[-=*_^#]{3,}\s*$") autodoc_re = re.compile(".. auto(function|method|attribute|class|exception|module)::\s*([A-Za-z0-9_.]+)\s*$") autosummary_re = re.compile(r'^\.\.\s+autosummary::\s*') module_re = re.compile(r'^\.\.\s+(current)?module::\s*([a-zA-Z0-9_.]+)\s*$') autosummary_item_re = re.compile(r'^\s+([_a-zA-Z][a-zA-Z0-9_.]*)\s*.*?') toctree_arg_re = re.compile(r'^\s+:toctree:\s*(.*?)\s*$') documented = {} current_title = [] last_line = None toctree = None current_module = module in_autosummary = False for line in lines: try: if in_autosummary: m = toctree_arg_re.match(line) if m: toctree = m.group(1) continue if line.strip().startswith(':'): continue # skip options m = autosummary_item_re.match(line) if m: name = m.group(1).strip() if current_module and not name.startswith(current_module + '.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, 'autosummary', toctree)) continue if line.strip() == '': continue in_autosummary = False m = autosummary_re.match(line) if m: in_autosummary = True continue m = autodoc_re.search(line) if m: name = m.group(2).strip() if m.group(1) == "module": current_module = name documented.update(get_documented_in_docstring( name, filename=filename)) elif current_module and not name.startswith(current_module+'.'): name = "%s.%s" % (current_module, name) documented.setdefault(name, []).append( (filename, current_title, "auto" + m.group(1), None)) continue m = title_underline_re.match(line) if m and last_line: current_title = last_line.strip() continue m = module_re.match(line) if m: current_module = m.group(2) continue finally: last_line = line return documented if __name__ == "__main__": main()
Python
from distutils.core import setup import setuptools import sys, os version = "0.2.dev" setup( name="numpydoc", packages=["numpydoc"], package_dir={"numpydoc": ""}, version=version, description="Sphinx extension to support docstrings in Numpy format", # classifiers from http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=["Development Status :: 3 - Alpha", "Environment :: Plugins", "License :: OSI Approved :: BSD License", "Topic :: Documentation"], keywords="sphinx numpy", author="Pauli Virtanen and others", author_email="pav@iki.fi", url="http://projects.scipy.org/numpy/browser/trunk/doc/sphinxext", license="BSD", zip_safe=False, install_requires=["Sphinx >= 0.5"], package_data={'numpydoc': 'tests'}, entry_points={ "console_scripts": [ "autosummary_generate = numpydoc.autosummary_generate:main", ], }, )
Python
""" Turn compiler.ast structures back into executable python code. The unparse method takes a compiler.ast tree and transforms it back into valid python code. It is incomplete and currently only works for import statements, function calls, function definitions, assignments, and basic expressions. Inspired by python-2.5-svn/Demo/parser/unparse.py fixme: We may want to move to using _ast trees because the compiler for them is about 6 times faster than compiler.compile. """ import sys import cStringIO from compiler.ast import Const, Name, Tuple, Div, Mul, Sub, Add def unparse(ast, single_line_functions=False): s = cStringIO.StringIO() UnparseCompilerAst(ast, s, single_line_functions) return s.getvalue().lstrip() op_precedence = { 'compiler.ast.Power':3, 'compiler.ast.Mul':2, 'compiler.ast.Div':2, 'compiler.ast.Add':1, 'compiler.ast.Sub':1 } class UnparseCompilerAst: """ Methods in this class recursively traverse an AST and output source code for the abstract syntax; original formatting is disregarged. """ ######################################################################### # object interface. ######################################################################### def __init__(self, tree, file = sys.stdout, single_line_functions=False): """ Unparser(tree, file=sys.stdout) -> None. Print the source for tree to file. """ self.f = file self._single_func = single_line_functions self._do_indent = True self._indent = 0 self._dispatch(tree) self._write("\n") self.f.flush() ######################################################################### # Unparser private interface. ######################################################################### ### format, output, and dispatch methods ################################ def _fill(self, text = ""): "Indent a piece of text, according to the current indentation level" if self._do_indent: self._write("\n"+" "*self._indent + text) else: self._write(text) def _write(self, text): "Append a piece of text to the current line." self.f.write(text) def _enter(self): "Print ':', and increase the indentation." self._write(": ") self._indent += 1 def _leave(self): "Decrease the indentation level." self._indent -= 1 def _dispatch(self, tree): "_dispatcher function, _dispatching tree type T to method _T." if isinstance(tree, list): for t in tree: self._dispatch(t) return meth = getattr(self, "_"+tree.__class__.__name__) if tree.__class__.__name__ == 'NoneType' and not self._do_indent: return meth(tree) ######################################################################### # compiler.ast unparsing methods. # # There should be one method per concrete grammar type. They are # organized in alphabetical order. ######################################################################### def _Add(self, t): self.__binary_op(t, '+') def _And(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") and (") self._write(")") def _AssAttr(self, t): """ Handle assigning an attribute of an object """ self._dispatch(t.expr) self._write('.'+t.attrname) def _Assign(self, t): """ Expression Assignment such as "a = 1". This only handles assignment in expressions. Keyword assignment is handled separately. """ self._fill() for target in t.nodes: self._dispatch(target) self._write(" = ") self._dispatch(t.expr) if not self._do_indent: self._write('; ') def _AssName(self, t): """ Name on left hand side of expression. Treat just like a name on the right side of an expression. """ self._Name(t) def _AssTuple(self, t): """ Tuple on left hand side of an expression. """ # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) def _AugAssign(self, t): """ +=,-=,*=,/=,**=, etc. operations """ self._fill() self._dispatch(t.node) self._write(' '+t.op+' ') self._dispatch(t.expr) if not self._do_indent: self._write(';') def _Bitand(self, t): """ Bit and operation. """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" & ") def _Bitor(self, t): """ Bit or operation """ for i, node in enumerate(t.nodes): self._write("(") self._dispatch(node) self._write(")") if i != len(t.nodes)-1: self._write(" | ") def _CallFunc(self, t): """ Function call. """ self._dispatch(t.node) self._write("(") comma = False for e in t.args: if comma: self._write(", ") else: comma = True self._dispatch(e) if t.star_args: if comma: self._write(", ") else: comma = True self._write("*") self._dispatch(t.star_args) if t.dstar_args: if comma: self._write(", ") else: comma = True self._write("**") self._dispatch(t.dstar_args) self._write(")") def _Compare(self, t): self._dispatch(t.expr) for op, expr in t.ops: self._write(" " + op + " ") self._dispatch(expr) def _Const(self, t): """ A constant value such as an integer value, 3, or a string, "hello". """ self._dispatch(t.value) def _Decorators(self, t): """ Handle function decorators (eg. @has_units) """ for node in t.nodes: self._dispatch(node) def _Dict(self, t): self._write("{") for i, (k, v) in enumerate(t.items): self._dispatch(k) self._write(": ") self._dispatch(v) if i < len(t.items)-1: self._write(", ") self._write("}") def _Discard(self, t): """ Node for when return value is ignored such as in "foo(a)". """ self._fill() self._dispatch(t.expr) def _Div(self, t): self.__binary_op(t, '/') def _Ellipsis(self, t): self._write("...") def _From(self, t): """ Handle "from xyz import foo, bar as baz". """ # fixme: Are From and ImportFrom handled differently? self._fill("from ") self._write(t.modname) self._write(" import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Function(self, t): """ Handle function definitions """ if t.decorators is not None: self._fill("@") self._dispatch(t.decorators) self._fill("def "+t.name + "(") defaults = [None] * (len(t.argnames) - len(t.defaults)) + list(t.defaults) for i, arg in enumerate(zip(t.argnames, defaults)): self._write(arg[0]) if arg[1] is not None: self._write('=') self._dispatch(arg[1]) if i < len(t.argnames)-1: self._write(', ') self._write(")") if self._single_func: self._do_indent = False self._enter() self._dispatch(t.code) self._leave() self._do_indent = True def _Getattr(self, t): """ Handle getting an attribute of an object """ if isinstance(t.expr, (Div, Mul, Sub, Add)): self._write('(') self._dispatch(t.expr) self._write(')') else: self._dispatch(t.expr) self._write('.'+t.attrname) def _If(self, t): self._fill() for i, (compare,code) in enumerate(t.tests): if i == 0: self._write("if ") else: self._write("elif ") self._dispatch(compare) self._enter() self._fill() self._dispatch(code) self._leave() self._write("\n") if t.else_ is not None: self._write("else") self._enter() self._fill() self._dispatch(t.else_) self._leave() self._write("\n") def _IfExp(self, t): self._dispatch(t.then) self._write(" if ") self._dispatch(t.test) if t.else_ is not None: self._write(" else (") self._dispatch(t.else_) self._write(")") def _Import(self, t): """ Handle "import xyz.foo". """ self._fill("import ") for i, (name,asname) in enumerate(t.names): if i != 0: self._write(", ") self._write(name) if asname is not None: self._write(" as "+asname) def _Keyword(self, t): """ Keyword value assignment within function calls and definitions. """ self._write(t.name) self._write("=") self._dispatch(t.expr) def _List(self, t): self._write("[") for i,node in enumerate(t.nodes): self._dispatch(node) if i < len(t.nodes)-1: self._write(", ") self._write("]") def _Module(self, t): if t.doc is not None: self._dispatch(t.doc) self._dispatch(t.node) def _Mul(self, t): self.__binary_op(t, '*') def _Name(self, t): self._write(t.name) def _NoneType(self, t): self._write("None") def _Not(self, t): self._write('not (') self._dispatch(t.expr) self._write(')') def _Or(self, t): self._write(" (") for i, node in enumerate(t.nodes): self._dispatch(node) if i != len(t.nodes)-1: self._write(") or (") self._write(")") def _Pass(self, t): self._write("pass\n") def _Printnl(self, t): self._fill("print ") if t.dest: self._write(">> ") self._dispatch(t.dest) self._write(", ") comma = False for node in t.nodes: if comma: self._write(', ') else: comma = True self._dispatch(node) def _Power(self, t): self.__binary_op(t, '**') def _Return(self, t): self._fill("return ") if t.value: if isinstance(t.value, Tuple): text = ', '.join([ name.name for name in t.value.asList() ]) self._write(text) else: self._dispatch(t.value) if not self._do_indent: self._write('; ') def _Slice(self, t): self._dispatch(t.expr) self._write("[") if t.lower: self._dispatch(t.lower) self._write(":") if t.upper: self._dispatch(t.upper) #if t.step: # self._write(":") # self._dispatch(t.step) self._write("]") def _Sliceobj(self, t): for i, node in enumerate(t.nodes): if i != 0: self._write(":") if not (isinstance(node, Const) and node.value is None): self._dispatch(node) def _Stmt(self, tree): for node in tree.nodes: self._dispatch(node) def _Sub(self, t): self.__binary_op(t, '-') def _Subscript(self, t): self._dispatch(t.expr) self._write("[") for i, value in enumerate(t.subs): if i != 0: self._write(",") self._dispatch(value) self._write("]") def _TryExcept(self, t): self._fill("try") self._enter() self._dispatch(t.body) self._leave() for handler in t.handlers: self._fill('except ') self._dispatch(handler[0]) if handler[1] is not None: self._write(', ') self._dispatch(handler[1]) self._enter() self._dispatch(handler[2]) self._leave() if t.else_: self._fill("else") self._enter() self._dispatch(t.else_) self._leave() def _Tuple(self, t): if not t.nodes: # Empty tuple. self._write("()") else: self._write("(") # _write each elements, separated by a comma. for element in t.nodes[:-1]: self._dispatch(element) self._write(", ") # Handle the last one without writing comma last_element = t.nodes[-1] self._dispatch(last_element) self._write(")") def _UnaryAdd(self, t): self._write("+") self._dispatch(t.expr) def _UnarySub(self, t): self._write("-") self._dispatch(t.expr) def _With(self, t): self._fill('with ') self._dispatch(t.expr) if t.vars: self._write(' as ') self._dispatch(t.vars.name) self._enter() self._dispatch(t.body) self._leave() self._write('\n') def _int(self, t): self._write(repr(t)) def __binary_op(self, t, symbol): # Check if parenthesis are needed on left side and then dispatch has_paren = False left_class = str(t.left.__class__) if (left_class in op_precedence.keys() and op_precedence[left_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.left) if has_paren: self._write(')') # Write the appropriate symbol for operator self._write(symbol) # Check if parenthesis are needed on the right side and then dispatch has_paren = False right_class = str(t.right.__class__) if (right_class in op_precedence.keys() and op_precedence[right_class] < op_precedence[str(t.__class__)]): has_paren = True if has_paren: self._write('(') self._dispatch(t.right) if has_paren: self._write(')') def _float(self, t): # if t is 0.1, str(t)->'0.1' while repr(t)->'0.1000000000001' # We prefer str here. self._write(str(t)) def _str(self, t): self._write(repr(t)) def _tuple(self, t): self._write(str(t)) ######################################################################### # These are the methods from the _ast modules unparse. # # As our needs to handle more advanced code increase, we may want to # modify some of the methods below so that they work for compiler.ast. ######################################################################### # # stmt # def _Expr(self, tree): # self._fill() # self._dispatch(tree.value) # # def _Import(self, t): # self._fill("import ") # first = True # for a in t.names: # if first: # first = False # else: # self._write(", ") # self._write(a.name) # if a.asname: # self._write(" as "+a.asname) # ## def _ImportFrom(self, t): ## self._fill("from ") ## self._write(t.module) ## self._write(" import ") ## for i, a in enumerate(t.names): ## if i == 0: ## self._write(", ") ## self._write(a.name) ## if a.asname: ## self._write(" as "+a.asname) ## # XXX(jpe) what is level for? ## # # def _Break(self, t): # self._fill("break") # # def _Continue(self, t): # self._fill("continue") # # def _Delete(self, t): # self._fill("del ") # self._dispatch(t.targets) # # def _Assert(self, t): # self._fill("assert ") # self._dispatch(t.test) # if t.msg: # self._write(", ") # self._dispatch(t.msg) # # def _Exec(self, t): # self._fill("exec ") # self._dispatch(t.body) # if t.globals: # self._write(" in ") # self._dispatch(t.globals) # if t.locals: # self._write(", ") # self._dispatch(t.locals) # # def _Print(self, t): # self._fill("print ") # do_comma = False # if t.dest: # self._write(">>") # self._dispatch(t.dest) # do_comma = True # for e in t.values: # if do_comma:self._write(", ") # else:do_comma=True # self._dispatch(e) # if not t.nl: # self._write(",") # # def _Global(self, t): # self._fill("global") # for i, n in enumerate(t.names): # if i != 0: # self._write(",") # self._write(" " + n) # # def _Yield(self, t): # self._fill("yield") # if t.value: # self._write(" (") # self._dispatch(t.value) # self._write(")") # # def _Raise(self, t): # self._fill('raise ') # if t.type: # self._dispatch(t.type) # if t.inst: # self._write(", ") # self._dispatch(t.inst) # if t.tback: # self._write(", ") # self._dispatch(t.tback) # # # def _TryFinally(self, t): # self._fill("try") # self._enter() # self._dispatch(t.body) # self._leave() # # self._fill("finally") # self._enter() # self._dispatch(t.finalbody) # self._leave() # # def _excepthandler(self, t): # self._fill("except ") # if t.type: # self._dispatch(t.type) # if t.name: # self._write(", ") # self._dispatch(t.name) # self._enter() # self._dispatch(t.body) # self._leave() # # def _ClassDef(self, t): # self._write("\n") # self._fill("class "+t.name) # if t.bases: # self._write("(") # for a in t.bases: # self._dispatch(a) # self._write(", ") # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _FunctionDef(self, t): # self._write("\n") # for deco in t.decorators: # self._fill("@") # self._dispatch(deco) # self._fill("def "+t.name + "(") # self._dispatch(t.args) # self._write(")") # self._enter() # self._dispatch(t.body) # self._leave() # # def _For(self, t): # self._fill("for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # def _While(self, t): # self._fill("while ") # self._dispatch(t.test) # self._enter() # self._dispatch(t.body) # self._leave() # if t.orelse: # self._fill("else") # self._enter() # self._dispatch(t.orelse) # self._leave # # # expr # def _Str(self, tree): # self._write(repr(tree.s)) ## # def _Repr(self, t): # self._write("`") # self._dispatch(t.value) # self._write("`") # # def _Num(self, t): # self._write(repr(t.n)) # # def _ListComp(self, t): # self._write("[") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write("]") # # def _GeneratorExp(self, t): # self._write("(") # self._dispatch(t.elt) # for gen in t.generators: # self._dispatch(gen) # self._write(")") # # def _comprehension(self, t): # self._write(" for ") # self._dispatch(t.target) # self._write(" in ") # self._dispatch(t.iter) # for if_clause in t.ifs: # self._write(" if ") # self._dispatch(if_clause) # # def _IfExp(self, t): # self._dispatch(t.body) # self._write(" if ") # self._dispatch(t.test) # if t.orelse: # self._write(" else ") # self._dispatch(t.orelse) # # unop = {"Invert":"~", "Not": "not", "UAdd":"+", "USub":"-"} # def _UnaryOp(self, t): # self._write(self.unop[t.op.__class__.__name__]) # self._write("(") # self._dispatch(t.operand) # self._write(")") # # binop = { "Add":"+", "Sub":"-", "Mult":"*", "Div":"/", "Mod":"%", # "LShift":">>", "RShift":"<<", "BitOr":"|", "BitXor":"^", "BitAnd":"&", # "FloorDiv":"//", "Pow": "**"} # def _BinOp(self, t): # self._write("(") # self._dispatch(t.left) # self._write(")" + self.binop[t.op.__class__.__name__] + "(") # self._dispatch(t.right) # self._write(")") # # boolops = {_ast.And: 'and', _ast.Or: 'or'} # def _BoolOp(self, t): # self._write("(") # self._dispatch(t.values[0]) # for v in t.values[1:]: # self._write(" %s " % self.boolops[t.op.__class__]) # self._dispatch(v) # self._write(")") # # def _Attribute(self,t): # self._dispatch(t.value) # self._write(".") # self._write(t.attr) # ## def _Call(self, t): ## self._dispatch(t.func) ## self._write("(") ## comma = False ## for e in t.args: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## for e in t.keywords: ## if comma: self._write(", ") ## else: comma = True ## self._dispatch(e) ## if t.starargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("*") ## self._dispatch(t.starargs) ## if t.kwargs: ## if comma: self._write(", ") ## else: comma = True ## self._write("**") ## self._dispatch(t.kwargs) ## self._write(")") # # # slice # def _Index(self, t): # self._dispatch(t.value) # # def _ExtSlice(self, t): # for i, d in enumerate(t.dims): # if i != 0: # self._write(': ') # self._dispatch(d) # # # others # def _arguments(self, t): # first = True # nonDef = len(t.args)-len(t.defaults) # for a in t.args[0:nonDef]: # if first:first = False # else: self._write(", ") # self._dispatch(a) # for a,d in zip(t.args[nonDef:], t.defaults): # if first:first = False # else: self._write(", ") # self._dispatch(a), # self._write("=") # self._dispatch(d) # if t.vararg: # if first:first = False # else: self._write(", ") # self._write("*"+t.vararg) # if t.kwarg: # if first:first = False # else: self._write(", ") # self._write("**"+t.kwarg) # ## def _keyword(self, t): ## self._write(t.arg) ## self._write("=") ## self._dispatch(t.value) # # def _Lambda(self, t): # self._write("lambda ") # self._dispatch(t.args) # self._write(": ") # self._dispatch(t.body)
Python
""" ============== phantom_import ============== Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar extensions to use docstrings loaded from an XML file. This extension loads an XML file in the Pydocweb format [1] and creates a dummy module that contains the specified docstrings. This can be used to get the current docstrings from a Pydocweb instance without needing to rebuild the documented module. .. [1] http://code.google.com/p/pydocweb """ import imp, sys, compiler, types, os, inspect, re def setup(app): app.connect('builder-inited', initialize) app.add_config_value('phantom_import_file', None, True) def initialize(app): fn = app.config.phantom_import_file if (fn and os.path.isfile(fn)): print "[numpydoc] Phantom importing modules from", fn, "..." import_phantom_module(fn) #------------------------------------------------------------------------------ # Creating 'phantom' modules from an XML description #------------------------------------------------------------------------------ def import_phantom_module(xml_file): """ Insert a fake Python module to sys.modules, based on a XML file. The XML file is expected to conform to Pydocweb DTD. The fake module will contain dummy objects, which guarantee the following: - Docstrings are correct. - Class inheritance relationships are correct (if present in XML). - Function argspec is *NOT* correct (even if present in XML). Instead, the function signature is prepended to the function docstring. - Class attributes are *NOT* correct; instead, they are dummy objects. Parameters ---------- xml_file : str Name of an XML file to read """ import lxml.etree as etree object_cache = {} tree = etree.parse(xml_file) root = tree.getroot() # Sort items so that # - Base classes come before classes inherited from them # - Modules come before their contents all_nodes = dict([(n.attrib['id'], n) for n in root]) def _get_bases(node, recurse=False): bases = [x.attrib['ref'] for x in node.findall('base')] if recurse: j = 0 while True: try: b = bases[j] except IndexError: break if b in all_nodes: bases.extend(_get_bases(all_nodes[b])) j += 1 return bases type_index = ['module', 'class', 'callable', 'object'] def base_cmp(a, b): x = cmp(type_index.index(a.tag), type_index.index(b.tag)) if x != 0: return x if a.tag == 'class' and b.tag == 'class': a_bases = _get_bases(a, recurse=True) b_bases = _get_bases(b, recurse=True) x = cmp(len(a_bases), len(b_bases)) if x != 0: return x if a.attrib['id'] in b_bases: return -1 if b.attrib['id'] in a_bases: return 1 return cmp(a.attrib['id'].count('.'), b.attrib['id'].count('.')) nodes = root.getchildren() nodes.sort(base_cmp) # Create phantom items for node in nodes: name = node.attrib['id'] doc = (node.text or '').decode('string-escape') + "\n" if doc == "\n": doc = "" # create parent, if missing parent = name while True: parent = '.'.join(parent.split('.')[:-1]) if not parent: break if parent in object_cache: break obj = imp.new_module(parent) object_cache[parent] = obj sys.modules[parent] = obj # create object if node.tag == 'module': obj = imp.new_module(name) obj.__doc__ = doc sys.modules[name] = obj elif node.tag == 'class': bases = [object_cache[b] for b in _get_bases(node) if b in object_cache] bases.append(object) init = lambda self: None init.__doc__ = doc obj = type(name, tuple(bases), {'__doc__': doc, '__init__': init}) obj.__name__ = name.split('.')[-1] elif node.tag == 'callable': funcname = node.attrib['id'].split('.')[-1] argspec = node.attrib.get('argspec') if argspec: argspec = re.sub('^[^(]*', '', argspec) doc = "%s%s\n\n%s" % (funcname, argspec, doc) obj = lambda: 0 obj.__argspec_is_invalid_ = True obj.func_name = funcname obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__objclass__ = object_cache[parent] else: class Dummy(object): pass obj = Dummy() obj.__name__ = name obj.__doc__ = doc if inspect.isclass(object_cache[parent]): obj.__get__ = lambda: None object_cache[name] = obj if parent: if inspect.ismodule(object_cache[parent]): obj.__module__ = parent setattr(object_cache[parent], name.split('.')[-1], obj) # Populate items for node in root: obj = object_cache.get(node.attrib['id']) if obj is None: continue for ref in node.findall('ref'): if node.tag == 'class': if ref.attrib['ref'].startswith(node.attrib['id'] + '.'): setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref'])) else: setattr(obj, ref.attrib['name'], object_cache.get(ref.attrib['ref']))
Python
from numpydoc import setup
Python
import re, inspect, textwrap, pydoc import sphinx from docscrape import NumpyDocString, FunctionDoc, ClassDoc class SphinxDocString(NumpyDocString): # string conversion routines def _str_header(self, name, symbol='`'): return ['.. rubric:: ' + name, ''] def _str_field_list(self, name): return [':' + name + ':'] def _str_indent(self, doc, indent=4): out = [] for line in doc: out += [' '*indent + line] return out def _str_signature(self): return [''] if self['Signature']: return ['``%s``' % self['Signature']] + [''] else: return [''] def _str_summary(self): return self['Summary'] + [''] def _str_extended_summary(self): return self['Extended Summary'] + [''] def _str_param_list(self, name): out = [] if self[name]: out += self._str_field_list(name) out += [''] for param,param_type,desc in self[name]: out += self._str_indent(['**%s** : %s' % (param.strip(), param_type)]) out += [''] out += self._str_indent(desc,8) out += [''] return out def _str_section(self, name): out = [] if self[name]: out += self._str_header(name) out += [''] content = textwrap.dedent("\n".join(self[name])).split("\n") out += content out += [''] return out def _str_see_also(self, func_role): out = [] if self['See Also']: see_also = super(SphinxDocString, self)._str_see_also(func_role) out = ['.. seealso::', ''] out += self._str_indent(see_also[2:]) return out def _str_warnings(self): out = [] if self['Warnings']: out = ['.. warning::', ''] out += self._str_indent(self['Warnings']) return out def _str_index(self): idx = self['index'] out = [] if len(idx) == 0: return out out += ['.. index:: %s' % idx.get('default','')] for section, references in idx.iteritems(): if section == 'default': continue elif section == 'refguide': out += [' single: %s' % (', '.join(references))] else: out += [' %s: %s' % (section, ','.join(references))] return out def _str_references(self): out = [] if self['References']: out += self._str_header('References') if isinstance(self['References'], str): self['References'] = [self['References']] out.extend(self['References']) out += [''] # Latex collects all references to a separate bibliography, # so we need to insert links to it if sphinx.__version__ >= 0.6: out += ['.. only:: latex',''] else: out += ['.. latexonly::',''] items = [] for line in self['References']: m = re.match(r'.. \[([a-z0-9._-]+)\]', line, re.I) if m: items.append(m.group(1)) out += [' ' + ", ".join(["[%s]_" % item for item in items]), ''] return out def __str__(self, indent=0, func_role="obj"): out = [] out += self._str_signature() out += self._str_index() + [''] out += self._str_summary() out += self._str_extended_summary() for param_list in ('Parameters', 'Attributes', 'Methods', 'Returns','Raises'): out += self._str_param_list(param_list) out += self._str_warnings() out += self._str_see_also(func_role) out += self._str_section('Notes') out += self._str_references() out += self._str_section('Examples') out = self._str_indent(out,indent) return '\n'.join(out) class SphinxFunctionDoc(SphinxDocString, FunctionDoc): pass class SphinxClassDoc(SphinxDocString, ClassDoc): pass def get_doc_object(obj, what=None, doc=None): if what is None: if inspect.isclass(obj): what = 'class' elif inspect.ismodule(obj): what = 'module' elif callable(obj): what = 'function' else: what = 'object' if what == 'class': return SphinxClassDoc(obj, '', func_doc=SphinxFunctionDoc, doc=doc) elif what in ('function', 'method'): return SphinxFunctionDoc(obj, '', doc=doc) else: if doc is None: doc = pydoc.getdoc(obj) return SphinxDocString(doc)
Python
""" ======== numpydoc ======== Sphinx extension that handles docstrings in the Numpy standard format. [1] It will: - Convert Parameters etc. sections to field lists. - Convert See Also section to a See also entry. - Renumber references. - Extract the signature from the docstring, if it can't be determined otherwise. .. [1] http://projects.scipy.org/numpy/wiki/CodingStyleGuidelines#docstring-standard """ import os, re, pydoc from docscrape_sphinx import get_doc_object, SphinxDocString import inspect def mangle_docstrings(app, what, name, obj, options, lines, reference_offset=[0]): if what == 'module': # Strip top title title_re = re.compile(r'^\s*[#*=]{4,}\n[a-z0-9 -]+\n[#*=]{4,}\s*', re.I|re.S) lines[:] = title_re.sub('', "\n".join(lines)).split("\n") else: doc = get_doc_object(obj, what, "\n".join(lines)) lines[:] = str(doc).split("\n") if app.config.numpydoc_edit_link and hasattr(obj, '__name__') and \ obj.__name__: if hasattr(obj, '__module__'): v = dict(full_name="%s.%s" % (obj.__module__, obj.__name__)) else: v = dict(full_name=obj.__name__) lines += ['', '.. htmlonly::', ''] lines += [' %s' % x for x in (app.config.numpydoc_edit_link % v).split("\n")] # replace reference numbers so that there are no duplicates references = [] for line in lines: line = line.strip() m = re.match(r'^.. \[([a-z0-9_.-])\]', line, re.I) if m: references.append(m.group(1)) # start renaming from the longest string, to avoid overwriting parts references.sort(key=lambda x: -len(x)) if references: for i, line in enumerate(lines): for r in references: if re.match(r'^\d+$', r): new_r = "R%d" % (reference_offset[0] + int(r)) else: new_r = "%s%d" % (r, reference_offset[0]) lines[i] = lines[i].replace('[%s]_' % r, '[%s]_' % new_r) lines[i] = lines[i].replace('.. [%s]' % r, '.. [%s]' % new_r) reference_offset[0] += len(references) def mangle_signature(app, what, name, obj, options, sig, retann): # Do not try to inspect classes that don't define `__init__` if (inspect.isclass(obj) and 'initializes x; see ' in pydoc.getdoc(obj.__init__)): return '', '' if not (callable(obj) or hasattr(obj, '__argspec_is_invalid_')): return if not hasattr(obj, '__doc__'): return doc = SphinxDocString(pydoc.getdoc(obj)) if doc['Signature']: sig = re.sub("^[^(]*", "", doc['Signature']) return sig, '' def initialize(app): try: app.connect('autodoc-process-signature', mangle_signature) except: monkeypatch_sphinx_ext_autodoc() def setup(app, get_doc_object_=get_doc_object): global get_doc_object get_doc_object = get_doc_object_ app.connect('autodoc-process-docstring', mangle_docstrings) app.connect('builder-inited', initialize) app.add_config_value('numpydoc_edit_link', None, True) #------------------------------------------------------------------------------ # Monkeypatch sphinx.ext.autodoc to accept argspecless autodocs (Sphinx < 0.5) #------------------------------------------------------------------------------ def monkeypatch_sphinx_ext_autodoc(): global _original_format_signature import sphinx.ext.autodoc if sphinx.ext.autodoc.format_signature is our_format_signature: return print "[numpydoc] Monkeypatching sphinx.ext.autodoc ..." _original_format_signature = sphinx.ext.autodoc.format_signature sphinx.ext.autodoc.format_signature = our_format_signature def our_format_signature(what, obj): r = mangle_signature(None, what, None, obj, None, None, None) if r is not None: return r[0] else: return _original_format_signature(what, obj)
Python
# -*- coding: utf-8 -*- # default_application, default_controller, default_function # are used when the respective element is missing from the # (possibly rewritten) incoming URL # default_application = 'init' # ordinarily set in base routes.py default_controller = 'default' # ordinarily set in app-specific routes.py default_function = 'index' # ordinarily set in app-specific routes.py # routes_app is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # an applicationname. This mechanism allows you to specify the use of an # app-specific routes.py. This entry is meaningful only in the base routes.py. # # Example: support welcome, admin, app and myapp, with myapp the default: routes_app = ((r'/(?P<app>welcome|admin|app)\b.*', r'\g<app>'), (r'(.*)', r'myapp'), (r'/?(.*)', r'myapp')) # routes_in is a tuple of tuples. The first item in each is a regexp that will # be used to match the incoming request URL. The second item in the tuple is # what it will be replaced with. This mechanism allows you to redirect incoming # routes to different web2py locations # # Example: If you wish for your entire website to use init's static directory: # # routes_in=( (r'/static/(?P<file>[\w./-]+)', r'/init/static/\g<file>') ) # BASE = '' # optonal prefix for incoming URLs routes_in = ( # do not reroute admin unless you want to disable it (BASE + '/admin', '/admin/default/index'), (BASE + '/admin/$anything', '/admin/$anything'), # do not reroute appadmin unless you want to disable it (BASE + '/$app/appadmin', '/$app/appadmin/index'), (BASE + '/$app/appadmin/$anything', '/$app/appadmin/$anything'), # do not reroute static files (BASE + '/$app/static/$anything', '/$app/static/$anything'), # reroute favicon and robots, use exable for lack of better choice ('/favicon.ico', '/examples/static/favicon.ico'), ('/robots.txt', '/examples/static/robots.txt'), # do other stuff ((r'.*http://otherdomain.com.* (?P<any>.*)', r'/app/ctr\g<any>')), # remove the BASE prefix (BASE + '/$anything', '/$anything'), ) # routes_out, like routes_in translates URL paths created with the web2py URL() # function in the same manner that route_in translates inbound URL paths. # routes_out = ( # do not reroute admin unless you want to disable it ('/admin/$anything', BASE + '/admin/$anything'), # do not reroute appadmin unless you want to disable it ('/$app/appadmin/$anything', BASE + '/$app/appadmin/$anything'), # do not reroute static files ('/$app/static/$anything', BASE + '/$app/static/$anything'), # do other stuff (r'.*http://otherdomain.com.* /app/ctr(?P<any>.*)', r'\g<any>'), (r'/app(?P<any>.*)', r'\g<any>'), # restore the BASE prefix ('/$anything', BASE + '/$anything'), ) # Specify log level for rewrite's debug logging # Possible values: debug, info, warning, error, critical (loglevels), # off, print (print uses print statement rather than logging) # GAE users may want to use 'off' to suppress routine logging. # logging = 'debug' # Error-handling redirects all HTTP errors (status codes >= 400) to a specified # path. If you wish to use error-handling redirects, uncomment the tuple # below. You can customize responses by adding a tuple entry with the first # value in 'appName/HTTPstatusCode' format. ( Only HTTP codes >= 400 are # routed. ) and the value as a path to redirect the user to. You may also use # '*' as a wildcard. # # The error handling page is also passed the error code and ticket as # variables. Traceback information will be stored in the ticket. # # routes_onerror = [ # (r'init/400', r'/init/default/login') # ,(r'init/*', r'/init/static/fail.html') # ,(r'*/404', r'/init/static/cantfind.html') # ,(r'*/*', r'/init/error/index') # ] # specify action in charge of error handling # # error_handler = dict(application='error', # controller='default', # function='index') # In the event that the error-handling page itself returns an error, web2py will # fall back to its old static responses. You can customize them here. # ErrorMessageTicket takes a string format dictionary containing (only) the # "ticket" key. # error_message = '<html><body><h1>%s</h1></body></html>' # error_message_ticket = '<html><body><h1>Internal error</h1>Ticket issued: <a href="/admin/default/ticket/%(ticket)s" target="_blank">%(ticket)s</a></body></html>' # specify a list of apps that bypass args-checking and use request.raw_args # #routes_apps_raw=['myapp'] #routes_apps_raw=['myapp', 'myotherapp'] def __routes_doctest(): ''' Dummy function for doctesting routes.py. Use filter_url() to test incoming or outgoing routes; filter_err() for error redirection. filter_url() accepts overrides for method and remote host: filter_url(url, method='get', remote='0.0.0.0', out=False) filter_err() accepts overrides for application and ticket: filter_err(status, application='app', ticket='tkt') >>> import os >>> import gluon.main >>> from gluon.rewrite import regex_select, load, filter_url, regex_filter_out, filter_err, compile_regex >>> regex_select() >>> load(routes=os.path.basename(__file__)) >>> os.path.relpath(filter_url('http://domain.com/favicon.ico')) 'applications/examples/static/favicon.ico' >>> os.path.relpath(filter_url('http://domain.com/robots.txt')) 'applications/examples/static/robots.txt' >>> filter_url('http://domain.com') '/init/default/index' >>> filter_url('http://domain.com/') '/init/default/index' >>> filter_url('http://domain.com/init/default/fcn') '/init/default/fcn' >>> filter_url('http://domain.com/init/default/fcn/') '/init/default/fcn' >>> filter_url('http://domain.com/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn/arg1') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1/') "/app/ctr/fcn ['arg1']" >>> filter_url('http://domain.com/app/ctr/fcn/arg1//') "/app/ctr/fcn ['arg1', '']" >>> filter_url('http://domain.com/app/ctr/fcn//arg1') "/app/ctr/fcn ['', 'arg1']" >>> filter_url('HTTP://DOMAIN.COM/app/ctr/fcn') '/app/ctr/fcn' >>> filter_url('http://domain.com/app/ctr/fcn?query') '/app/ctr/fcn ?query' >>> filter_url('http://otherdomain.com/fcn') '/app/ctr/fcn' >>> regex_filter_out('/app/ctr/fcn') '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn', out=True) '/ctr/fcn' >>> filter_url('https://otherdomain.com/app/ctr/fcn/arg1//', out=True) '/ctr/fcn/arg1//' >>> filter_url('http://otherdomain.com/app/ctr/fcn', out=True) '/fcn' >>> filter_url('http://otherdomain.com/app/ctr/fcn?query', out=True) '/fcn?query' >>> filter_url('http://otherdomain.com/app/ctr/fcn#anchor', out=True) '/fcn#anchor' >>> filter_err(200) 200 >>> filter_err(399) 399 >>> filter_err(400) 400 >>> filter_url('http://domain.com/welcome', app=True) 'welcome' >>> filter_url('http://domain.com/', app=True) 'myapp' >>> filter_url('http://domain.com', app=True) 'myapp' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[0].pattern '^.*http://otherdomain.com.* (?P<any>.*)$' >>> compile_regex('.*http://otherdomain.com.* (?P<any>.*)', '/app/ctr\g<any>')[1] '/app/ctr\\\\g<any>' >>> compile_regex('/$c/$f', '/init/$c/$f')[0].pattern '^.*?:https?://[^:/]+:[a-z]+ /(?P<c>\\\\w+)/(?P<f>\\\\w+)$' >>> compile_regex('/$c/$f', '/init/$c/$f')[1] '/init/\\\\g<c>/\\\\g<f>' ''' pass if __name__ == '__main__': import doctest doctest.testmod()
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys if '__file__' in globals(): path = os.path.dirname(os.path.abspath(__file__)) elif hasattr(sys, 'frozen'): path = os.path.dirname(os.path.abspath(sys.executable)) # for py2exe else: # should never happen path = os.getcwd() os.chdir(path) sys.path = [path] + [p for p in sys.path if not p == path] # import gluon.import_all ##### This should be uncommented for py2exe.py import gluon.widget # Start Web2py and Web2py cron service! if __name__ == '__main__': try: from multiprocessing import freeze_support freeze_support() except: sys.stderr.write('Sorry, -K only supported for python 2.6-2.7\n') if os.environ.has_key("COVERAGE_PROCESS_START"): try: import coverage coverage.process_startup() except: pass gluon.widget.start(cron=True)
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file is part of the web2py Web Framework Copyrighted by Massimo Di Pierro <mdipierro@cs.depaul.edu> License: LGPLv3 (http://www.gnu.org/licenses/lgpl.html) """ ############################################################################## # Configuration parameters for Google App Engine ############################################################################## LOG_STATS = False # web2py level log statistics APPSTATS = True # GAE level usage statistics and profiling DEBUG = False # debug mode # # Read more about APPSTATS here # http://googleappengine.blogspot.com/2010/03/easy-performance-profiling-with.html # can be accessed from: # http://localhost:8080/_ah/stats ############################################################################## # All tricks in this file developed by Robin Bhattacharyya ############################################################################## import time import os import sys import logging import cPickle import pickle import wsgiref.handlers import datetime path = os.path.dirname(os.path.abspath(__file__)) sys.path = [path] + [p for p in sys.path if not p == path] sys.modules['cPickle'] = sys.modules['pickle'] from gluon.settings import global_settings from google.appengine.ext import webapp from google.appengine.ext.webapp.util import run_wsgi_app global_settings.web2py_runtime_gae = True global_settings.db_sessions = True if os.environ.get('SERVER_SOFTWARE', '').startswith('Devel'): (global_settings.web2py_runtime, DEBUG) = \ ('gae:development', True) else: (global_settings.web2py_runtime, DEBUG) = \ ('gae:production', False) import gluon.main def log_stats(fun): """Function that will act as a decorator to make logging""" def newfun(env, res): """Log the execution time of the passed function""" timer = lambda t: (t.time(), t.clock()) (t0, c0) = timer(time) executed_function = fun(env, res) (t1, c1) = timer(time) log_info = """**** Request: %.2fms/%.2fms (real time/cpu time)""" log_info = log_info % ((t1 - t0) * 1000, (c1 - c0) * 1000) logging.info(log_info) return executed_function return newfun logging.basicConfig(level=logging.INFO) def wsgiapp(env, res): """Return the wsgiapp""" env['PATH_INFO'] = env['PATH_INFO'].decode('latin1').encode('utf8') #when using the blobstore image uploader GAE dev SDK passes these as unicode # they should be regular strings as they are parts of URLs env['wsgi.url_scheme'] = str(env['wsgi.url_scheme']) env['QUERY_STRING'] = str(env['QUERY_STRING']) env['SERVER_NAME'] = str(env['SERVER_NAME']) #this deals with a problem where GAE development server seems to forget # the path between requests if global_settings.web2py_runtime == 'gae:development': gluon.admin.create_missing_folders() web2py_path = global_settings.applications_parent # backward compatibility return gluon.main.wsgibase(env, res) if LOG_STATS or DEBUG: wsgiapp = log_stats(wsgiapp) def main(): """Run the wsgi app""" run_wsgi_app(wsgiapp) if __name__ == '__main__': main()
Python
import logging logger = logging.getLogger('x90-analyze') logger.setLevel(logging.DEBUG) # File Handler hdlr = logging.FileHandler('logs/run.log') formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) hdlr.setLevel(logging.DEBUG) # Stream handler ch = logging.StreamHandler() formatter = logging.Formatter('[%(levelname)s] %(message)s') ch.setFormatter(formatter) logger.addHandler(ch) ch.setLevel(logging.INFO) def printerror (msg): logger.error(msg) def printwarning (msg): logger.warning(msg) def printinfo (msg): logger.info(msg)
Python
import os import re import shutil import commands import _mysql import hashlib import logger # Analyze project. def analyze_metrics(project, revision, url, db, folder): analyze_code_metrics(project, revision, url, db, folder) analyze_filemetrics(project, revision, url, db, folder) # Get code metrics: def analyze_code_metrics(project, revision, url, db, folder): logger.printinfo("Analyzing code") phand = os.popen("cloc "+folder) # read output from the command while 1: line = phand.readline() if line == "": break # Find the sum of the code calculations with regex. m = re.search('SUM:.*?(?P<FILES>[0-9]+).*? (?P<BLANK>[0-9]+).*? (?P<COMMENT>[0-9]+).*? (?P<CODE>[0-9]+)', line) if m is not None: files = m.group("FILES") blank = m.group("BLANK") comment = m.group("COMMENT") code = m.group("CODE") db.insertmetric(project, revision, url, files, blank, comment, code) phand.close() return phand.close() return # Code metrics by file: def analyze_filemetrics (project, revision, url, db, folder): logger.printinfo("Analyzing files") phand = os.popen("cloc --by-file --sql=1 " + folder) # read output from the command while 1: line = phand.readline() if line == "": break m = re.search('\',\ \'(?P<LANG>.*?)\',\ \'(?P<FILE>.*?)\',\ (?P<BLANK>[0-9]+),\ (?P<COMMENT>[0-9]+),\ (?P<CODE>[0-9]+),\ ', line) if m is not None: filename = m.group("FILE"); blank = m.group("BLANK"); comment = m.group("COMMENT"); code = m.group("CODE"); lang = m.group("LANG"); db.insertfilemetric(project, revision, url, filename, blank, comment, code, lang) phand.close()
Python
import _mysql import logger import hashlib class DbHandler: ## ## Ansluter till databas of verifierar att tabellerna finns. ## Om de inte finns, skapa dem.. ## def __init__(self, pSettings): # Connect to database: try: self.db=_mysql.connect(host=pSettings.host, user=pSettings.username, passwd=pSettings.password, db=pSettings.schema) # Verifiera att tabeller finns. self.db.query("SELECT * FROM project LIMIT 1") self.db.use_result(); self.db.query("SELECT * FROM log LIMIT 1") self.db.use_result(); self.db.query("SELECT * FROM metric LIMIT 1") self.db.use_result(); return None; except _mysql.Error, e: if e.args[0] == 1146: # Skapa tabell logger.printerror("No tables found. Create tables first!") logger.printerror("The SQL code to create tables is in sql/tables.sql") exit(); if e.args[0] == 2005: logger.printerror("Fel: Kunde inte ansluta till: "+pHost) exit(); if e.args[0] == 1045: logger.printerror("[E] Invalid username/password!"+pHost) exit(); if e.args[0] == 1049: logger.printerror("[E] The schema doesnt exists!\r\nCreate it in mysql first.") exit(); else: logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1])) exit(); # Insert project to database def insertproject(self, name, type): try: self.db.query("insert into project (name, type) VALUES ('"+name+"','"+type+"')") except _mysql.Error, e: if e.args[0] == 1062: logger.printinfo("[!] Projektet "+name+" finns redan, analyzerar det igen!") else: logger.printerror("[E] Error %d: %s" % (e.args[0],e.args[1])) return; # Insert to scmlog def insertscmlog(self, project, url, rev, user, date): # Insert into database and notify user. try: self.db.query("insert into log (project, url, rev, user, date) VALUES ('"+project+"','"+url+"','"+rev+"','"+user+"','"+date+"')") logger.printinfo("New revision "+rev) except _mysql.Error, e: if e.args[0] != 1062: # Ignorerar duplicate fel. print "Error %d: %s" % (e.args[0],e.args[1]) def fetchrevisonstoanalyze(self, project, url): # Get the first revision each month and check if its been analyzed! self.db.query("select revs.foundrev as rev, (Select 1 from metric where metric.rev=revs.foundrev and revs.url=metric.url and revs.project=metric.project limit 1) as analyzed from (SELECT log.url,log.project, ( select c.rev from log as c where c.project=log.project and c.date= min(log.date) limit 1) as foundrev FROM `log` where project='"+project+"' and url='"+url+"' group by date_format(date,'%Y%m') order by date desc) as revs") r = self.db.store_result() revisions = r.fetch_row(10000) revs = [] for row in revisions: revision = row[0] analyzed = row[1] if(analyzed is None): revs.append(revision) return revs # Insert metric def insertmetric(self, project, revision, url, files, blank, comment, code): self.db.query("insert into metric (files, blank, comment, code, rev, url, project) VALUES ('" +files+"','"+blank+"','"+comment+"','"+code+"','"+revision+"','"+url+"','"+project+"')"); # Insert filemetric def insertfilemetric(self, project, revision, url, filename, blank, comment, code, lang): try: # Because of the limited key size in mysql, Generate a md5 hash as filename id: md5name = hashlib.md5( filename ).hexdigest(); self.db.query("insert into filemetric (project, rev,url, file, blank, comment, code, lang, md5) VALUES ('" +project+"','"+revision+"','"+url+"','"+filename+"','"+blank+"','"+comment +"','"+code+"','"+lang+"','"+md5name+"')"); except UnboundLocalError, e: print e except _mysql.Error, e: print "Error %d: %s" % (e.args[0],e.args[1])
Python
## ## Mercurial-analyzer ## ## Todo: skriv om... from xml.dom import minidom import logger ## Parses a dom file def parsedom(file): try: dom = minidom.parse(file) except Exception: logger.printerror("Failed to parse the xml file " + file); exit() return dom class Project: name="-noname-" type="svn" urls = [] def getprojects (file = 'settings/projects.xml'): projects = []; dom = parsedom(file) logger.printinfo("Parsing project-settings") try: for node in dom.getElementsByTagName('project'): proj = Project(); tmp = []; for xnode in node.getElementsByTagName("name"): proj.name = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("type"): proj.type = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("url"): tmp.append(xnode.firstChild.wholeText); proj.urls = tmp; projects.append(proj); except Exception: logger.printerror("Malformed xml elements") exit() return projects; class DbSettings: host="" username="" password="" schema="" def getdbsettings (file = 'settings/db.xml'): logger.printinfo("Parsing database-settings") dom = parsedom(file) dbsetting = DbSettings() try: for node in dom.getElementsByTagName('database'): for xnode in node.getElementsByTagName("host"): dbsetting.host = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("username"): dbsetting.username = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("password"): dbsetting.password = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("schema"): dbsetting.schema = xnode.firstChild.wholeText except Exception: logger.printerror("Malformed xml elements") exit() # Validate, or atleast check that variables have been changed... if(dbsetting.host==""): logger.printerror("Missing host") exit() if(dbsetting.username==""): logger.printerror("Missing username") exit() if(dbsetting.password==""): logger.printerror("Missing password") exit() if(dbsetting.schema==""): logger.printerror("Missing schema") exit() return dbsetting; class Type: name="-noname-" changelog="" regex="" checkout="" def gettypes (file = 'settings/types.xml'): types = {}; dom = parsedom(file) logger.printinfo("Parsing supported vcs info") try: for node in dom.getElementsByTagName('type'): proj = Type(); for xnode in node.getElementsByTagName("name"): proj.name = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("changelog"): proj.changelog = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("regex"): proj.regex = xnode.firstChild.wholeText for xnode in node.getElementsByTagName("checkout"): proj.checkout = xnode.firstChild.wholeText types[proj.name]=proj; except Exception: logger.printerror("Malformed xml elements") exit() return types;
Python
import os import sys import re import shutil import commands import _mysql import logger import metrics # Find and insert commits to database def analyze_scmlog(project, url, vcsinfo, db): logger.printinfo("Getting changelog from vcs") if os.path.exists ('/tmp/x90analy'): shutil.rmtree("/tmp/x90analy") # Checkout first version first to collect activity data. logger.printinfo("Cloning latest version of repo, to get changeset ") # prepare cmd cmd = vcsinfo.changelog.replace("@[url]", url); cmd = cmd.replace("@[workdir]", "/tmp/x90analy"); phand = os.popen(cmd) # read and parse output from the command while 1: line = phand.readline() if line == "": break # Match with regex. m = re.search(vcsinfo.regex, line) if m is not None: rev = m.group("REV") user = m.group("AUTHOR") date = m.group("YEAR")+"-"+m.group("MONTH")+"-"+m.group("DAY") db.insertscmlog(project.name, url, rev, user, date) phand.close() # Analyze code of revisions (the last one each month) def analyze_revisions(project, url, vcsinfo, db): logger.printinfo("Analyzing code") revisions = db.fetchrevisonstoanalyze(project.name, url) for revision in revisions: logger.printinfo("\t[+] Checking out rev: "+revision) # prepare cmd cmd = vcsinfo.checkout.replace("@[rev]", revision); cmd = cmd.replace("@[workdir]", "/tmp/x90analy"); # check it out! phand = os.popen(cmd) while 1: line = phand.readline() if line == "": break phand.close() metrics.analyze_metrics(project.name, revision, url, db, "/tmp/x90analy") def analyze_project(project, vcsinfo, db): logger.printinfo("Analyzing:"+project.name); # Add project to database. db.insertproject(project.name, project.type); for url in project.urls: # Get revisions: analyze_scmlog(project, url, vcsinfo, db); # Analyze revisions: analyze_revisions(project, url, vcsinfo, db);
Python
## ## mercurial-analyzer ## ## Requires: Cloc (sudo apt-get install cloc) import analyzelib import settingsreader from database import DbHandler import logger def getType(types, name): try: ret = types[name]; return ret except Exception: logger.printerror("Missing type "+name) exit(); logger.printinfo("\t------------------------") logger.printinfo("\t 0x90-analyzer ") logger.printinfo("\t------------------------") # Connect to mysql-db with settings from settings.xml dbsettings = settingsreader.getdbsettings() db = DbHandler(dbsettings) types = settingsreader.gettypes() # Find and analyze projects from settings.xml projects = settingsreader.getprojects() for project in projects: type = getType(types, project.type); analyzelib.analyze_project(project, type, db) logger.printinfo("Done.")
Python
#==================================================================== # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ==================================================================== # # This software consists of voluntary contributions made by many # individuals on behalf of the Apache Software Foundation. For more # information on the Apache Software Foundation, please see # <http://www.apache.org/>. # import os import re import tempfile import shutil ignore_pattern = re.compile('^(.svn|target|bin|classes)') java_pattern = re.compile('^.*\.java') annot_pattern = re.compile('import org\.apache\.http\.annotation\.') def process_dir(dir): files = os.listdir(dir) for file in files: f = os.path.join(dir, file) if os.path.isdir(f): if not ignore_pattern.match(file): process_dir(f) else: if java_pattern.match(file): process_source(f) def process_source(filename): tmp = tempfile.mkstemp() tmpfd = tmp[0] tmpfile = tmp[1] try: changed = False dst = os.fdopen(tmpfd, 'w') try: src = open(filename) try: for line in src: if annot_pattern.match(line): changed = True line = line.replace('import org.apache.http.annotation.', 'import net.jcip.annotations.') dst.write(line) finally: src.close() finally: dst.close(); if changed: shutil.move(tmpfile, filename) else: os.remove(tmpfile) except: os.remove(tmpfile) process_dir('.')
Python
# coding=utf-8 # (The line above is necessary so that I can use 世界 in the # *comment* below without Python getting all bent out of shape.) # Copyright 2007-2009 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. '''Mercurial interface to codereview.appspot.com. To configure, set the following options in your repository's .hg/hgrc file. [extensions] codereview = path/to/codereview.py [codereview] server = codereview.appspot.com The server should be running Rietveld; see http://code.google.com/p/rietveld/. In addition to the new commands, this extension introduces the file pattern syntax @nnnnnn, where nnnnnn is a change list number, to mean the files included in that change list, which must be associated with the current client. For example, if change 123456 contains the files x.go and y.go, "hg diff @123456" is equivalent to"hg diff x.go y.go". ''' from mercurial import cmdutil, commands, hg, util, error, match from mercurial.node import nullrev, hex, nullid, short import os, re, time import stat import subprocess import threading from HTMLParser import HTMLParser # The standard 'json' package is new in Python 2.6. # Before that it was an external package named simplejson. try: # Standard location in 2.6 and beyond. import json except Exception, e: try: # Conventional name for earlier package. import simplejson as json except: try: # Was also bundled with django, which is commonly installed. from django.utils import simplejson as json except: # We give up. raise e try: hgversion = util.version() except: from mercurial.version import version as v hgversion = v.get_version() try: from mercurial.discovery import findcommonincoming except: def findcommonincoming(repo, remote): return repo.findcommonincoming(remote) # in Mercurial 1.9 the cmdutil.match and cmdutil.revpair moved to scmutil if hgversion >= '1.9': from mercurial import scmutil else: scmutil = cmdutil oldMessage = """ The code review extension requires Mercurial 1.3 or newer. To install a new Mercurial, sudo easy_install mercurial works on most systems. """ linuxMessage = """ You may need to clear your current Mercurial installation by running: sudo apt-get remove mercurial mercurial-common sudo rm -rf /etc/mercurial """ if hgversion < '1.3': msg = oldMessage if os.access("/etc/mercurial", 0): msg += linuxMessage raise util.Abort(msg) def promptyesno(ui, msg): # Arguments to ui.prompt changed between 1.3 and 1.3.1. # Even so, some 1.3.1 distributions seem to have the old prompt!?!? # What a terrible way to maintain software. try: return ui.promptchoice(msg, ["&yes", "&no"], 0) == 0 except AttributeError: return ui.prompt(msg, ["&yes", "&no"], "y") != "n" # To experiment with Mercurial in the python interpreter: # >>> repo = hg.repository(ui.ui(), path = ".") ####################################################################### # Normally I would split this into multiple files, but it simplifies # import path headaches to keep it all in one file. Sorry. import sys if __name__ == "__main__": print >>sys.stderr, "This is a Mercurial extension and should not be invoked directly." sys.exit(2) server = "codereview.appspot.com" server_url_base = None defaultcc = None contributors = {} missing_codereview = None real_rollback = None releaseBranch = None ####################################################################### # RE: UNICODE STRING HANDLING # # Python distinguishes between the str (string of bytes) # and unicode (string of code points) types. Most operations # work on either one just fine, but some (like regexp matching) # require unicode, and others (like write) require str. # # As befits the language, Python hides the distinction between # unicode and str by converting between them silently, but # *only* if all the bytes/code points involved are 7-bit ASCII. # This means that if you're not careful, your program works # fine on "hello, world" and fails on "hello, 世界". And of course, # the obvious way to be careful - use static types - is unavailable. # So the only way is trial and error to find where to put explicit # conversions. # # Because more functions do implicit conversion to str (string of bytes) # than do implicit conversion to unicode (string of code points), # the convention in this module is to represent all text as str, # converting to unicode only when calling a unicode-only function # and then converting back to str as soon as possible. def typecheck(s, t): if type(s) != t: raise util.Abort("type check failed: %s has type %s != %s" % (repr(s), type(s), t)) # If we have to pass unicode instead of str, ustr does that conversion clearly. def ustr(s): typecheck(s, str) return s.decode("utf-8") # Even with those, Mercurial still sometimes turns unicode into str # and then tries to use it as ascii. Change Mercurial's default. def set_mercurial_encoding_to_utf8(): from mercurial import encoding encoding.encoding = 'utf-8' set_mercurial_encoding_to_utf8() # Even with those we still run into problems. # I tried to do things by the book but could not convince # Mercurial to let me check in a change with UTF-8 in the # CL description or author field, no matter how many conversions # between str and unicode I inserted and despite changing the # default encoding. I'm tired of this game, so set the default # encoding for all of Python to 'utf-8', not 'ascii'. def default_to_utf8(): import sys reload(sys) # site.py deleted setdefaultencoding; get it back sys.setdefaultencoding('utf-8') default_to_utf8() ####################################################################### # Change list parsing. # # Change lists are stored in .hg/codereview/cl.nnnnnn # where nnnnnn is the number assigned by the code review server. # Most data about a change list is stored on the code review server # too: the description, reviewer, and cc list are all stored there. # The only thing in the cl.nnnnnn file is the list of relevant files. # Also, the existence of the cl.nnnnnn file marks this repository # as the one where the change list lives. emptydiff = """Index: ~rietveld~placeholder~ =================================================================== diff --git a/~rietveld~placeholder~ b/~rietveld~placeholder~ new file mode 100644 """ class CL(object): def __init__(self, name): typecheck(name, str) self.name = name self.desc = '' self.files = [] self.reviewer = [] self.cc = [] self.url = '' self.local = False self.web = False self.copied_from = None # None means current user self.mailed = False self.private = False def DiskText(self): cl = self s = "" if cl.copied_from: s += "Author: " + cl.copied_from + "\n\n" if cl.private: s += "Private: " + str(self.private) + "\n" s += "Mailed: " + str(self.mailed) + "\n" s += "Description:\n" s += Indent(cl.desc, "\t") s += "Files:\n" for f in cl.files: s += "\t" + f + "\n" typecheck(s, str) return s def EditorText(self): cl = self s = _change_prolog s += "\n" if cl.copied_from: s += "Author: " + cl.copied_from + "\n" if cl.url != '': s += 'URL: ' + cl.url + ' # cannot edit\n\n' if cl.private: s += "Private: True\n" s += "Reviewer: " + JoinComma(cl.reviewer) + "\n" s += "CC: " + JoinComma(cl.cc) + "\n" s += "\n" s += "Description:\n" if cl.desc == '': s += "\t<enter description here>\n" else: s += Indent(cl.desc, "\t") s += "\n" if cl.local or cl.name == "new": s += "Files:\n" for f in cl.files: s += "\t" + f + "\n" s += "\n" typecheck(s, str) return s def PendingText(self): cl = self s = cl.name + ":" + "\n" s += Indent(cl.desc, "\t") s += "\n" if cl.copied_from: s += "\tAuthor: " + cl.copied_from + "\n" s += "\tReviewer: " + JoinComma(cl.reviewer) + "\n" s += "\tCC: " + JoinComma(cl.cc) + "\n" s += "\tFiles:\n" for f in cl.files: s += "\t\t" + f + "\n" typecheck(s, str) return s def Flush(self, ui, repo): if self.name == "new": self.Upload(ui, repo, gofmt_just_warn=True, creating=True) dir = CodeReviewDir(ui, repo) path = dir + '/cl.' + self.name f = open(path+'!', "w") f.write(self.DiskText()) f.close() if sys.platform == "win32" and os.path.isfile(path): os.remove(path) os.rename(path+'!', path) if self.web and not self.copied_from: EditDesc(self.name, desc=self.desc, reviewers=JoinComma(self.reviewer), cc=JoinComma(self.cc), private=self.private) def Delete(self, ui, repo): dir = CodeReviewDir(ui, repo) os.unlink(dir + "/cl." + self.name) def Subject(self): s = line1(self.desc) if len(s) > 60: s = s[0:55] + "..." if self.name != "new": s = "code review %s: %s" % (self.name, s) typecheck(s, str) return s def Upload(self, ui, repo, send_mail=False, gofmt=True, gofmt_just_warn=False, creating=False, quiet=False): if not self.files and not creating: ui.warn("no files in change list\n") if ui.configbool("codereview", "force_gofmt", True) and gofmt: CheckFormat(ui, repo, self.files, just_warn=gofmt_just_warn) set_status("uploading CL metadata + diffs") os.chdir(repo.root) form_fields = [ ("content_upload", "1"), ("reviewers", JoinComma(self.reviewer)), ("cc", JoinComma(self.cc)), ("description", self.desc), ("base_hashes", ""), ] if self.name != "new": form_fields.append(("issue", self.name)) vcs = None # We do not include files when creating the issue, # because we want the patch sets to record the repository # and base revision they are diffs against. We use the patch # set message for that purpose, but there is no message with # the first patch set. Instead the message gets used as the # new CL's overall subject. So omit the diffs when creating # and then we'll run an immediate upload. # This has the effect that every CL begins with an empty "Patch set 1". if self.files and not creating: vcs = MercurialVCS(upload_options, ui, repo) data = vcs.GenerateDiff(self.files) files = vcs.GetBaseFiles(data) if len(data) > MAX_UPLOAD_SIZE: uploaded_diff_file = [] form_fields.append(("separate_patches", "1")) else: uploaded_diff_file = [("data", "data.diff", data)] else: uploaded_diff_file = [("data", "data.diff", emptydiff)] if vcs and self.name != "new": form_fields.append(("subject", "diff -r " + vcs.base_rev + " " + getremote(ui, repo, {}).path)) else: # First upload sets the subject for the CL itself. form_fields.append(("subject", self.Subject())) ctype, body = EncodeMultipartFormData(form_fields, uploaded_diff_file) response_body = MySend("/upload", body, content_type=ctype) patchset = None msg = response_body lines = msg.splitlines() if len(lines) >= 2: msg = lines[0] patchset = lines[1].strip() patches = [x.split(" ", 1) for x in lines[2:]] if response_body.startswith("Issue updated.") and quiet: pass else: ui.status(msg + "\n") set_status("uploaded CL metadata + diffs") if not response_body.startswith("Issue created.") and not response_body.startswith("Issue updated."): raise util.Abort("failed to update issue: " + response_body) issue = msg[msg.rfind("/")+1:] self.name = issue if not self.url: self.url = server_url_base + self.name if not uploaded_diff_file: set_status("uploading patches") patches = UploadSeparatePatches(issue, rpc, patchset, data, upload_options) if vcs: set_status("uploading base files") vcs.UploadBaseFiles(issue, rpc, patches, patchset, upload_options, files) if send_mail: set_status("sending mail") MySend("/" + issue + "/mail", payload="") self.web = True set_status("flushing changes to disk") self.Flush(ui, repo) return def Mail(self, ui, repo): pmsg = "Hello " + JoinComma(self.reviewer) if self.cc: pmsg += " (cc: %s)" % (', '.join(self.cc),) pmsg += ",\n" pmsg += "\n" repourl = getremote(ui, repo, {}).path if not self.mailed: pmsg += "I'd like you to review this change to\n" + repourl + "\n" else: pmsg += "Please take another look.\n" typecheck(pmsg, str) PostMessage(ui, self.name, pmsg, subject=self.Subject()) self.mailed = True self.Flush(ui, repo) def GoodCLName(name): typecheck(name, str) return re.match("^[0-9]+$", name) def ParseCL(text, name): typecheck(text, str) typecheck(name, str) sname = None lineno = 0 sections = { 'Author': '', 'Description': '', 'Files': '', 'URL': '', 'Reviewer': '', 'CC': '', 'Mailed': '', 'Private': '', } for line in text.split('\n'): lineno += 1 line = line.rstrip() if line != '' and line[0] == '#': continue if line == '' or line[0] == ' ' or line[0] == '\t': if sname == None and line != '': return None, lineno, 'text outside section' if sname != None: sections[sname] += line + '\n' continue p = line.find(':') if p >= 0: s, val = line[:p].strip(), line[p+1:].strip() if s in sections: sname = s if val != '': sections[sname] += val + '\n' continue return None, lineno, 'malformed section header' for k in sections: sections[k] = StripCommon(sections[k]).rstrip() cl = CL(name) if sections['Author']: cl.copied_from = sections['Author'] cl.desc = sections['Description'] for line in sections['Files'].split('\n'): i = line.find('#') if i >= 0: line = line[0:i].rstrip() line = line.strip() if line == '': continue cl.files.append(line) cl.reviewer = SplitCommaSpace(sections['Reviewer']) cl.cc = SplitCommaSpace(sections['CC']) cl.url = sections['URL'] if sections['Mailed'] != 'False': # Odd default, but avoids spurious mailings when # reading old CLs that do not have a Mailed: line. # CLs created with this update will always have # Mailed: False on disk. cl.mailed = True if sections['Private'] in ('True', 'true', 'Yes', 'yes'): cl.private = True if cl.desc == '<enter description here>': cl.desc = '' return cl, 0, '' def SplitCommaSpace(s): typecheck(s, str) s = s.strip() if s == "": return [] return re.split(", *", s) def CutDomain(s): typecheck(s, str) i = s.find('@') if i >= 0: s = s[0:i] return s def JoinComma(l): for s in l: typecheck(s, str) return ", ".join(l) def ExceptionDetail(): s = str(sys.exc_info()[0]) if s.startswith("<type '") and s.endswith("'>"): s = s[7:-2] elif s.startswith("<class '") and s.endswith("'>"): s = s[8:-2] arg = str(sys.exc_info()[1]) if len(arg) > 0: s += ": " + arg return s def IsLocalCL(ui, repo, name): return GoodCLName(name) and os.access(CodeReviewDir(ui, repo) + "/cl." + name, 0) # Load CL from disk and/or the web. def LoadCL(ui, repo, name, web=True): typecheck(name, str) set_status("loading CL " + name) if not GoodCLName(name): return None, "invalid CL name" dir = CodeReviewDir(ui, repo) path = dir + "cl." + name if os.access(path, 0): ff = open(path) text = ff.read() ff.close() cl, lineno, err = ParseCL(text, name) if err != "": return None, "malformed CL data: "+err cl.local = True else: cl = CL(name) if web: set_status("getting issue metadata from web") d = JSONGet(ui, "/api/" + name + "?messages=true") set_status(None) if d is None: return None, "cannot load CL %s from server" % (name,) if 'owner_email' not in d or 'issue' not in d or str(d['issue']) != name: return None, "malformed response loading CL data from code review server" cl.dict = d cl.reviewer = d.get('reviewers', []) cl.cc = d.get('cc', []) if cl.local and cl.copied_from and cl.desc: # local copy of CL written by someone else # and we saved a description. use that one, # so that committers can edit the description # before doing hg submit. pass else: cl.desc = d.get('description', "") cl.url = server_url_base + name cl.web = True cl.private = d.get('private', False) != False set_status("loaded CL " + name) return cl, '' global_status = None def set_status(s): # print >>sys.stderr, "\t", time.asctime(), s global global_status global_status = s class StatusThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): # pause a reasonable amount of time before # starting to display status messages, so that # most hg commands won't ever see them. time.sleep(30) # now show status every 15 seconds while True: time.sleep(15 - time.time() % 15) s = global_status if s is None: continue if s == "": s = "(unknown status)" print >>sys.stderr, time.asctime(), s def start_status_thread(): t = StatusThread() t.setDaemon(True) # allowed to exit if t is still running t.start() class LoadCLThread(threading.Thread): def __init__(self, ui, repo, dir, f, web): threading.Thread.__init__(self) self.ui = ui self.repo = repo self.dir = dir self.f = f self.web = web self.cl = None def run(self): cl, err = LoadCL(self.ui, self.repo, self.f[3:], web=self.web) if err != '': self.ui.warn("loading "+self.dir+self.f+": " + err + "\n") return self.cl = cl # Load all the CLs from this repository. def LoadAllCL(ui, repo, web=True): dir = CodeReviewDir(ui, repo) m = {} files = [f for f in os.listdir(dir) if f.startswith('cl.')] if not files: return m active = [] first = True for f in files: t = LoadCLThread(ui, repo, dir, f, web) t.start() if web and first: # first request: wait in case it needs to authenticate # otherwise we get lots of user/password prompts # running in parallel. t.join() if t.cl: m[t.cl.name] = t.cl first = False else: active.append(t) for t in active: t.join() if t.cl: m[t.cl.name] = t.cl return m # Find repository root. On error, ui.warn and return None def RepoDir(ui, repo): url = repo.url(); if not url.startswith('file:'): ui.warn("repository %s is not in local file system\n" % (url,)) return None url = url[5:] if url.endswith('/'): url = url[:-1] typecheck(url, str) return url # Find (or make) code review directory. On error, ui.warn and return None def CodeReviewDir(ui, repo): dir = RepoDir(ui, repo) if dir == None: return None dir += '/.hg/codereview/' if not os.path.isdir(dir): try: os.mkdir(dir, 0700) except: ui.warn('cannot mkdir %s: %s\n' % (dir, ExceptionDetail())) return None typecheck(dir, str) return dir # Turn leading tabs into spaces, so that the common white space # prefix doesn't get confused when people's editors write out # some lines with spaces, some with tabs. Only a heuristic # (some editors don't use 8 spaces either) but a useful one. def TabsToSpaces(line): i = 0 while i < len(line) and line[i] == '\t': i += 1 return ' '*(8*i) + line[i:] # Strip maximal common leading white space prefix from text def StripCommon(text): typecheck(text, str) ws = None for line in text.split('\n'): line = line.rstrip() if line == '': continue line = TabsToSpaces(line) white = line[:len(line)-len(line.lstrip())] if ws == None: ws = white else: common = '' for i in range(min(len(white), len(ws))+1): if white[0:i] == ws[0:i]: common = white[0:i] ws = common if ws == '': break if ws == None: return text t = '' for line in text.split('\n'): line = line.rstrip() line = TabsToSpaces(line) if line.startswith(ws): line = line[len(ws):] if line == '' and t == '': continue t += line + '\n' while len(t) >= 2 and t[-2:] == '\n\n': t = t[:-1] typecheck(t, str) return t # Indent text with indent. def Indent(text, indent): typecheck(text, str) typecheck(indent, str) t = '' for line in text.split('\n'): t += indent + line + '\n' typecheck(t, str) return t # Return the first line of l def line1(text): typecheck(text, str) return text.split('\n')[0] _change_prolog = """# Change list. # Lines beginning with # are ignored. # Multi-line values should be indented. """ ####################################################################### # Mercurial helper functions # Get effective change nodes taking into account applied MQ patches def effective_revpair(repo): try: return scmutil.revpair(repo, ['qparent']) except: return scmutil.revpair(repo, None) # Return list of changed files in repository that match pats. # Warn about patterns that did not match. def matchpats(ui, repo, pats, opts): matcher = scmutil.match(repo, pats, opts) node1, node2 = effective_revpair(repo) modified, added, removed, deleted, unknown, ignored, clean = repo.status(node1, node2, matcher, ignored=True, clean=True, unknown=True) return (modified, added, removed, deleted, unknown, ignored, clean) # Return list of changed files in repository that match pats. # The patterns came from the command line, so we warn # if they have no effect or cannot be understood. def ChangedFiles(ui, repo, pats, opts, taken=None): taken = taken or {} # Run each pattern separately so that we can warn about # patterns that didn't do anything useful. for p in pats: modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts) redo = False for f in unknown: promptadd(ui, repo, f) redo = True for f in deleted: promptremove(ui, repo, f) redo = True if redo: modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, [p], opts) for f in modified + added + removed: if f in taken: ui.warn("warning: %s already in CL %s\n" % (f, taken[f].name)) if not modified and not added and not removed: ui.warn("warning: %s did not match any modified files\n" % (p,)) # Again, all at once (eliminates duplicates) modified, added, removed = matchpats(ui, repo, pats, opts)[:3] l = modified + added + removed l.sort() if taken: l = Sub(l, taken.keys()) return l # Return list of changed files in repository that match pats and still exist. def ChangedExistingFiles(ui, repo, pats, opts): modified, added = matchpats(ui, repo, pats, opts)[:2] l = modified + added l.sort() return l # Return list of files claimed by existing CLs def Taken(ui, repo): all = LoadAllCL(ui, repo, web=False) taken = {} for _, cl in all.items(): for f in cl.files: taken[f] = cl return taken # Return list of changed files that are not claimed by other CLs def DefaultFiles(ui, repo, pats, opts): return ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) def Sub(l1, l2): return [l for l in l1 if l not in l2] def Add(l1, l2): l = l1 + Sub(l2, l1) l.sort() return l def Intersect(l1, l2): return [l for l in l1 if l in l2] def getremote(ui, repo, opts): # save $http_proxy; creating the HTTP repo object will # delete it in an attempt to "help" proxy = os.environ.get('http_proxy') source = hg.parseurl(ui.expandpath("default"), None)[0] try: remoteui = hg.remoteui # hg 1.6 except: remoteui = cmdutil.remoteui other = hg.repository(remoteui(repo, opts), source) if proxy is not None: os.environ['http_proxy'] = proxy return other def Incoming(ui, repo, opts): _, incoming, _ = findcommonincoming(repo, getremote(ui, repo, opts)) return incoming desc_re = '^(.+: |(tag )?(release|weekly)\.|fix build|undo CL)' desc_msg = '''Your CL description appears not to use the standard form. The first line of your change description is conventionally a one-line summary of the change, prefixed by the primary affected package, and is used as the subject for code review mail; the rest of the description elaborates. Examples: encoding/rot13: new package math: add IsInf, IsNaN net: fix cname in LookupHost unicode: update to Unicode 5.0.2 ''' def promptremove(ui, repo, f): if promptyesno(ui, "hg remove %s (y/n)?" % (f,)): if commands.remove(ui, repo, 'path:'+f) != 0: ui.warn("error removing %s" % (f,)) def promptadd(ui, repo, f): if promptyesno(ui, "hg add %s (y/n)?" % (f,)): if commands.add(ui, repo, 'path:'+f) != 0: ui.warn("error adding %s" % (f,)) def EditCL(ui, repo, cl): set_status(None) # do not show status s = cl.EditorText() while True: s = ui.edit(s, ui.username()) clx, line, err = ParseCL(s, cl.name) if err != '': if not promptyesno(ui, "error parsing change list: line %d: %s\nre-edit (y/n)?" % (line, err)): return "change list not modified" continue # Check description. if clx.desc == '': if promptyesno(ui, "change list should have a description\nre-edit (y/n)?"): continue elif re.search('<enter reason for undo>', clx.desc): if promptyesno(ui, "change list description omits reason for undo\nre-edit (y/n)?"): continue elif not re.match(desc_re, clx.desc.split('\n')[0]): if promptyesno(ui, desc_msg + "re-edit (y/n)?"): continue # Check file list for files that need to be hg added or hg removed # or simply aren't understood. pats = ['path:'+f for f in clx.files] modified, added, removed, deleted, unknown, ignored, clean = matchpats(ui, repo, pats, {}) files = [] for f in clx.files: if f in modified or f in added or f in removed: files.append(f) continue if f in deleted: promptremove(ui, repo, f) files.append(f) continue if f in unknown: promptadd(ui, repo, f) files.append(f) continue if f in ignored: ui.warn("error: %s is excluded by .hgignore; omitting\n" % (f,)) continue if f in clean: ui.warn("warning: %s is listed in the CL but unchanged\n" % (f,)) files.append(f) continue p = repo.root + '/' + f if os.path.isfile(p): ui.warn("warning: %s is a file but not known to hg\n" % (f,)) files.append(f) continue if os.path.isdir(p): ui.warn("error: %s is a directory, not a file; omitting\n" % (f,)) continue ui.warn("error: %s does not exist; omitting\n" % (f,)) clx.files = files cl.desc = clx.desc cl.reviewer = clx.reviewer cl.cc = clx.cc cl.files = clx.files cl.private = clx.private break return "" # For use by submit, etc. (NOT by change) # Get change list number or list of files from command line. # If files are given, make a new change list. def CommandLineCL(ui, repo, pats, opts, defaultcc=None): if len(pats) > 0 and GoodCLName(pats[0]): if len(pats) != 1: return None, "cannot specify change number and file names" if opts.get('message'): return None, "cannot use -m with existing CL" cl, err = LoadCL(ui, repo, pats[0], web=True) if err != "": return None, err else: cl = CL("new") cl.local = True cl.files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) if not cl.files: return None, "no files changed" if opts.get('reviewer'): cl.reviewer = Add(cl.reviewer, SplitCommaSpace(opts.get('reviewer'))) if opts.get('cc'): cl.cc = Add(cl.cc, SplitCommaSpace(opts.get('cc'))) if defaultcc: cl.cc = Add(cl.cc, defaultcc) if cl.name == "new": if opts.get('message'): cl.desc = opts.get('message') else: err = EditCL(ui, repo, cl) if err != '': return None, err return cl, "" # reposetup replaces cmdutil.match with this wrapper, # which expands the syntax @clnumber to mean the files # in that CL. original_match = None def ReplacementForCmdutilMatch(repo, pats=None, opts=None, globbed=False, default='relpath'): taken = [] files = [] pats = pats or [] opts = opts or {} for p in pats: if p.startswith('@'): taken.append(p) clname = p[1:] if not GoodCLName(clname): raise util.Abort("invalid CL name " + clname) cl, err = LoadCL(repo.ui, repo, clname, web=False) if err != '': raise util.Abort("loading CL " + clname + ": " + err) if not cl.files: raise util.Abort("no files in CL " + clname) files = Add(files, cl.files) pats = Sub(pats, taken) + ['path:'+f for f in files] # work-around for http://selenic.com/hg/rev/785bbc8634f8 if hgversion >= '1.9' and not hasattr(repo, 'match'): repo = repo[None] return original_match(repo, pats=pats, opts=opts, globbed=globbed, default=default) def RelativePath(path, cwd): n = len(cwd) if path.startswith(cwd) and path[n] == '/': return path[n+1:] return path def CheckFormat(ui, repo, files, just_warn=False): set_status("running gofmt") CheckGofmt(ui, repo, files, just_warn) CheckTabfmt(ui, repo, files, just_warn) # Check that gofmt run on the list of files does not change them def CheckGofmt(ui, repo, files, just_warn): files = [f for f in files if (f.startswith('src/') or f.startswith('test/bench/')) and f.endswith('.go')] if not files: return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] files = [f for f in files if os.access(f, 0)] if not files: return try: cmd = subprocess.Popen(["gofmt", "-l"] + files, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=sys.platform != "win32") cmd.stdin.close() except: raise util.Abort("gofmt: " + ExceptionDetail()) data = cmd.stdout.read() errors = cmd.stderr.read() cmd.wait() set_status("done with gofmt") if len(errors) > 0: ui.warn("gofmt errors:\n" + errors.rstrip() + "\n") return if len(data) > 0: msg = "gofmt needs to format these files (run hg gofmt):\n" + Indent(data, "\t").rstrip() if just_warn: ui.warn("warning: " + msg + "\n") else: raise util.Abort(msg) return # Check that *.[chys] files indent using tabs. def CheckTabfmt(ui, repo, files, just_warn): files = [f for f in files if f.startswith('src/') and re.search(r"\.[chys]$", f)] if not files: return cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] files = [f for f in files if os.access(f, 0)] badfiles = [] for f in files: try: for line in open(f, 'r'): # Four leading spaces is enough to complain about, # except that some Plan 9 code uses four spaces as the label indent, # so allow that. if line.startswith(' ') and not re.match(' [A-Za-z0-9_]+:', line): badfiles.append(f) break except: # ignore cannot open file, etc. pass if len(badfiles) > 0: msg = "these files use spaces for indentation (use tabs instead):\n\t" + "\n\t".join(badfiles) if just_warn: ui.warn("warning: " + msg + "\n") else: raise util.Abort(msg) return ####################################################################### # Mercurial commands # every command must take a ui and and repo as arguments. # opts is a dict where you can find other command line flags # # Other parameters are taken in order from items on the command line that # don't start with a dash. If no default value is given in the parameter list, # they are required. # def change(ui, repo, *pats, **opts): """create, edit or delete a change list Create, edit or delete a change list. A change list is a group of files to be reviewed and submitted together, plus a textual description of the change. Change lists are referred to by simple alphanumeric names. Changes must be reviewed before they can be submitted. In the absence of options, the change command opens the change list for editing in the default editor. Deleting a change with the -d or -D flag does not affect the contents of the files listed in that change. To revert the files listed in a change, use hg revert @123456 before running hg change -d 123456. """ if missing_codereview: return missing_codereview dirty = {} if len(pats) > 0 and GoodCLName(pats[0]): name = pats[0] if len(pats) != 1: return "cannot specify CL name and file patterns" pats = pats[1:] cl, err = LoadCL(ui, repo, name, web=True) if err != '': return err if not cl.local and (opts["stdin"] or not opts["stdout"]): return "cannot change non-local CL " + name else: if repo[None].branch() != "default": return "cannot run hg change outside default branch" name = "new" cl = CL("new") dirty[cl] = True files = ChangedFiles(ui, repo, pats, opts, taken=Taken(ui, repo)) if opts["delete"] or opts["deletelocal"]: if opts["delete"] and opts["deletelocal"]: return "cannot use -d and -D together" flag = "-d" if opts["deletelocal"]: flag = "-D" if name == "new": return "cannot use "+flag+" with file patterns" if opts["stdin"] or opts["stdout"]: return "cannot use "+flag+" with -i or -o" if not cl.local: return "cannot change non-local CL " + name if opts["delete"]: if cl.copied_from: return "original author must delete CL; hg change -D will remove locally" PostMessage(ui, cl.name, "*** Abandoned ***", send_mail=cl.mailed) EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) return if opts["stdin"]: s = sys.stdin.read() clx, line, err = ParseCL(s, name) if err != '': return "error parsing change list: line %d: %s" % (line, err) if clx.desc is not None: cl.desc = clx.desc; dirty[cl] = True if clx.reviewer is not None: cl.reviewer = clx.reviewer dirty[cl] = True if clx.cc is not None: cl.cc = clx.cc dirty[cl] = True if clx.files is not None: cl.files = clx.files dirty[cl] = True if clx.private != cl.private: cl.private = clx.private dirty[cl] = True if not opts["stdin"] and not opts["stdout"]: if name == "new": cl.files = files err = EditCL(ui, repo, cl) if err != "": return err dirty[cl] = True for d, _ in dirty.items(): name = d.name d.Flush(ui, repo) if name == "new": d.Upload(ui, repo, quiet=True) if opts["stdout"]: ui.write(cl.EditorText()) elif opts["pending"]: ui.write(cl.PendingText()) elif name == "new": if ui.quiet: ui.write(cl.name) else: ui.write("CL created: " + cl.url + "\n") return def code_login(ui, repo, **opts): """log in to code review server Logs in to the code review server, saving a cookie in a file in your home directory. """ if missing_codereview: return missing_codereview MySend(None) def clpatch(ui, repo, clname, **opts): """import a patch from the code review server Imports a patch from the code review server into the local client. If the local client has already modified any of the files that the patch modifies, this command will refuse to apply the patch. Submitting an imported patch will keep the original author's name as the Author: line but add your own name to a Committer: line. """ if repo[None].branch() != "default": return "cannot run hg clpatch outside default branch" return clpatch_or_undo(ui, repo, clname, opts, mode="clpatch") def undo(ui, repo, clname, **opts): """undo the effect of a CL Creates a new CL that undoes an earlier CL. After creating the CL, opens the CL text for editing so that you can add the reason for the undo to the description. """ if repo[None].branch() != "default": return "cannot run hg undo outside default branch" return clpatch_or_undo(ui, repo, clname, opts, mode="undo") def release_apply(ui, repo, clname, **opts): """apply a CL to the release branch Creates a new CL copying a previously committed change from the main branch to the release branch. The current client must either be clean or already be in the release branch. The release branch must be created by starting with a clean client, disabling the code review plugin, and running: hg update weekly.YYYY-MM-DD hg branch release-branch.rNN hg commit -m 'create release-branch.rNN' hg push --new-branch Then re-enable the code review plugin. People can test the release branch by running hg update release-branch.rNN in a clean client. To return to the normal tree, hg update default Move changes since the weekly into the release branch using hg release-apply followed by the usual code review process and hg submit. When it comes time to tag the release, record the final long-form tag of the release-branch.rNN in the *default* branch's .hgtags file. That is, run hg update default and then edit .hgtags as you would for a weekly. """ c = repo[None] if not releaseBranch: return "no active release branches" if c.branch() != releaseBranch: if c.modified() or c.added() or c.removed(): raise util.Abort("uncommitted local changes - cannot switch branches") err = hg.clean(repo, releaseBranch) if err: return err try: err = clpatch_or_undo(ui, repo, clname, opts, mode="backport") if err: raise util.Abort(err) except Exception, e: hg.clean(repo, "default") raise e return None def rev2clname(rev): # Extract CL name from revision description. # The last line in the description that is a codereview URL is the real one. # Earlier lines might be part of the user-written description. all = re.findall('(?m)^http://codereview.appspot.com/([0-9]+)$', rev.description()) if len(all) > 0: return all[-1] return "" undoHeader = """undo CL %s / %s <enter reason for undo> ««« original CL description """ undoFooter = """ »»» """ backportHeader = """[%s] %s ««« CL %s / %s """ backportFooter = """ »»» """ # Implementation of clpatch/undo. def clpatch_or_undo(ui, repo, clname, opts, mode): if missing_codereview: return missing_codereview if mode == "undo" or mode == "backport": if hgversion < '1.4': # Don't have cmdutil.match (see implementation of sync command). return "hg is too old to run hg %s - update to 1.4 or newer" % mode # Find revision in Mercurial repository. # Assume CL number is 7+ decimal digits. # Otherwise is either change log sequence number (fewer decimal digits), # hexadecimal hash, or tag name. # Mercurial will fall over long before the change log # sequence numbers get to be 7 digits long. if re.match('^[0-9]{7,}$', clname): found = False matchfn = scmutil.match(repo, [], {'rev': None}) def prep(ctx, fns): pass for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep): rev = repo[ctx.rev()] # Last line with a code review URL is the actual review URL. # Earlier ones might be part of the CL description. n = rev2clname(rev) if n == clname: found = True break if not found: return "cannot find CL %s in local repository" % clname else: rev = repo[clname] if not rev: return "unknown revision %s" % clname clname = rev2clname(rev) if clname == "": return "cannot find CL name in revision description" # Create fresh CL and start with patch that would reverse the change. vers = short(rev.node()) cl = CL("new") desc = str(rev.description()) if mode == "undo": cl.desc = (undoHeader % (clname, vers)) + desc + undoFooter else: cl.desc = (backportHeader % (releaseBranch, line1(desc), clname, vers)) + desc + undoFooter v1 = vers v0 = short(rev.parents()[0].node()) if mode == "undo": arg = v1 + ":" + v0 else: vers = v0 arg = v0 + ":" + v1 patch = RunShell(["hg", "diff", "--git", "-r", arg]) else: # clpatch cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err if patch == emptydiff: return "codereview issue %s has no diff" % clname # find current hg version (hg identify) ctx = repo[None] parents = ctx.parents() id = '+'.join([short(p.node()) for p in parents]) # if version does not match the patch version, # try to update the patch line numbers. if vers != "" and id != vers: # "vers in repo" gives the wrong answer # on some versions of Mercurial. Instead, do the actual # lookup and catch the exception. try: repo[vers].description() except: return "local repository is out of date; sync to get %s" % (vers) patch1, err = portPatch(repo, patch, vers, id) if err != "": if not opts["ignore_hgpatch_failure"]: return "codereview issue %s is out of date: %s (%s->%s)" % (clname, err, vers, id) else: patch = patch1 argv = ["hgpatch"] if opts["no_incoming"] or mode == "backport": argv += ["--checksync=false"] try: cmd = subprocess.Popen(argv, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=None, close_fds=sys.platform != "win32") except: return "hgpatch: " + ExceptionDetail() out, err = cmd.communicate(patch) if cmd.returncode != 0 and not opts["ignore_hgpatch_failure"]: return "hgpatch failed" cl.local = True cl.files = out.strip().split() if not cl.files and not opts["ignore_hgpatch_failure"]: return "codereview issue %s has no changed files" % clname files = ChangedFiles(ui, repo, [], opts) extra = Sub(cl.files, files) if extra: ui.warn("warning: these files were listed in the patch but not changed:\n\t" + "\n\t".join(extra) + "\n") cl.Flush(ui, repo) if mode == "undo": err = EditCL(ui, repo, cl) if err != "": return "CL created, but error editing: " + err cl.Flush(ui, repo) else: ui.write(cl.PendingText() + "\n") # portPatch rewrites patch from being a patch against # oldver to being a patch against newver. def portPatch(repo, patch, oldver, newver): lines = patch.splitlines(True) # True = keep \n delta = None for i in range(len(lines)): line = lines[i] if line.startswith('--- a/'): file = line[6:-1] delta = fileDeltas(repo, file, oldver, newver) if not delta or not line.startswith('@@ '): continue # @@ -x,y +z,w @@ means the patch chunk replaces # the original file's line numbers x up to x+y with the # line numbers z up to z+w in the new file. # Find the delta from x in the original to the same # line in the current version and add that delta to both # x and z. m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) if not m: return None, "error parsing patch line numbers" n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) d, err = lineDelta(delta, n1, len1) if err != "": return "", err n1 += d n2 += d lines[i] = "@@ -%d,%d +%d,%d @@\n" % (n1, len1, n2, len2) newpatch = ''.join(lines) return newpatch, "" # fileDelta returns the line number deltas for the given file's # changes from oldver to newver. # The deltas are a list of (n, len, newdelta) triples that say # lines [n, n+len) were modified, and after that range the # line numbers are +newdelta from what they were before. def fileDeltas(repo, file, oldver, newver): cmd = ["hg", "diff", "--git", "-r", oldver + ":" + newver, "path:" + file] data = RunShell(cmd, silent_ok=True) deltas = [] for line in data.splitlines(): m = re.match('@@ -([0-9]+),([0-9]+) \+([0-9]+),([0-9]+) @@', line) if not m: continue n1, len1, n2, len2 = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4)) deltas.append((n1, len1, n2+len2-(n1+len1))) return deltas # lineDelta finds the appropriate line number delta to apply to the lines [n, n+len). # It returns an error if those lines were rewritten by the patch. def lineDelta(deltas, n, len): d = 0 for (old, oldlen, newdelta) in deltas: if old >= n+len: break if old+len > n: return 0, "patch and recent changes conflict" d = newdelta return d, "" def download(ui, repo, clname, **opts): """download a change from the code review server Download prints a description of the given change list followed by its diff, downloaded from the code review server. """ if missing_codereview: return missing_codereview cl, vers, patch, err = DownloadCL(ui, repo, clname) if err != "": return err ui.write(cl.EditorText() + "\n") ui.write(patch + "\n") return def file(ui, repo, clname, pat, *pats, **opts): """assign files to or remove files from a change list Assign files to or (with -d) remove files from a change list. The -d option only removes files from the change list. It does not edit them or remove them from the repository. """ if missing_codereview: return missing_codereview pats = tuple([pat] + list(pats)) if not GoodCLName(clname): return "invalid CL name " + clname dirty = {} cl, err = LoadCL(ui, repo, clname, web=False) if err != '': return err if not cl.local: return "cannot change non-local CL " + clname files = ChangedFiles(ui, repo, pats, opts) if opts["delete"]: oldfiles = Intersect(files, cl.files) if oldfiles: if not ui.quiet: ui.status("# Removing files from CL. To undo:\n") ui.status("# cd %s\n" % (repo.root)) for f in oldfiles: ui.status("# hg file %s %s\n" % (cl.name, f)) cl.files = Sub(cl.files, oldfiles) cl.Flush(ui, repo) else: ui.status("no such files in CL") return if not files: return "no such modified files" files = Sub(files, cl.files) taken = Taken(ui, repo) warned = False for f in files: if f in taken: if not warned and not ui.quiet: ui.status("# Taking files from other CLs. To undo:\n") ui.status("# cd %s\n" % (repo.root)) warned = True ocl = taken[f] if not ui.quiet: ui.status("# hg file %s %s\n" % (ocl.name, f)) if ocl not in dirty: ocl.files = Sub(ocl.files, files) dirty[ocl] = True cl.files = Add(cl.files, files) dirty[cl] = True for d, _ in dirty.items(): d.Flush(ui, repo) return def gofmt(ui, repo, *pats, **opts): """apply gofmt to modified files Applies gofmt to the modified files in the repository that match the given patterns. """ if missing_codereview: return missing_codereview files = ChangedExistingFiles(ui, repo, pats, opts) files = [f for f in files if f.endswith(".go")] if not files: return "no modified go files" cwd = os.getcwd() files = [RelativePath(repo.root + '/' + f, cwd) for f in files] try: cmd = ["gofmt", "-l"] if not opts["list"]: cmd += ["-w"] if os.spawnvp(os.P_WAIT, "gofmt", cmd + files) != 0: raise util.Abort("gofmt did not exit cleanly") except error.Abort, e: raise except: raise util.Abort("gofmt: " + ExceptionDetail()) return def mail(ui, repo, *pats, **opts): """mail a change for review Uploads a patch to the code review server and then sends mail to the reviewer and CC list asking for a review. """ if missing_codereview: return missing_codereview cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc) if err != "": return err cl.Upload(ui, repo, gofmt_just_warn=True) if not cl.reviewer: # If no reviewer is listed, assign the review to defaultcc. # This makes sure that it appears in the # codereview.appspot.com/user/defaultcc # page, so that it doesn't get dropped on the floor. if not defaultcc: return "no reviewers listed in CL" cl.cc = Sub(cl.cc, defaultcc) cl.reviewer = defaultcc cl.Flush(ui, repo) if cl.files == []: return "no changed files, not sending mail" cl.Mail(ui, repo) def pending(ui, repo, *pats, **opts): """show pending changes Lists pending changes followed by a list of unassigned but modified files. """ if missing_codereview: return missing_codereview m = LoadAllCL(ui, repo, web=True) names = m.keys() names.sort() for name in names: cl = m[name] ui.write(cl.PendingText() + "\n") files = DefaultFiles(ui, repo, [], opts) if len(files) > 0: s = "Changed files not in any CL:\n" for f in files: s += "\t" + f + "\n" ui.write(s) def reposetup(ui, repo): global original_match if original_match is None: start_status_thread() original_match = scmutil.match scmutil.match = ReplacementForCmdutilMatch RietveldSetup(ui, repo) def CheckContributor(ui, repo, user=None): set_status("checking CONTRIBUTORS file") user, userline = FindContributor(ui, repo, user, warn=False) if not userline: raise util.Abort("cannot find %s in CONTRIBUTORS" % (user,)) return userline def FindContributor(ui, repo, user=None, warn=True): if not user: user = ui.config("ui", "username") if not user: raise util.Abort("[ui] username is not configured in .hgrc") user = user.lower() m = re.match(r".*<(.*)>", user) if m: user = m.group(1) if user not in contributors: if warn: ui.warn("warning: cannot find %s in CONTRIBUTORS\n" % (user,)) return user, None user, email = contributors[user] return email, "%s <%s>" % (user, email) def submit(ui, repo, *pats, **opts): """submit change to remote repository Submits change to remote repository. Bails out if the local repository is not in sync with the remote one. """ if missing_codereview: return missing_codereview # We already called this on startup but sometimes Mercurial forgets. set_mercurial_encoding_to_utf8() repo.ui.quiet = True if not opts["no_incoming"] and Incoming(ui, repo, opts): return "local repository out of date; must sync before submit" cl, err = CommandLineCL(ui, repo, pats, opts, defaultcc=defaultcc) if err != "": return err user = None if cl.copied_from: user = cl.copied_from userline = CheckContributor(ui, repo, user) typecheck(userline, str) about = "" if cl.reviewer: about += "R=" + JoinComma([CutDomain(s) for s in cl.reviewer]) + "\n" if opts.get('tbr'): tbr = SplitCommaSpace(opts.get('tbr')) cl.reviewer = Add(cl.reviewer, tbr) about += "TBR=" + JoinComma([CutDomain(s) for s in tbr]) + "\n" if cl.cc: about += "CC=" + JoinComma([CutDomain(s) for s in cl.cc]) + "\n" if not cl.reviewer: return "no reviewers listed in CL" if not cl.local: return "cannot submit non-local CL" # upload, to sync current patch and also get change number if CL is new. if not cl.copied_from: cl.Upload(ui, repo, gofmt_just_warn=True) # check gofmt for real; allowed upload to warn in order to save CL. cl.Flush(ui, repo) CheckFormat(ui, repo, cl.files) about += "%s%s\n" % (server_url_base, cl.name) if cl.copied_from: about += "\nCommitter: " + CheckContributor(ui, repo, None) + "\n" typecheck(about, str) if not cl.mailed and not cl.copied_from: # in case this is TBR cl.Mail(ui, repo) # submit changes locally date = opts.get('date') if date: opts['date'] = util.parsedate(date) typecheck(opts['date'], str) opts['message'] = cl.desc.rstrip() + "\n\n" + about typecheck(opts['message'], str) if opts['dryrun']: print "NOT SUBMITTING:" print "User: ", userline print "Message:" print Indent(opts['message'], "\t") print "Files:" print Indent('\n'.join(cl.files), "\t") return "dry run; not submitted" m = match.exact(repo.root, repo.getcwd(), cl.files) node = repo.commit(ustr(opts['message']), ustr(userline), opts.get('date'), m) if not node: return "nothing changed" # push to remote; if it fails for any reason, roll back try: log = repo.changelog rev = log.rev(node) parents = log.parentrevs(rev) if (rev-1 not in parents and (parents == (nullrev, nullrev) or len(log.heads(log.node(parents[0]))) > 1 and (parents[1] == nullrev or len(log.heads(log.node(parents[1]))) > 1))): # created new head raise util.Abort("local repository out of date; must sync before submit") # push changes to remote. # if it works, we're committed. # if not, roll back other = getremote(ui, repo, opts) r = repo.push(other, False, None) if r == 0: raise util.Abort("local repository out of date; must sync before submit") except: real_rollback() raise # we're committed. upload final patch, close review, add commit message changeURL = short(node) url = other.url() m = re.match("^https?://([^@/]+@)?([^.]+)\.googlecode\.com/hg/?", url) if m: changeURL = "http://code.google.com/p/%s/source/detail?r=%s" % (m.group(2), changeURL) else: print >>sys.stderr, "URL: ", url pmsg = "*** Submitted as " + changeURL + " ***\n\n" + opts['message'] # When posting, move reviewers to CC line, # so that the issue stops showing up in their "My Issues" page. PostMessage(ui, cl.name, pmsg, reviewers="", cc=JoinComma(cl.reviewer+cl.cc)) if not cl.copied_from: EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) c = repo[None] if c.branch() == releaseBranch and not c.modified() and not c.added() and not c.removed(): ui.write("switching from %s to default branch.\n" % releaseBranch) err = hg.clean(repo, "default") if err: return err return None def sync(ui, repo, **opts): """synchronize with remote repository Incorporates recent changes from the remote repository into the local repository. """ if missing_codereview: return missing_codereview if not opts["local"]: ui.status = sync_note ui.note = sync_note other = getremote(ui, repo, opts) modheads = repo.pull(other) err = commands.postincoming(ui, repo, modheads, True, "tip") if err: return err commands.update(ui, repo, rev="default") sync_changes(ui, repo) def sync_note(msg): # we run sync (pull -u) in verbose mode to get the # list of files being updated, but that drags along # a bunch of messages we don't care about. # omit them. if msg == 'resolving manifests\n': return if msg == 'searching for changes\n': return if msg == "couldn't find merge tool hgmerge\n": return sys.stdout.write(msg) def sync_changes(ui, repo): # Look through recent change log descriptions to find # potential references to http://.*/our-CL-number. # Double-check them by looking at the Rietveld log. def Rev(rev): desc = repo[rev].description().strip() for clname in re.findall('(?m)^http://(?:[^\n]+)/([0-9]+)$', desc): if IsLocalCL(ui, repo, clname) and IsRietveldSubmitted(ui, clname, repo[rev].hex()): ui.warn("CL %s submitted as %s; closing\n" % (clname, repo[rev])) cl, err = LoadCL(ui, repo, clname, web=False) if err != "": ui.warn("loading CL %s: %s\n" % (clname, err)) continue if not cl.copied_from: EditDesc(cl.name, closed=True, private=cl.private) cl.Delete(ui, repo) if hgversion < '1.4': get = util.cachefunc(lambda r: repo[r].changeset()) changeiter, matchfn = cmdutil.walkchangerevs(ui, repo, [], get, {'rev': None}) n = 0 for st, rev, fns in changeiter: if st != 'iter': continue n += 1 if n > 100: break Rev(rev) else: matchfn = scmutil.match(repo, [], {'rev': None}) def prep(ctx, fns): pass for ctx in cmdutil.walkchangerevs(repo, matchfn, {'rev': None}, prep): Rev(ctx.rev()) # Remove files that are not modified from the CLs in which they appear. all = LoadAllCL(ui, repo, web=False) changed = ChangedFiles(ui, repo, [], {}) for _, cl in all.items(): extra = Sub(cl.files, changed) if extra: ui.warn("Removing unmodified files from CL %s:\n" % (cl.name,)) for f in extra: ui.warn("\t%s\n" % (f,)) cl.files = Sub(cl.files, extra) cl.Flush(ui, repo) if not cl.files: if not cl.copied_from: ui.warn("CL %s has no files; delete (abandon) with hg change -d %s\n" % (cl.name, cl.name)) else: ui.warn("CL %s has no files; delete locally with hg change -D %s\n" % (cl.name, cl.name)) return def upload(ui, repo, name, **opts): """upload diffs to the code review server Uploads the current modifications for a given change to the server. """ if missing_codereview: return missing_codereview repo.ui.quiet = True cl, err = LoadCL(ui, repo, name, web=True) if err != "": return err if not cl.local: return "cannot upload non-local change" cl.Upload(ui, repo) print "%s%s\n" % (server_url_base, cl.name) return review_opts = [ ('r', 'reviewer', '', 'add reviewer'), ('', 'cc', '', 'add cc'), ('', 'tbr', '', 'add future reviewer'), ('m', 'message', '', 'change description (for new change)'), ] cmdtable = { # The ^ means to show this command in the help text that # is printed when running hg with no arguments. "^change": ( change, [ ('d', 'delete', None, 'delete existing change list'), ('D', 'deletelocal', None, 'delete locally, but do not change CL on server'), ('i', 'stdin', None, 'read change list from standard input'), ('o', 'stdout', None, 'print change list to standard output'), ('p', 'pending', None, 'print pending summary to standard output'), ], "[-d | -D] [-i] [-o] change# or FILE ..." ), "^clpatch": ( clpatch, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), # Would prefer to call this codereview-login, but then # hg help codereview prints the help for this command # instead of the help for the extension. "code-login": ( code_login, [], "", ), "^download": ( download, [], "change#" ), "^file": ( file, [ ('d', 'delete', None, 'delete files from change list (but not repository)'), ], "[-d] change# FILE ..." ), "^gofmt": ( gofmt, [ ('l', 'list', None, 'list files that would change, but do not edit them'), ], "FILE ..." ), "^pending|p": ( pending, [], "[FILE ...]" ), "^mail": ( mail, review_opts + [ ] + commands.walkopts, "[-r reviewer] [--cc cc] [change# | file ...]" ), "^release-apply": ( release_apply, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), # TODO: release-start, release-tag, weekly-tag "^submit": ( submit, review_opts + [ ('', 'no_incoming', None, 'disable initial incoming check (for testing)'), ('n', 'dryrun', None, 'make change only locally (for testing)'), ] + commands.walkopts + commands.commitopts + commands.commitopts2, "[-r reviewer] [--cc cc] [change# | file ...]" ), "^sync": ( sync, [ ('', 'local', None, 'do not pull changes from remote repository') ], "[--local]", ), "^undo": ( undo, [ ('', 'ignore_hgpatch_failure', None, 'create CL metadata even if hgpatch fails'), ('', 'no_incoming', None, 'disable check for incoming changes'), ], "change#" ), "^upload": ( upload, [], "change#" ), } ####################################################################### # Wrappers around upload.py for interacting with Rietveld # HTML form parser class FormParser(HTMLParser): def __init__(self): self.map = {} self.curtag = None self.curdata = None HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if tag == "input": key = None value = '' for a in attrs: if a[0] == 'name': key = a[1] if a[0] == 'value': value = a[1] if key is not None: self.map[key] = value if tag == "textarea": key = None for a in attrs: if a[0] == 'name': key = a[1] if key is not None: self.curtag = key self.curdata = '' def handle_endtag(self, tag): if tag == "textarea" and self.curtag is not None: self.map[self.curtag] = self.curdata self.curtag = None self.curdata = None def handle_charref(self, name): self.handle_data(unichr(int(name))) def handle_entityref(self, name): import htmlentitydefs if name in htmlentitydefs.entitydefs: self.handle_data(htmlentitydefs.entitydefs[name]) else: self.handle_data("&" + name + ";") def handle_data(self, data): if self.curdata is not None: self.curdata += data def JSONGet(ui, path): try: data = MySend(path, force_auth=False) typecheck(data, str) d = fix_json(json.loads(data)) except: ui.warn("JSONGet %s: %s\n" % (path, ExceptionDetail())) return None return d # Clean up json parser output to match our expectations: # * all strings are UTF-8-encoded str, not unicode. # * missing fields are missing, not None, # so that d.get("foo", defaultvalue) works. def fix_json(x): if type(x) in [str, int, float, bool, type(None)]: pass elif type(x) is unicode: x = x.encode("utf-8") elif type(x) is list: for i in range(len(x)): x[i] = fix_json(x[i]) elif type(x) is dict: todel = [] for k in x: if x[k] is None: todel.append(k) else: x[k] = fix_json(x[k]) for k in todel: del x[k] else: raise util.Abort("unknown type " + str(type(x)) + " in fix_json") if type(x) is str: x = x.replace('\r\n', '\n') return x def IsRietveldSubmitted(ui, clname, hex): dict = JSONGet(ui, "/api/" + clname + "?messages=true") if dict is None: return False for msg in dict.get("messages", []): text = msg.get("text", "") m = re.match('\*\*\* Submitted as [^*]*?([0-9a-f]+) \*\*\*', text) if m is not None and len(m.group(1)) >= 8 and hex.startswith(m.group(1)): return True return False def IsRietveldMailed(cl): for msg in cl.dict.get("messages", []): if msg.get("text", "").find("I'd like you to review this change") >= 0: return True return False def DownloadCL(ui, repo, clname): set_status("downloading CL " + clname) cl, err = LoadCL(ui, repo, clname, web=True) if err != "": return None, None, None, "error loading CL %s: %s" % (clname, err) # Find most recent diff diffs = cl.dict.get("patchsets", []) if not diffs: return None, None, None, "CL has no patch sets" patchid = diffs[-1] patchset = JSONGet(ui, "/api/" + clname + "/" + str(patchid)) if patchset is None: return None, None, None, "error loading CL patchset %s/%d" % (clname, patchid) if patchset.get("patchset", 0) != patchid: return None, None, None, "malformed patchset information" vers = "" msg = patchset.get("message", "").split() if len(msg) >= 3 and msg[0] == "diff" and msg[1] == "-r": vers = msg[2] diff = "/download/issue" + clname + "_" + str(patchid) + ".diff" diffdata = MySend(diff, force_auth=False) # Print warning if email is not in CONTRIBUTORS file. email = cl.dict.get("owner_email", "") if not email: return None, None, None, "cannot find owner for %s" % (clname) him = FindContributor(ui, repo, email) me = FindContributor(ui, repo, None) if him == me: cl.mailed = IsRietveldMailed(cl) else: cl.copied_from = email return cl, vers, diffdata, "" def MySend(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Run MySend1 maybe twice, because Rietveld is unreliable.""" try: return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) except Exception, e: if type(e) != urllib2.HTTPError or e.code != 500: # only retry on HTTP 500 error raise print >>sys.stderr, "Loading "+request_path+": "+ExceptionDetail()+"; trying again in 2 seconds." time.sleep(2) return MySend1(request_path, payload, content_type, timeout, force_auth, **kwargs) # Like upload.py Send but only authenticates when the # redirect is to www.google.com/accounts. This keeps # unnecessary redirects from happening during testing. def MySend1(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. global rpc if rpc == None: rpc = GetRpcServer(upload_options) self = rpc if not self.authenticated and force_auth: self._Authenticate() if request_path is None: return old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() # Translate \r\n into \n, because Rietveld doesn't. response = response.replace('\r\n', '\n') # who knows what urllib will give us if type(response) == unicode: response = response.encode("utf-8") typecheck(response, str) return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401: self._Authenticate() elif e.code == 302: loc = e.info()["location"] if not loc.startswith('https://www.google.com/a') or loc.find('/ServiceLogin') < 0: return '' self._Authenticate() else: raise finally: socket.setdefaulttimeout(old_timeout) def GetForm(url): f = FormParser() f.feed(ustr(MySend(url))) # f.feed wants unicode f.close() # convert back to utf-8 to restore sanity m = {} for k,v in f.map.items(): m[k.encode("utf-8")] = v.replace("\r\n", "\n").encode("utf-8") return m def EditDesc(issue, subject=None, desc=None, reviewers=None, cc=None, closed=False, private=False): set_status("uploading change to description") form_fields = GetForm("/" + issue + "/edit") if subject is not None: form_fields['subject'] = subject if desc is not None: form_fields['description'] = desc if reviewers is not None: form_fields['reviewers'] = reviewers if cc is not None: form_fields['cc'] = cc if closed: form_fields['closed'] = "checked" if private: form_fields['private'] = "checked" ctype, body = EncodeMultipartFormData(form_fields.items(), []) response = MySend("/" + issue + "/edit", body, content_type=ctype) if response != "": print >>sys.stderr, "Error editing description:\n" + "Sent form: \n", form_fields, "\n", response sys.exit(2) def PostMessage(ui, issue, message, reviewers=None, cc=None, send_mail=True, subject=None): set_status("uploading message") form_fields = GetForm("/" + issue + "/publish") if reviewers is not None: form_fields['reviewers'] = reviewers if cc is not None: form_fields['cc'] = cc if send_mail: form_fields['send_mail'] = "checked" else: del form_fields['send_mail'] if subject is not None: form_fields['subject'] = subject form_fields['message'] = message form_fields['message_only'] = '1' # Don't include draft comments if reviewers is not None or cc is not None: form_fields['message_only'] = '' # Must set '' in order to override cc/reviewer ctype = "applications/x-www-form-urlencoded" body = urllib.urlencode(form_fields) response = MySend("/" + issue + "/publish", body, content_type=ctype) if response != "": print response sys.exit(2) class opt(object): pass def nocommit(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use mail, upload, or submit instead of commit") def nobackout(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use undo instead of backout") def norollback(*pats, **opts): """(disabled when using this extension)""" raise util.Abort("codereview extension enabled; use undo instead of rollback") def RietveldSetup(ui, repo): global defaultcc, upload_options, rpc, server, server_url_base, force_google_account, verbosity, contributors global missing_codereview repo_config_path = '' # Read repository-specific options from lib/codereview/codereview.cfg try: repo_config_path = repo.root + '/lib/codereview/codereview.cfg' f = open(repo_config_path) for line in f: if line.startswith('defaultcc: '): defaultcc = SplitCommaSpace(line[10:]) except: # If there are no options, chances are good this is not # a code review repository; stop now before we foul # things up even worse. Might also be that repo doesn't # even have a root. See issue 959. if repo_config_path == '': missing_codereview = 'codereview disabled: repository has no root' else: missing_codereview = 'codereview disabled: cannot open ' + repo_config_path return # Should only modify repository with hg submit. # Disable the built-in Mercurial commands that might # trip things up. cmdutil.commit = nocommit global real_rollback real_rollback = repo.rollback repo.rollback = norollback # would install nobackout if we could; oh well try: f = open(repo.root + '/CONTRIBUTORS', 'r') except: raise util.Abort("cannot open %s: %s" % (repo.root+'/CONTRIBUTORS', ExceptionDetail())) for line in f: # CONTRIBUTORS is a list of lines like: # Person <email> # Person <email> <alt-email> # The first email address is the one used in commit logs. if line.startswith('#'): continue m = re.match(r"([^<>]+\S)\s+(<[^<>\s]+>)((\s+<[^<>\s]+>)*)\s*$", line) if m: name = m.group(1) email = m.group(2)[1:-1] contributors[email.lower()] = (name, email) for extra in m.group(3).split(): contributors[extra[1:-1].lower()] = (name, email) if not ui.verbose: verbosity = 0 # Config options. x = ui.config("codereview", "server") if x is not None: server = x # TODO(rsc): Take from ui.username? email = None x = ui.config("codereview", "email") if x is not None: email = x server_url_base = "http://" + server + "/" testing = ui.config("codereview", "testing") force_google_account = ui.configbool("codereview", "force_google_account", False) upload_options = opt() upload_options.email = email upload_options.host = None upload_options.verbose = 0 upload_options.description = None upload_options.description_file = None upload_options.reviewers = None upload_options.cc = None upload_options.message = None upload_options.issue = None upload_options.download_base = False upload_options.revision = None upload_options.send_mail = False upload_options.vcs = None upload_options.server = server upload_options.save_cookies = True if testing: upload_options.save_cookies = False upload_options.email = "test@example.com" rpc = None global releaseBranch tags = repo.branchtags().keys() if 'release-branch.r100' in tags: # NOTE(rsc): This tags.sort is going to get the wrong # answer when comparing release-branch.r99 with # release-branch.r100. If we do ten releases a year # that gives us 4 years before we have to worry about this. raise util.Abort('tags.sort needs to be fixed for release-branch.r100') tags.sort() for t in tags: if t.startswith('release-branch.'): releaseBranch = t ####################################################################### # http://codereview.appspot.com/static/upload.py, heavily edited. #!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Tool for uploading diffs from a version control system to the codereview app. Usage summary: upload.py [options] [-- diff_options] Diff options are passed to the diff command of the underlying system. Supported version control systems: Git Mercurial Subversion It is important for Git/Mercurial users to specify a tree/node/branch to diff against by using the '--rev' option. """ # This code is derived from appcfg.py in the App Engine SDK (open source), # and from ASPN recipe #146306. import cookielib import getpass import logging import mimetypes import optparse import os import re import socket import subprocess import sys import urllib import urllib2 import urlparse # The md5 module was deprecated in Python 2.5. try: from hashlib import md5 except ImportError: from md5 import md5 try: import readline except ImportError: pass # The logging verbosity: # 0: Errors only. # 1: Status messages. # 2: Info logs. # 3: Debug logs. verbosity = 1 # Max size of patch or base file. MAX_UPLOAD_SIZE = 900 * 1024 # whitelist for non-binary filetypes which do not start with "text/" # .mm (Objective-C) shows up as application/x-freemind on my Linux box. TEXT_MIMETYPES = [ 'application/javascript', 'application/x-javascript', 'application/x-freemind' ] def GetEmail(prompt): """Prompts the user for their email address and returns it. The last used email address is saved to a file and offered up as a suggestion to the user. If the user presses enter without typing in anything the last used email address is used. If the user enters a new address, it is saved for next time we prompt. """ last_email_file_name = os.path.expanduser("~/.last_codereview_email_address") last_email = "" if os.path.exists(last_email_file_name): try: last_email_file = open(last_email_file_name, "r") last_email = last_email_file.readline().strip("\n") last_email_file.close() prompt += " [%s]" % last_email except IOError, e: pass email = raw_input(prompt + ": ").strip() if email: try: last_email_file = open(last_email_file_name, "w") last_email_file.write(email) last_email_file.close() except IOError, e: pass else: email = last_email return email def StatusUpdate(msg): """Print a status message to stdout. If 'verbosity' is greater than 0, print the message. Args: msg: The string to print. """ if verbosity > 0: print msg def ErrorExit(msg): """Print an error message to stderr and exit.""" print >>sys.stderr, msg sys.exit(1) class ClientLoginError(urllib2.HTTPError): """Raised to indicate there was an error authenticating with ClientLogin.""" def __init__(self, url, code, msg, headers, args): urllib2.HTTPError.__init__(self, url, code, msg, headers, None) self.args = args self.reason = args["Error"] class AbstractRpcServer(object): """Provides a common interface for a simple RPC server.""" def __init__(self, host, auth_function, host_override=None, extra_headers={}, save_cookies=False): """Creates a new HttpRpcServer. Args: host: The host to send requests to. auth_function: A function that takes no arguments and returns an (email, password) tuple when called. Will be called if authentication is required. host_override: The host header to send to the server (defaults to host). extra_headers: A dict of extra headers to append to every request. save_cookies: If True, save the authentication cookies to local disk. If False, use an in-memory cookiejar instead. Subclasses must implement this functionality. Defaults to False. """ self.host = host self.host_override = host_override self.auth_function = auth_function self.authenticated = False self.extra_headers = extra_headers self.save_cookies = save_cookies self.opener = self._GetOpener() if self.host_override: logging.info("Server: %s; Host: %s", self.host, self.host_override) else: logging.info("Server: %s", self.host) def _GetOpener(self): """Returns an OpenerDirector for making HTTP requests. Returns: A urllib2.OpenerDirector object. """ raise NotImplementedError() def _CreateRequest(self, url, data=None): """Creates a new urllib request.""" logging.debug("Creating request for: '%s' with payload:\n%s", url, data) req = urllib2.Request(url, data=data) if self.host_override: req.add_header("Host", self.host_override) for key, value in self.extra_headers.iteritems(): req.add_header(key, value) return req def _GetAuthToken(self, email, password): """Uses ClientLogin to authenticate the user, returning an auth token. Args: email: The user's email address password: The user's password Raises: ClientLoginError: If there was an error authenticating with ClientLogin. HTTPError: If there was some other form of HTTP error. Returns: The authentication token returned by ClientLogin. """ account_type = "GOOGLE" if self.host.endswith(".google.com") and not force_google_account: # Needed for use inside Google. account_type = "HOSTED" req = self._CreateRequest( url="https://www.google.com/accounts/ClientLogin", data=urllib.urlencode({ "Email": email, "Passwd": password, "service": "ah", "source": "rietveld-codereview-upload", "accountType": account_type, }), ) try: response = self.opener.open(req) response_body = response.read() response_dict = dict(x.split("=") for x in response_body.split("\n") if x) return response_dict["Auth"] except urllib2.HTTPError, e: if e.code == 403: body = e.read() response_dict = dict(x.split("=", 1) for x in body.split("\n") if x) raise ClientLoginError(req.get_full_url(), e.code, e.msg, e.headers, response_dict) else: raise def _GetAuthCookie(self, auth_token): """Fetches authentication cookies for an authentication token. Args: auth_token: The authentication token returned by ClientLogin. Raises: HTTPError: If there was an error fetching the authentication cookies. """ # This is a dummy value to allow us to identify when we're successful. continue_location = "http://localhost/" args = {"continue": continue_location, "auth": auth_token} req = self._CreateRequest("http://%s/_ah/login?%s" % (self.host, urllib.urlencode(args))) try: response = self.opener.open(req) except urllib2.HTTPError, e: response = e if (response.code != 302 or response.info()["location"] != continue_location): raise urllib2.HTTPError(req.get_full_url(), response.code, response.msg, response.headers, response.fp) self.authenticated = True def _Authenticate(self): """Authenticates the user. The authentication process works as follows: 1) We get a username and password from the user 2) We use ClientLogin to obtain an AUTH token for the user (see http://code.google.com/apis/accounts/AuthForInstalledApps.html). 3) We pass the auth token to /_ah/login on the server to obtain an authentication cookie. If login was successful, it tries to redirect us to the URL we provided. If we attempt to access the upload API without first obtaining an authentication cookie, it returns a 401 response (or a 302) and directs us to authenticate ourselves with ClientLogin. """ for i in range(3): credentials = self.auth_function() try: auth_token = self._GetAuthToken(credentials[0], credentials[1]) except ClientLoginError, e: if e.reason == "BadAuthentication": print >>sys.stderr, "Invalid username or password." continue if e.reason == "CaptchaRequired": print >>sys.stderr, ( "Please go to\n" "https://www.google.com/accounts/DisplayUnlockCaptcha\n" "and verify you are a human. Then try again.") break if e.reason == "NotVerified": print >>sys.stderr, "Account not verified." break if e.reason == "TermsNotAgreed": print >>sys.stderr, "User has not agreed to TOS." break if e.reason == "AccountDeleted": print >>sys.stderr, "The user account has been deleted." break if e.reason == "AccountDisabled": print >>sys.stderr, "The user account has been disabled." break if e.reason == "ServiceDisabled": print >>sys.stderr, "The user's access to the service has been disabled." break if e.reason == "ServiceUnavailable": print >>sys.stderr, "The service is not available; try again later." break raise self._GetAuthCookie(auth_token) return def Send(self, request_path, payload=None, content_type="application/octet-stream", timeout=None, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an empty request. content_type: The Content-Type header to use. timeout: timeout in seconds; default None i.e. no timeout. (Note: for large requests on OS X, the timeout doesn't work right.) kwargs: Any keyword arguments are converted into query string parameters. Returns: The response body, as a string. """ # TODO: Don't require authentication. Let the server say # whether it is necessary. if not self.authenticated: self._Authenticate() old_timeout = socket.getdefaulttimeout() socket.setdefaulttimeout(timeout) try: tries = 0 while True: tries += 1 args = dict(kwargs) url = "http://%s%s" % (self.host, request_path) if args: url += "?" + urllib.urlencode(args) req = self._CreateRequest(url=url, data=payload) req.add_header("Content-Type", content_type) try: f = self.opener.open(req) response = f.read() f.close() return response except urllib2.HTTPError, e: if tries > 3: raise elif e.code == 401 or e.code == 302: self._Authenticate() else: raise finally: socket.setdefaulttimeout(old_timeout) class HttpRpcServer(AbstractRpcServer): """Provides a simplified RPC-style interface for HTTP requests.""" def _Authenticate(self): """Save the cookie jar after authentication.""" super(HttpRpcServer, self)._Authenticate() if self.save_cookies: StatusUpdate("Saving authentication cookies to %s" % self.cookie_file) self.cookie_jar.save() def _GetOpener(self): """Returns an OpenerDirector that supports cookies and ignores redirects. Returns: A urllib2.OpenerDirector object. """ opener = urllib2.OpenerDirector() opener.add_handler(urllib2.ProxyHandler()) opener.add_handler(urllib2.UnknownHandler()) opener.add_handler(urllib2.HTTPHandler()) opener.add_handler(urllib2.HTTPDefaultErrorHandler()) opener.add_handler(urllib2.HTTPSHandler()) opener.add_handler(urllib2.HTTPErrorProcessor()) if self.save_cookies: self.cookie_file = os.path.expanduser("~/.codereview_upload_cookies_" + server) self.cookie_jar = cookielib.MozillaCookieJar(self.cookie_file) if os.path.exists(self.cookie_file): try: self.cookie_jar.load() self.authenticated = True StatusUpdate("Loaded authentication cookies from %s" % self.cookie_file) except (cookielib.LoadError, IOError): # Failed to load cookies - just ignore them. pass else: # Create an empty cookie file with mode 600 fd = os.open(self.cookie_file, os.O_CREAT, 0600) os.close(fd) # Always chmod the cookie file os.chmod(self.cookie_file, 0600) else: # Don't save cookies across runs of update.py. self.cookie_jar = cookielib.CookieJar() opener.add_handler(urllib2.HTTPCookieProcessor(self.cookie_jar)) return opener def GetRpcServer(options): """Returns an instance of an AbstractRpcServer. Returns: A new AbstractRpcServer, on which RPC calls can be made. """ rpc_server_class = HttpRpcServer def GetUserCredentials(): """Prompts the user for a username and password.""" # Disable status prints so they don't obscure the password prompt. global global_status st = global_status global_status = None email = options.email if email is None: email = GetEmail("Email (login for uploading to %s)" % options.server) password = getpass.getpass("Password for %s: " % email) # Put status back. global_status = st return (email, password) # If this is the dev_appserver, use fake authentication. host = (options.host or options.server).lower() if host == "localhost" or host.startswith("localhost:"): email = options.email if email is None: email = "test@example.com" logging.info("Using debug user %s. Override with --email" % email) server = rpc_server_class( options.server, lambda: (email, "password"), host_override=options.host, extra_headers={"Cookie": 'dev_appserver_login="%s:False"' % email}, save_cookies=options.save_cookies) # Don't try to talk to ClientLogin. server.authenticated = True return server return rpc_server_class(options.server, GetUserCredentials, host_override=options.host, save_cookies=options.save_cookies) def EncodeMultipartFormData(fields, files): """Encode form fields for multipart/form-data. Args: fields: A sequence of (name, value) elements for regular form fields. files: A sequence of (name, filename, value) elements for data to be uploaded as files. Returns: (content_type, body) ready for httplib.HTTP instance. Source: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 """ BOUNDARY = '-M-A-G-I-C---B-O-U-N-D-A-R-Y-' CRLF = '\r\n' lines = [] for (key, value) in fields: typecheck(key, str) typecheck(value, str) lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"' % key) lines.append('') lines.append(value) for (key, filename, value) in files: typecheck(key, str) typecheck(filename, str) typecheck(value, str) lines.append('--' + BOUNDARY) lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename)) lines.append('Content-Type: %s' % GetContentType(filename)) lines.append('') lines.append(value) lines.append('--' + BOUNDARY + '--') lines.append('') body = CRLF.join(lines) content_type = 'multipart/form-data; boundary=%s' % BOUNDARY return content_type, body def GetContentType(filename): """Helper to guess the content-type from the filename.""" return mimetypes.guess_type(filename)[0] or 'application/octet-stream' # Use a shell for subcommands on Windows to get a PATH search. use_shell = sys.platform.startswith("win") def RunShellWithReturnCode(command, print_output=False, universal_newlines=True, env=os.environ): """Executes a command and returns the output from stdout and the return code. Args: command: Command to execute. print_output: If True, the output is printed to stdout. If False, both stdout and stderr are ignored. universal_newlines: Use universal_newlines flag (default: True). Returns: Tuple (output, return code) """ logging.info("Running %s", command) p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=use_shell, universal_newlines=universal_newlines, env=env) if print_output: output_array = [] while True: line = p.stdout.readline() if not line: break print line.strip("\n") output_array.append(line) output = "".join(output_array) else: output = p.stdout.read() p.wait() errout = p.stderr.read() if print_output and errout: print >>sys.stderr, errout p.stdout.close() p.stderr.close() return output, p.returncode def RunShell(command, silent_ok=False, universal_newlines=True, print_output=False, env=os.environ): data, retcode = RunShellWithReturnCode(command, print_output, universal_newlines, env) if retcode: ErrorExit("Got error status from %s:\n%s" % (command, data)) if not silent_ok and not data: ErrorExit("No output from %s" % command) return data class VersionControlSystem(object): """Abstract base class providing an interface to the VCS.""" def __init__(self, options): """Constructor. Args: options: Command line options. """ self.options = options def GenerateDiff(self, args): """Return the current diff as a string. Args: args: Extra arguments to pass to the diff command. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def CheckForUnknownFiles(self): """Show an "are you sure?" prompt if there are unknown files.""" unknown_files = self.GetUnknownFiles() if unknown_files: print "The following files are not added to version control:" for line in unknown_files: print line prompt = "Are you sure to continue?(y/N) " answer = raw_input(prompt).strip() if answer != "y": ErrorExit("User aborted") def GetBaseFile(self, filename): """Get the content of the upstream version of a file. Returns: A tuple (base_content, new_content, is_binary, status) base_content: The contents of the base file. new_content: For text files, this is empty. For binary files, this is the contents of the new file, since the diff output won't contain information to reconstruct the current file. is_binary: True iff the file is binary. status: The status of the file. """ raise NotImplementedError( "abstract method -- subclass %s must override" % self.__class__) def GetBaseFiles(self, diff): """Helper that calls GetBase file for each file in the patch. Returns: A dictionary that maps from filename to GetBaseFile's tuple. Filenames are retrieved based on lines that start with "Index:" or "Property changes on:". """ files = {} for line in diff.splitlines(True): if line.startswith('Index:') or line.startswith('Property changes on:'): unused, filename = line.split(':', 1) # On Windows if a file has property changes its filename uses '\' # instead of '/'. filename = filename.strip().replace('\\', '/') files[filename] = self.GetBaseFile(filename) return files def UploadBaseFiles(self, issue, rpc_server, patch_list, patchset, options, files): """Uploads the base files (and if necessary, the current ones as well).""" def UploadFile(filename, file_id, content, is_binary, status, is_base): """Uploads a file to the server.""" set_status("uploading " + filename) file_too_large = False if is_base: type = "base" else: type = "current" if len(content) > MAX_UPLOAD_SIZE: print ("Not uploading the %s file for %s because it's too large." % (type, filename)) file_too_large = True content = "" checksum = md5(content).hexdigest() if options.verbose > 0 and not file_too_large: print "Uploading %s file for %s" % (type, filename) url = "/%d/upload_content/%d/%d" % (int(issue), int(patchset), file_id) form_fields = [ ("filename", filename), ("status", status), ("checksum", checksum), ("is_binary", str(is_binary)), ("is_current", str(not is_base)), ] if file_too_large: form_fields.append(("file_too_large", "1")) if options.email: form_fields.append(("user", options.email)) ctype, body = EncodeMultipartFormData(form_fields, [("data", filename, content)]) response_body = rpc_server.Send(url, body, content_type=ctype) if not response_body.startswith("OK"): StatusUpdate(" --> %s" % response_body) sys.exit(1) # Don't want to spawn too many threads, nor do we want to # hit Rietveld too hard, or it will start serving 500 errors. # When 8 works, it's no better than 4, and sometimes 8 is # too many for Rietveld to handle. MAX_PARALLEL_UPLOADS = 4 sema = threading.BoundedSemaphore(MAX_PARALLEL_UPLOADS) upload_threads = [] finished_upload_threads = [] class UploadFileThread(threading.Thread): def __init__(self, args): threading.Thread.__init__(self) self.args = args def run(self): UploadFile(*self.args) finished_upload_threads.append(self) sema.release() def StartUploadFile(*args): sema.acquire() while len(finished_upload_threads) > 0: t = finished_upload_threads.pop() upload_threads.remove(t) t.join() t = UploadFileThread(args) upload_threads.append(t) t.start() def WaitForUploads(): for t in upload_threads: t.join() patches = dict() [patches.setdefault(v, k) for k, v in patch_list] for filename in patches.keys(): base_content, new_content, is_binary, status = files[filename] file_id_str = patches.get(filename) if file_id_str.find("nobase") != -1: base_content = None file_id_str = file_id_str[file_id_str.rfind("_") + 1:] file_id = int(file_id_str) if base_content != None: StartUploadFile(filename, file_id, base_content, is_binary, status, True) if new_content != None: StartUploadFile(filename, file_id, new_content, is_binary, status, False) WaitForUploads() def IsImage(self, filename): """Returns true if the filename has an image extension.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False return mimetype.startswith("image/") def IsBinary(self, filename): """Returns true if the guessed mimetyped isnt't in text group.""" mimetype = mimetypes.guess_type(filename)[0] if not mimetype: return False # e.g. README, "real" binaries usually have an extension # special case for text files which don't start with text/ if mimetype in TEXT_MIMETYPES: return False return not mimetype.startswith("text/") class FakeMercurialUI(object): def __init__(self): self.quiet = True self.output = '' def write(self, *args, **opts): self.output += ' '.join(args) use_hg_shell = False # set to True to shell out to hg always; slower class MercurialVCS(VersionControlSystem): """Implementation of the VersionControlSystem interface for Mercurial.""" def __init__(self, options, ui, repo): super(MercurialVCS, self).__init__(options) self.ui = ui self.repo = repo # Absolute path to repository (we can be in a subdir) self.repo_dir = os.path.normpath(repo.root) # Compute the subdir cwd = os.path.normpath(os.getcwd()) assert cwd.startswith(self.repo_dir) self.subdir = cwd[len(self.repo_dir):].lstrip(r"\/") if self.options.revision: self.base_rev = self.options.revision else: mqparent, err = RunShellWithReturnCode(['hg', 'log', '--rev', 'qparent', '--template={node}']) if not err and mqparent != "": self.base_rev = mqparent else: self.base_rev = RunShell(["hg", "parents", "-q"]).split(':')[1].strip() def _GetRelPath(self, filename): """Get relative path of a file according to the current directory, given its logical path in the repo.""" assert filename.startswith(self.subdir), (filename, self.subdir) return filename[len(self.subdir):].lstrip(r"\/") def GenerateDiff(self, extra_args): # If no file specified, restrict to the current subdir extra_args = extra_args or ["."] cmd = ["hg", "diff", "--git", "-r", self.base_rev] + extra_args data = RunShell(cmd, silent_ok=True) svndiff = [] filecount = 0 for line in data.splitlines(): m = re.match("diff --git a/(\S+) b/(\S+)", line) if m: # Modify line to make it look like as it comes from svn diff. # With this modification no changes on the server side are required # to make upload.py work with Mercurial repos. # NOTE: for proper handling of moved/copied files, we have to use # the second filename. filename = m.group(2) svndiff.append("Index: %s" % filename) svndiff.append("=" * 67) filecount += 1 logging.info(line) else: svndiff.append(line) if not filecount: ErrorExit("No valid patches found in output from hg diff") return "\n".join(svndiff) + "\n" def GetUnknownFiles(self): """Return a list of files unknown to the VCS.""" args = [] status = RunShell(["hg", "status", "--rev", self.base_rev, "-u", "."], silent_ok=True) unknown_files = [] for line in status.splitlines(): st, fn = line.split(" ", 1) if st == "?": unknown_files.append(fn) return unknown_files def GetBaseFile(self, filename): set_status("inspecting " + filename) # "hg status" and "hg cat" both take a path relative to the current subdir # rather than to the repo root, but "hg diff" has given us the full path # to the repo root. base_content = "" new_content = None is_binary = False oldrelpath = relpath = self._GetRelPath(filename) # "hg status -C" returns two lines for moved/copied files, one otherwise if use_hg_shell: out = RunShell(["hg", "status", "-C", "--rev", self.base_rev, relpath]) else: fui = FakeMercurialUI() ret = commands.status(fui, self.repo, *[relpath], **{'rev': [self.base_rev], 'copies': True}) if ret: raise util.Abort(ret) out = fui.output out = out.splitlines() # HACK: strip error message about missing file/directory if it isn't in # the working copy if out[0].startswith('%s: ' % relpath): out = out[1:] status, what = out[0].split(' ', 1) if len(out) > 1 and status == "A" and what == relpath: oldrelpath = out[1].strip() status = "M" if ":" in self.base_rev: base_rev = self.base_rev.split(":", 1)[0] else: base_rev = self.base_rev if status != "A": if use_hg_shell: base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True) else: base_content = str(self.repo[base_rev][oldrelpath].data()) is_binary = "\0" in base_content # Mercurial's heuristic if status != "R": new_content = open(relpath, "rb").read() is_binary = is_binary or "\0" in new_content if is_binary and base_content and use_hg_shell: # Fetch again without converting newlines base_content = RunShell(["hg", "cat", "-r", base_rev, oldrelpath], silent_ok=True, universal_newlines=False) if not is_binary or not self.IsImage(relpath): new_content = None return base_content, new_content, is_binary, status # NOTE: The SplitPatch function is duplicated in engine.py, keep them in sync. def SplitPatch(data): """Splits a patch into separate pieces for each file. Args: data: A string containing the output of svn diff. Returns: A list of 2-tuple (filename, text) where text is the svn diff output pertaining to filename. """ patches = [] filename = None diff = [] for line in data.splitlines(True): new_filename = None if line.startswith('Index:'): unused, new_filename = line.split(':', 1) new_filename = new_filename.strip() elif line.startswith('Property changes on:'): unused, temp_filename = line.split(':', 1) # When a file is modified, paths use '/' between directories, however # when a property is modified '\' is used on Windows. Make them the same # otherwise the file shows up twice. temp_filename = temp_filename.strip().replace('\\', '/') if temp_filename != filename: # File has property changes but no modifications, create a new diff. new_filename = temp_filename if new_filename: if filename and diff: patches.append((filename, ''.join(diff))) filename = new_filename diff = [line] continue if diff is not None: diff.append(line) if filename and diff: patches.append((filename, ''.join(diff))) return patches def UploadSeparatePatches(issue, rpc_server, patchset, data, options): """Uploads a separate patch for each file in the diff output. Returns a list of [patch_key, filename] for each file. """ patches = SplitPatch(data) rv = [] for patch in patches: set_status("uploading patch for " + patch[0]) if len(patch[1]) > MAX_UPLOAD_SIZE: print ("Not uploading the patch for " + patch[0] + " because the file is too large.") continue form_fields = [("filename", patch[0])] if not options.download_base: form_fields.append(("content_upload", "1")) files = [("data", "data.diff", patch[1])] ctype, body = EncodeMultipartFormData(form_fields, files) url = "/%d/upload_patch/%d" % (int(issue), int(patchset)) print "Uploading patch for " + patch[0] response_body = rpc_server.Send(url, body, content_type=ctype) lines = response_body.splitlines() if not lines or lines[0] != "OK": StatusUpdate(" --> %s" % response_body) sys.exit(1) rv.append([lines[1], patch[0]]) return rv
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python # # Copyright 2006, 2007 Google Inc. All Rights Reserved. # Author: danderson@google.com (David Anderson) # # Script for uploading files to a Google Code project. # # This is intended to be both a useful script for people who want to # streamline project uploads and a reference implementation for # uploading files to Google Code projects. # # To upload a file to Google Code, you need to provide a path to the # file on your local machine, a small summary of what the file is, a # project name, and a valid account that is a member or owner of that # project. You can optionally provide a list of labels that apply to # the file. The file will be uploaded under the same name that it has # in your local filesystem (that is, the "basename" or last path # component). Run the script with '--help' to get the exact syntax # and available options. # # Note that the upload script requests that you enter your # googlecode.com password. This is NOT your Gmail account password! # This is the password you use on googlecode.com for committing to # Subversion and uploading files. You can find your password by going # to http://code.google.com/hosting/settings when logged in with your # Gmail account. If you have already committed to your project's # Subversion repository, the script will automatically retrieve your # credentials from there (unless disabled, see the output of '--help' # for details). # # If you are looking at this script as a reference for implementing # your own Google Code file uploader, then you should take a look at # the upload() function, which is the meat of the uploader. You # basically need to build a multipart/form-data POST request with the # right fields and send it to https://PROJECT.googlecode.com/files . # Authenticate the request using HTTP Basic authentication, as is # shown below. # # Licensed under the terms of the Apache Software License 2.0: # http://www.apache.org/licenses/LICENSE-2.0 # # Questions, comments, feature requests and patches are most welcome. # Please direct all of these to the Google Code users group: # http://groups.google.com/group/google-code-hosting """Google Code file uploader script. """ __author__ = 'danderson@google.com (David Anderson)' import httplib import os.path import optparse import getpass import base64 import sys def upload(file, project_name, user_name, password, summary, labels=None): """Upload a file to a Google Code project's file server. Args: file: The local path to the file. project_name: The name of your project on Google Code. user_name: Your Google account name. password: The googlecode.com password for your account. Note that this is NOT your global Google Account password! summary: A small description for the file. labels: an optional list of label strings with which to tag the file. Returns: a tuple: http_status: 201 if the upload succeeded, something else if an error occured. http_reason: The human-readable string associated with http_status file_url: If the upload succeeded, the URL of the file on Google Code, None otherwise. """ # The login is the user part of user@gmail.com. If the login provided # is in the full user@domain form, strip it down. if user_name.endswith('@gmail.com'): user_name = user_name[:user_name.index('@gmail.com')] form_fields = [('summary', summary)] if labels is not None: form_fields.extend([('label', l.strip()) for l in labels]) content_type, body = encode_upload_request(form_fields, file) upload_host = '%s.googlecode.com' % project_name upload_uri = '/files' auth_token = base64.b64encode('%s:%s'% (user_name, password)) headers = { 'Authorization': 'Basic %s' % auth_token, 'User-Agent': 'Googlecode.com uploader v0.9.4', 'Content-Type': content_type, } server = httplib.HTTPSConnection(upload_host) server.request('POST', upload_uri, body, headers) resp = server.getresponse() server.close() if resp.status == 201: location = resp.getheader('Location', None) else: location = None return resp.status, resp.reason, location def encode_upload_request(fields, file_path): """Encode the given fields and file into a multipart form body. fields is a sequence of (name, value) pairs. file is the path of the file to upload. The file will be uploaded to Google Code with the same file name. Returns: (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '----------Googlecode_boundary_reindeer_flotilla' CRLF = '\r\n' body = [] # Add the metadata about the upload first for key, value in fields: body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="%s"' % key, '', value, ]) # Now add the file itself file_name = os.path.basename(file_path) f = open(file_path, 'rb') file_content = f.read() f.close() body.extend( ['--' + BOUNDARY, 'Content-Disposition: form-data; name="filename"; filename="%s"' % file_name, # The upload server determines the mime-type, no need to set it. 'Content-Type: application/octet-stream', '', file_content, ]) # Finalize the form body body.extend(['--' + BOUNDARY + '--', '']) return 'multipart/form-data; boundary=%s' % BOUNDARY, CRLF.join(body) def upload_find_auth(file_path, project_name, summary, labels=None, user_name=None, password=None, tries=3): """Find credentials and upload a file to a Google Code project's file server. file_path, project_name, summary, and labels are passed as-is to upload. Args: file_path: The local path to the file. project_name: The name of your project on Google Code. summary: A small description for the file. labels: an optional list of label strings with which to tag the file. config_dir: Path to Subversion configuration directory, 'none', or None. user_name: Your Google account name. tries: How many attempts to make. """ while tries > 0: if user_name is None: # Read username if not specified or loaded from svn config, or on # subsequent tries. sys.stdout.write('Please enter your googlecode.com username: ') sys.stdout.flush() user_name = sys.stdin.readline().rstrip() if password is None: # Read password if not loaded from svn config, or on subsequent tries. print 'Please enter your googlecode.com password.' print '** Note that this is NOT your Gmail account password! **' print 'It is the password you use to access Subversion repositories,' print 'and can be found here: http://code.google.com/hosting/settings' password = getpass.getpass() status, reason, url = upload(file_path, project_name, user_name, password, summary, labels) # Returns 403 Forbidden instead of 401 Unauthorized for bad # credentials as of 2007-07-17. if status in [httplib.FORBIDDEN, httplib.UNAUTHORIZED]: # Rest for another try. user_name = password = None tries = tries - 1 else: # We're done. break return status, reason, url def main(): parser = optparse.OptionParser(usage='googlecode-upload.py -s SUMMARY ' '-p PROJECT [options] FILE') parser.add_option('-s', '--summary', dest='summary', help='Short description of the file') parser.add_option('-p', '--project', dest='project', help='Google Code project name') parser.add_option('-u', '--user', dest='user', help='Your Google Code username') parser.add_option('-w', '--password', dest='password', help='Your Google Code password') parser.add_option('-l', '--labels', dest='labels', help='An optional list of comma-separated labels to attach ' 'to the file') options, args = parser.parse_args() if not options.summary: parser.error('File summary is missing.') elif not options.project: parser.error('Project name is missing.') elif len(args) < 1: parser.error('File to upload not provided.') elif len(args) > 1: parser.error('Only one file may be specified.') file_path = args[0] if options.labels: labels = options.labels.split(',') else: labels = None status, reason, url = upload_find_auth(file_path, options.project, options.summary, labels, options.user, options.password) if url: print 'The file was uploaded successfully.' print 'URL: %s' % url return 0 else: print 'An error occurred. Your file was not uploaded.' print 'Google Code upload server said: %s (%s)' % (reason, status) return 1 if __name__ == '__main__': sys.exit(main())
Python
#!/usr/bin/env python3 import random class MastermindGame(): def __init__(self): self._generated_string = "" used_digits = set() for i in range(4): digit = random.randrange(0, 10, 1) while digit in used_digits: digit = random.randrange(0, 10, 1) used_digits.add(digit) self._generated_string += str(digit) def guess(self, attempt_string): if len(attempt_string) != len(self._generated_string): return False bulls = 0 cows = 0 used_digits = set() for digit1, digit2 in zip(self._generated_string, attempt_string): if digit1 == digit2: bulls += 1 else: used_digits.add(digit1) for digit in attempt_string: if digit in used_digits: cows += 1 if bulls == 4: return "Epic Win, bro!" return (bulls, cows) if __name__ == "__main__": game = MastermindGame() while 1: s = input() print(game.guess(s))
Python
#!/usr/bin/env python3 import random class MastermindGame(): def __init__(self): self._generated_string = "" used_digits = set() for i in range(4): digit = random.randrange(0, 10, 1) while digit in used_digits: digit = random.randrange(0, 10, 1) used_digits.add(digit) self._generated_string += str(digit) def guess(self, attempt_string): if len(attempt_string) != len(self._generated_string): return False bulls = 0 cows = 0 used_digits = set() for digit1, digit2 in zip(self._generated_string, attempt_string): if digit1 == digit2: bulls += 1 else: used_digits.add(digit1) for digit in attempt_string: if digit in used_digits: cows += 1 if bulls == 4: return "Epic Win, bro!" return (bulls, cows) if __name__ == "__main__": game = MastermindGame() while 1: s = input() print(game.guess(s))
Python
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") use_autocommit = yesno("Use autocommit?") use_executemany= yesno("Use executemany?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def create_db(): con = sqlite.connect(":memory:") if use_autocommit: if use_pysqlite2: con.isolation_level = None else: con.autocommit = True cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) cur.close() return con def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con = create_db() cur = con.cursor() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" starttime = time.time() for i in range(50): if use_executemany: cur.executemany(sql, l) else: for r in l: cur.execute(sql, r) endtime = time.time() print "elapsed", endtime - starttime cur.execute("select count(*) from test") print "rows:", cur.fetchone()[0] if __name__ == "__main__": test()
Python
import time def yesno(question): val = raw_input(question + " ") return val.startswith("y") or val.startswith("Y") use_pysqlite2 = yesno("Use pysqlite 2.0?") if use_pysqlite2: use_custom_types = yesno("Use custom types?") use_dictcursor = yesno("Use dict cursor?") use_rowcursor = yesno("Use row cursor?") else: use_tuple = yesno("Use rowclass=tuple?") if use_pysqlite2: from pysqlite2 import dbapi2 as sqlite else: import sqlite def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d if use_pysqlite2: def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d class DictCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = dict_factory class RowCursor(sqlite.Cursor): def __init__(self, *args, **kwargs): sqlite.Cursor.__init__(self, *args, **kwargs) self.row_factory = sqlite.Row def create_db(): if sqlite.version_info > (2, 0): if use_custom_types: con = sqlite.connect(":memory:", detect_types=sqlite.PARSE_DECLTYPES|sqlite.PARSE_COLNAMES) sqlite.register_converter("text", lambda x: "<%s>" % x) else: con = sqlite.connect(":memory:") if use_dictcursor: cur = con.cursor(factory=DictCursor) elif use_rowcursor: cur = con.cursor(factory=RowCursor) else: cur = con.cursor() else: if use_tuple: con = sqlite.connect(":memory:") con.rowclass = tuple cur = con.cursor() else: con = sqlite.connect(":memory:") cur = con.cursor() cur.execute(""" create table test(v text, f float, i integer) """) return (con, cur) def test(): row = ("sdfffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffasfd", 3.14, 42) l = [] for i in range(1000): l.append(row) con, cur = create_db() if sqlite.version_info > (2, 0): sql = "insert into test(v, f, i) values (?, ?, ?)" else: sql = "insert into test(v, f, i) values (%s, %s, %s)" for i in range(50): cur.executemany(sql, l) cur.execute("select count(*) as cnt from test") starttime = time.time() for i in range(50): cur.execute("select v, f, i from test") l = cur.fetchall() endtime = time.time() print "elapsed:", endtime - starttime if __name__ == "__main__": test()
Python
#!/usr/bin/env python from pysqlite2.test import test test()
Python
from pysqlite2 import dbapi2 as sqlite import os, threading def getcon(): #con = sqlite.connect("db", isolation_level=None, timeout=5.0) con = sqlite.connect(":memory:") cur = con.cursor() cur.execute("create table test(i, s)") for i in range(10): cur.execute("insert into test(i, s) values (?, 'asfd')", (i,)) con.commit() cur.close() return con def reader(what): con = getcon() while 1: cur = con.cursor() cur.execute("select i, s from test where i % 1000=?", (what,)) res = cur.fetchall() cur.close() con.close() def appender(): con = getcon() counter = 0 while 1: cur = con.cursor() cur.execute("insert into test(i, s) values (?, ?)", (counter, "foosadfasfasfsfafs")) #cur.execute("insert into test(foo) values (?)", (counter,)) counter += 1 if counter % 100 == 0: #print "appender committing", counter con.commit() cur.close() con.close() def updater(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: cur.execute("update test set s='foo' where i % 50=0") #print "updater committing", counter con.commit() cur.close() con.close() def deleter(): con = getcon() counter = 0 while 1: cur = con.cursor() counter += 1 if counter % 5 == 0: #print "deleter committing", counter cur.execute("delete from test where i % 20=0") con.commit() cur.close() con.close() threads = [] for i in range(10): continue threads.append(threading.Thread(target=lambda: reader(i))) for i in range(5): threads.append(threading.Thread(target=appender)) #threads.append(threading.Thread(target=updater)) #threads.append(threading.Thread(target=deleter)) for t in threads: t.start()
Python
# Gerhard Haering <gh@gharing.d> is responsible for the hacked version of this # module. # # This is a modified version of the bdist_wininst distutils command to make it # possible to build installers *with extension modules* on Unix. """distutils.command.bdist_wininst Implements the Distutils 'bdist_wininst' command: create a windows installer exe-program.""" # This module should be kept compatible with Python 2.1. __revision__ = "$Id: bdist_wininst.py 59620 2007-12-31 14:47:07Z christian.heimes $" import sys, os, string from distutils.core import Command from distutils.util import get_platform from distutils.dir_util import create_tree, remove_tree from distutils.errors import * from distutils.sysconfig import get_python_version from distutils import log class bdist_wininst (Command): description = "create an executable installer for MS Windows" user_options = [('bdist-dir=', None, "temporary directory for creating the distribution"), ('keep-temp', 'k', "keep the pseudo-installation tree around after " + "creating the distribution archive"), ('target-version=', None, "require a specific python version" + " on the target system"), ('no-target-compile', 'c', "do not compile .py to .pyc on the target system"), ('no-target-optimize', 'o', "do not compile .py to .pyo (optimized)" "on the target system"), ('dist-dir=', 'd', "directory to put final built distributions in"), ('bitmap=', 'b', "bitmap to use for the installer instead of python-powered logo"), ('title=', 't', "title to display on the installer background instead of default"), ('skip-build', None, "skip rebuilding everything (for testing/debugging)"), ('install-script=', None, "basename of installation script to be run after" "installation or before deinstallation"), ('pre-install-script=', None, "Fully qualified filename of a script to be run before " "any files are installed. This script need not be in the " "distribution"), ] boolean_options = ['keep-temp', 'no-target-compile', 'no-target-optimize', 'skip-build'] def initialize_options (self): self.bdist_dir = None self.keep_temp = 0 self.no_target_compile = 0 self.no_target_optimize = 0 self.target_version = None self.dist_dir = None self.bitmap = None self.title = None self.skip_build = 0 self.install_script = None self.pre_install_script = None # initialize_options() def finalize_options (self): if self.bdist_dir is None: bdist_base = self.get_finalized_command('bdist').bdist_base self.bdist_dir = os.path.join(bdist_base, 'wininst') if not self.target_version: self.target_version = "" if not self.skip_build and self.distribution.has_ext_modules(): short_version = get_python_version() if self.target_version and self.target_version != short_version: raise DistutilsOptionError, \ "target version can only be %s, or the '--skip_build'" \ " option must be specified" % (short_version,) self.target_version = short_version self.set_undefined_options('bdist', ('dist_dir', 'dist_dir')) if self.install_script: for script in self.distribution.scripts: if self.install_script == os.path.basename(script): break else: raise DistutilsOptionError, \ "install_script '%s' not found in scripts" % \ self.install_script # finalize_options() def run (self): # HACK I disabled this check. if 0 and (sys.platform != "win32" and (self.distribution.has_ext_modules() or self.distribution.has_c_libraries())): raise DistutilsPlatformError \ ("distribution contains extensions and/or C libraries; " "must be compiled on a Windows 32 platform") if not self.skip_build: self.run_command('build') install = self.reinitialize_command('install', reinit_subcommands=1) install.root = self.bdist_dir install.skip_build = self.skip_build install.warn_dir = 0 install_lib = self.reinitialize_command('install_lib') # we do not want to include pyc or pyo files install_lib.compile = 0 install_lib.optimize = 0 if self.distribution.has_ext_modules(): # If we are building an installer for a Python version other # than the one we are currently running, then we need to ensure # our build_lib reflects the other Python version rather than ours. # Note that for target_version!=sys.version, we must have skipped the # build step, so there is no issue with enforcing the build of this # version. target_version = self.target_version if not target_version: assert self.skip_build, "Should have already checked this" target_version = sys.version[0:3] plat_specifier = ".%s-%s" % (get_platform(), target_version) build = self.get_finalized_command('build') build.build_lib = os.path.join(build.build_base, 'lib' + plat_specifier) # Use a custom scheme for the zip-file, because we have to decide # at installation time which scheme to use. for key in ('purelib', 'platlib', 'headers', 'scripts', 'data'): value = string.upper(key) if key == 'headers': value = value + '/Include/$dist_name' setattr(install, 'install_' + key, value) log.info("installing to %s", self.bdist_dir) install.ensure_finalized() # avoid warning of 'install_lib' about installing # into a directory not in sys.path sys.path.insert(0, os.path.join(self.bdist_dir, 'PURELIB')) install.run() del sys.path[0] # And make an archive relative to the root of the # pseudo-installation tree. from tempfile import mktemp archive_basename = mktemp() fullname = self.distribution.get_fullname() arcname = self.make_archive(archive_basename, "zip", root_dir=self.bdist_dir) # create an exe containing the zip-file self.create_exe(arcname, fullname, self.bitmap) if self.distribution.has_ext_modules(): pyversion = get_python_version() else: pyversion = 'any' self.distribution.dist_files.append(('bdist_wininst', pyversion, self.get_installer_filename(fullname))) # remove the zip-file again log.debug("removing temporary file '%s'", arcname) os.remove(arcname) if not self.keep_temp: remove_tree(self.bdist_dir, dry_run=self.dry_run) # run() def get_inidata (self): # Return data describing the installation. lines = [] metadata = self.distribution.metadata # Write the [metadata] section. lines.append("[metadata]") # 'info' will be displayed in the installer's dialog box, # describing the items to be installed. info = (metadata.long_description or '') + '\n' # Escape newline characters def escape(s): return string.replace(s, "\n", "\\n") for name in ["author", "author_email", "description", "maintainer", "maintainer_email", "name", "url", "version"]: data = getattr(metadata, name, "") if data: info = info + ("\n %s: %s" % \ (string.capitalize(name), escape(data))) lines.append("%s=%s" % (name, escape(data))) # The [setup] section contains entries controlling # the installer runtime. lines.append("\n[Setup]") if self.install_script: lines.append("install_script=%s" % self.install_script) lines.append("info=%s" % escape(info)) lines.append("target_compile=%d" % (not self.no_target_compile)) lines.append("target_optimize=%d" % (not self.no_target_optimize)) if self.target_version: lines.append("target_version=%s" % self.target_version) title = self.title or self.distribution.get_fullname() lines.append("title=%s" % escape(title)) import time import distutils build_info = "Built %s with distutils-%s" % \ (time.ctime(time.time()), distutils.__version__) lines.append("build_info=%s" % build_info) return string.join(lines, "\n") # get_inidata() def create_exe (self, arcname, fullname, bitmap=None): import struct self.mkpath(self.dist_dir) cfgdata = self.get_inidata() installer_name = self.get_installer_filename(fullname) self.announce("creating %s" % installer_name) if bitmap: bitmapdata = open(bitmap, "rb").read() bitmaplen = len(bitmapdata) else: bitmaplen = 0 file = open(installer_name, "wb") file.write(self.get_exe_bytes()) if bitmap: file.write(bitmapdata) # Convert cfgdata from unicode to ascii, mbcs encoded try: unicode except NameError: pass else: if isinstance(cfgdata, unicode): cfgdata = cfgdata.encode("mbcs") # Append the pre-install script cfgdata = cfgdata + "\0" if self.pre_install_script: script_data = open(self.pre_install_script, "r").read() cfgdata = cfgdata + script_data + "\n\0" else: # empty pre-install script cfgdata = cfgdata + "\0" file.write(cfgdata) # The 'magic number' 0x1234567B is used to make sure that the # binary layout of 'cfgdata' is what the wininst.exe binary # expects. If the layout changes, increment that number, make # the corresponding changes to the wininst.exe sources, and # recompile them. header = struct.pack("<iii", 0x1234567B, # tag len(cfgdata), # length bitmaplen, # number of bytes in bitmap ) file.write(header) file.write(open(arcname, "rb").read()) # create_exe() def get_installer_filename(self, fullname): # Factored out to allow overriding in subclasses if self.target_version: # if we create an installer for a specific python version, # it's better to include this in the name installer_name = os.path.join(self.dist_dir, "%s.win32-py%s.exe" % (fullname, self.target_version)) else: installer_name = os.path.join(self.dist_dir, "%s.win32.exe" % fullname) return installer_name # get_installer_filename() def get_exe_bytes (self): from distutils.msvccompiler import get_build_version # If a target-version other than the current version has been # specified, then using the MSVC version from *this* build is no good. # Without actually finding and executing the target version and parsing # its sys.version, we just hard-code our knowledge of old versions. # NOTE: Possible alternative is to allow "--target-version" to # specify a Python executable rather than a simple version string. # We can then execute this program to obtain any info we need, such # as the real sys.version string for the build. cur_version = get_python_version() if self.target_version and self.target_version != cur_version: if self.target_version < "2.3": raise NotImplementedError elif self.target_version == "2.3": bv = "6" elif self.target_version in ("2.4", "2.5"): bv = "7.1" elif self.target_version in ("2.6", "2.7"): bv = "9.0" else: raise NotImplementedError else: # for current version - use authoritative check. bv = get_build_version() # wininst-x.y.exe is in the same directory as this file directory = os.path.dirname(__file__) # we must use a wininst-x.y.exe built with the same C compiler # used for python. XXX What about mingw, borland, and so on? # The uninstallers need to be available in $PYEXT_CROSS/uninst/*.exe # Use http://oss.itsystementwicklung.de/hg/pyext_cross_linux_to_win32/ # and copy it alongside your pysqlite checkout. filename = os.path.join(directory, os.path.join(os.environ["PYEXT_CROSS"], "uninst", "wininst-%s.exe" % bv)) return open(filename, "rb").read() # class bdist_wininst
Python
from __future__ import with_statement from pysqlite2 import dbapi2 as sqlite3 from datetime import datetime, timedelta import time def read_modify_write(): # Open connection and create example schema and data. # In reality, open a database file instead of an in-memory database. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, data); insert into test(data) values ('foo'); insert into test(data) values ('bar'); insert into test(data) values ('baz'); """) # The read part. There are two ways for fetching data using pysqlite. # 1. "Lazy-reading" # cur.execute("select ...") # for row in cur: # ... # # Advantage: Low memory consumption, good for large resultsets, data is # fetched on demand. # Disadvantage: Database locked as long as you iterate over cursor. # # 2. "Eager reading" # cur.fetchone() to fetch one row # cur.fetchall() to fetch all rows # Advantage: Locks cleared ASAP. # Disadvantage: fetchall() may build large lists. cur.execute("select id, data from test where id=?", (2,)) row = cur.fetchone() # Stupid way to modify the data column. lst = list(row) lst[1] = lst[1] + " & more" # This is the suggested recipe to modify data using pysqlite. We use # pysqlite's proprietary API to use the connection object as a context # manager. This is equivalent to the following code: # # try: # cur.execute("...") # except: # con.rollback() # raise # finally: # con.commit() # # This makes sure locks are cleared - either by commiting or rolling back # the transaction. # # If the rollback happens because of concurrency issues, you just have to # try again until it succeeds. Much more likely is that the rollback and # the raised exception happen because of other reasons, though (constraint # violation, etc.) - don't forget to roll back on errors. # # Or use this recipe. It's useful and gets everything done in two lines of # code. with con: cur.execute("update test set data=? where id=?", (lst[1], lst[0])) def delete_older_than(): # Use detect_types if you want to use date/time types in pysqlite. con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_COLNAMES) cur = con.cursor() # With "DEFAULT current_timestamp" we have SQLite fill the timestamp column # automatically. cur.executescript(""" create table test(id integer primary key, data, created timestamp default current_timestamp); """) with con: for i in range(3): cur.execute("insert into test(data) values ('foo')") time.sleep(1) # Delete older than certain interval # SQLite uses UTC time, so we need to create these timestamps in Python, too. with con: delete_before = datetime.utcnow() - timedelta(seconds=2) cur.execute("delete from test where created < ?", (delete_before,)) def modify_insert(): # Use a unique index and the REPLACE command to have the "insert if not # there, but modify if it is there" pattern. Race conditions are taken care # of by transactions. con = sqlite3.connect(":memory:") cur = con.cursor() cur.executescript(""" create table test(id integer primary key, name, age); insert into test(name, age) values ('Adam', 18); insert into test(name, age) values ('Eve', 21); create unique index idx_test_data_unique on test(name); """) with con: # Make Adam age 19 cur.execute("replace into test(name, age) values ('Adam', 19)") # Create new entry cur.execute("replace into test(name, age) values ('Abel', 3)") if __name__ == "__main__": read_modify_write() delete_older_than() modify_insert()
Python
from pysqlite2 import dbapi2 as sqlite3 Cursor = sqlite3.Cursor class EagerCursor(Cursor): def __init__(self, con): Cursor.__init__(self, con) self.rows = [] self.pos = 0 def execute(self, *args): sqlite3.Cursor.execute(self, *args) self.rows = Cursor.fetchall(self) self.pos = 0 def fetchone(self): try: row = self.rows[self.pos] self.pos += 1 return row except IndexError: return None def fetchmany(self, num=None): if num is None: num = self.arraysize result = self.rows[self.pos:self.pos+num] self.pos += num return result def fetchall(self): result = self.rows[self.pos:] self.pos = len(self.rows) return result def test(): con = sqlite3.connect(":memory:") cur = con.cursor(EagerCursor) cur.execute("create table test(foo)") cur.executemany("insert into test(foo) values (?)", [(3,), (4,), (5,)]) cur.execute("select * from test") print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() print cur.fetchone() if __name__ == "__main__": test()
Python
#!/usr/bin/env python # # Cross-compile and build pysqlite installers for win32 on Linux or Mac OS X. # # The way this works is very ugly, but hey, it *works*! And I didn't have to # reinvent the wheel using NSIS. import os import sys import urllib import zipfile from setup import get_amalgamation # Cross-compiler if sys.platform == "darwin": CC = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc" LIBDIR = "lib.macosx-10.6-i386-2.5" STRIP = "/usr/local/i386-mingw32-4.3.0/bin/i386-mingw32-gcc --strip-all" else: CC = "/usr/bin/i586-mingw32msvc-gcc" LIBDIR = "lib.linux-i686-2.5" STRIP = "strip --strip-all" # Optimization settings OPT = "-O2" # pysqlite sources + SQLite amalgamation SRC = "src/module.c src/connection.c src/cursor.c src/cache.c src/microprotocols.c src/prepare_protocol.c src/statement.c src/util.c src/row.c amalgamation/sqlite3.c" # You will need to fetch these from # https://pyext-cross.pysqlite.googlecode.com/hg/ CROSS_TOOLS = "../pysqlite-pyext-cross" def execute(cmd): print cmd return os.system(cmd) def compile_module(pyver): VER = pyver.replace(".", "") INC = "%s/python%s/include" % (CROSS_TOOLS, VER) vars = locals() vars.update(globals()) cmd = '%(CC)s -mno-cygwin %(OPT)s -mdll -DMODULE_NAME=\\"pysqlite2._sqlite\\" -DSQLITE_ENABLE_RTREE=1 -DSQLITE_ENABLE_FTS3=1 -I amalgamation -I %(INC)s -I . %(SRC)s -L %(CROSS_TOOLS)s/python%(VER)s/libs -lpython%(VER)s -o build/%(LIBDIR)s/pysqlite2/_sqlite.pyd' % vars execute(cmd) execute("%(STRIP)s build/%(LIBDIR)s/pysqlite2/_sqlite.pyd" % vars) def main(): vars = locals() vars.update(globals()) get_amalgamation() for ver in ["2.5", "2.6", "2.7"]: execute("rm -rf build") # First, compile the host version. This is just to get the .py files in place. execute("python2.5 setup.py build") # Yes, now delete the host extension module. What a waste of time. os.unlink("build/%(LIBDIR)s/pysqlite2/_sqlite.so" % vars) # Cross-compile win32 extension module. compile_module(ver) # Prepare for target Python version. libdir_ver = LIBDIR[:-3] + ver os.rename("build/%(LIBDIR)s" % vars, "build/" + libdir_ver) # And create the installer! os.putenv("PYEXT_CROSS", CROSS_TOOLS) execute("python2.5 setup.py cross_bdist_wininst --skip-build --target-version=" + ver) if __name__ == "__main__": main()
Python
# -*- coding: utf-8 -*- # # pysqlite documentation build configuration file, created by # sphinx-quickstart.py on Sat Mar 22 02:47:54 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't pickleable (module imports are okay, they're removed automatically). # # All configuration values have a default value; values that are commented out # serve to show the default value. import sys # If your extensions are in another directory, add it here. #sys.path.append('some/directory') # General configuration # --------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.addons.*') or your custom ones. #extensions = [] # Add any paths that contain templates here, relative to this directory. templates_path = ['.templates'] # The suffix of source filenames. source_suffix = '.rst' # The master toctree document. master_doc = 'index' # General substitutions. project = 'pysqlite' copyright = u'2008-2009, Gerhard Häring' # The default replacements for |version| and |release|, also used in various # other places throughout the built documents. # # The short X.Y version. version = '2.6' # The full version, including alpha/beta/rc tags. release = '2.6.0' # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. today_fmt = '%B %d, %Y' # List of documents that shouldn't be included in the build. #unused_docs = [] # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # Options for HTML output # ----------------------- # The style sheet to use for HTML and HTML Help pages. A file of that name # must exist either in Sphinx' static/ path, or in one of the custom paths # given in html_static_path. html_style = 'default.css' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['.static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Content template for the index page. #html_index = '' # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_use_modindex = True # If true, the reST sources are included in the HTML build as _sources/<name>. #html_copy_source = True # Output file base name for HTML help builder. htmlhelp_basename = 'pysqlitedoc' # Options for LaTeX output # ------------------------ # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, document class [howto/manual]). #latex_documents = [] # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_use_modindex = True
Python
from pysqlite2 import dbapi2 as sqlite3 FIELD_MAX_WIDTH = 20 TABLE_NAME = 'people' SELECT = 'select * from %s order by age, name_last' % TABLE_NAME con = sqlite3.connect("mydb") cur = con.cursor() cur.execute(SELECT) # Print a header. for fieldDesc in cur.description: print fieldDesc[0].ljust(FIELD_MAX_WIDTH) , print # Finish the header with a newline. print '-' * 78 # For each row, print the value of each field left-justified within # the maximum possible width of that field. fieldIndices = range(len(cur.description)) for row in cur: for fieldIndex in fieldIndices: fieldValue = str(row[fieldIndex]) print fieldValue.ljust(FIELD_MAX_WIDTH) , print # Finish the row with a newline.
Python
from pysqlite2 import dbapi2 as sqlite3 def progress(): print "Query still executing. Please wait ..." con = sqlite3.connect(":memory:") con.execute("create table test(x)") # Let's create some data con.executemany("insert into test(x) values (?)", [(x,) for x in xrange(300)]) # A progress handler, executed every 10 million opcodes con.set_progress_handler(progress, 10000000) # A particularly long-running query killer_stament = """ select count(*) from ( select t1.x from test t1, test t2, test t3 ) """ con.execute(killer_stament) print "-" * 50 # Clear the progress handler con.set_progress_handler(None, 0) con.execute(killer_stament)
Python
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb") cur = con.cursor() SELECT = "select name_last, age from people order by age, name_last" # 1. Iterate over the rows available from the cursor, unpacking the # resulting sequences to yield their elements (name_last, age): cur.execute(SELECT) for (name_last, age) in cur: print '%s is %d years old.' % (name_last, age) # 2. Equivalently: cur.execute(SELECT) for row in cur: print '%s is %d years old.' % (row[0], row[1])
Python
from pysqlite2 import dbapi2 as sqlite3 # Create a connection to the database file "mydb": con = sqlite3.connect("mydb") # Get a Cursor object that operates in the context of Connection con: cur = con.cursor() # Execute the SELECT statement: cur.execute("select * from people order by age") # Retrieve all rows as a sequence and print that sequence: print cur.fetchall()
Python
from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect("mydb")
Python
from pysqlite2 import dbapi2 as sqlite3 class MySum: def __init__(self): self.count = 0 def step(self, value): self.count += value def finalize(self): return self.count con = sqlite3.connect(":memory:") con.create_aggregate("mysum", 1, MySum) cur = con.cursor() cur.execute("create table test(i)") cur.execute("insert into test(i) values (1)") cur.execute("insert into test(i) values (2)") cur.execute("select mysum(i) from test") print cur.fetchone()[0]
Python
# A minimal SQLite shell for experiments from pysqlite2 import dbapi2 as sqlite3 con = sqlite3.connect(":memory:") con.isolation_level = None cur = con.cursor() buffer = "" print "Enter your SQL commands to execute in SQLite." print "Enter a blank line to exit." while True: line = raw_input() if line == "": break buffer += line if sqlite3.complete_statement(buffer): try: buffer = buffer.strip() cur.execute(buffer) if buffer.lstrip().upper().startswith("SELECT"): print cur.fetchall() except sqlite3.Error, e: print "An error occurred:", e.args[0] buffer = "" con.close()
Python
from pysqlite2 import dbapi2 as sqlite3 def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d con = sqlite3.connect(":memory:") con.row_factory = dict_factory cur = con.cursor() cur.execute("select 1 as a") print cur.fetchone()["a"]
Python
from pysqlite2 import dbapi2 as sqlite3 import datetime con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) cur = con.cursor() cur.execute("create table test(d date, ts timestamp)") today = datetime.date.today() now = datetime.datetime.now() cur.execute("insert into test(d, ts) values (?, ?)", (today, now)) cur.execute("select d, ts from test") row = cur.fetchone() print today, "=>", row[0], type(row[0]) print now, "=>", row[1], type(row[1]) cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"') row = cur.fetchone() print "current_date", row[0], type(row[0]) print "current_timestamp", row[1], type(row[1])
Python
from pysqlite2 import dbapi2 as sqlite3 def authorizer_callback(action, arg1, arg2, dbname, source): if action != sqlite3.SQLITE_SELECT: return sqlite3.SQLITE_DENY if arg1 == "private_table": return sqlite3.SQLITE_DENY return sqlite3.SQLITE_OK con = sqlite3.connect(":memory:") con.executescript(""" create table public_table(c1, c2); create table private_table(c1, c2); """) con.set_authorizer(authorizer_callback) try: con.execute("select * from private_table") except sqlite3.DatabaseError, e: print "SELECT FROM private_table =>", e.args[0] # access ... prohibited try: con.execute("insert into public_table(c1, c2) values (1, 2)") except sqlite3.DatabaseError, e: print "DML command =>", e.args[0] # access ... prohibited
Python