text:
import codecs
import csv
import fnmatch
import inspect
import locale
import os
import openerp.pooler as pooler
import openerp.sql_db as sql_db
import re
import logging
import tarfile
import tempfile
import threading
from babel.messages import extract
from os.path import join

from datetime import datetime
from lxml import etree

import config
import misc
from misc import UpdateableStr
from misc import SKIPPED_ELEMENT_TYPES
import osutil
from openerp import SUPERUSER_ID

_logger = logging.getLogger(__name__)

# used to notify web client that these translations should be loaded in the UI
WEB_TRANSLATION_COMMENT = "openerp-web"

_LOCALE2WIN32 = {
    'af_ZA': 'Afrikaans_South Africa',
    'sq_AL': 'Albanian_Albania',
    'ar_SA': 'Arabic_Saudi Arabia',
    'eu_ES': 'Basque_Spain',
    'be_BY': 'Belarusian_Belarus',
    'bs_BA': 'Serbian (Latin)',
    'bg_BG': 'Bulgarian_Bulgaria',
    'ca_ES': 'Catalan_Spain',
    'hr_HR': 'Croatian_Croatia',
    'zh_CN': 'Chinese_China',
    'zh_TW': 'Chinese_Taiwan',
    'cs_CZ': 'Czech_Czech Republic',
    'da_DK': 'Danish_Denmark',
    'nl_NL': 'Dutch_Netherlands',
    'et_EE': 'Estonian_Estonia',
    'fa_IR': 'Farsi_Iran',
    'ph_PH': 'Filipino_Philippines',
    'fi_FI': 'Finnish_Finland',
    'fr_FR': 'French_France',
    'fr_BE': 'French_France',
    'fr_CH': 'French_France',
    'fr_CA': 'French_France',
    'ga': 'Scottish Gaelic',
    'gl_ES': 'Galician_Spain',
    'ka_GE': 'Georgian_Georgia',
    'de_DE': 'German_Germany',
    'el_GR': 'Greek_Greece',
    'gu': 'Gujarati_India',
    'he_IL': 'Hebrew_Israel',
    'hi_IN': 'Hindi',
    'hu': 'Hungarian_Hungary',
    'is_IS': 'Icelandic_Iceland',
    'id_ID': 'Indonesian_indonesia',
    'it_IT': 'Italian_Italy',
    'ja_JP': 'Japanese_Japan',
    'kn_IN': 'Kannada',
    'km_KH': 'Khmer',
    'ko_KR': 'Korean_Korea',
    'lo_LA': 'Lao_Laos',
    'lt_LT': 'Lithuanian_Lithuania',
    'lat': 'Latvian_Latvia',
    'ml_IN': 'Malayalam_India',
    'mi_NZ': 'Maori',
    'mn': 'Cyrillic_Mongolian',
    'no_NO': 'Norwegian_Norway',
    'nn_NO': 'Norwegian-Nynorsk_Norway',
    'pl': 'Polish_Poland',
    'pt_PT': 'Portuguese_Portugal',
    'pt_BR': 'Portuguese_Brazil',
    'ro_RO': 'Romanian_Romania',
    'ru_RU': 'Russian_Russia',
    'sr_CS': 'Serbian (Cyrillic)_Serbia and Montenegro',
    'sk_SK': 'Slovak_Slovakia',
    'sl_SI': 'Slovenian_Slovenia',
    #should find more specific locales for spanish countries,
    #but better than nothing
    'es_AR': 'Spanish_Spain',
    'es_BO': 'Spanish_Spain',
    'es_CL': 'Spanish_Spain',
    'es_CO': 'Spanish_Spain',
    'es_CR': 'Spanish_Spain',
    'es_DO': 'Spanish_Spain',
    'es_EC': 'Spanish_Spain',
    'es_ES': 'Spanish_Spain',
    'es_GT': 'Spanish_Spain',
    'es_HN': 'Spanish_Spain',
    'es_MX': 'Spanish_Spain',
    'es_NI': 'Spanish_Spain',
    'es_PA': 'Spanish_Spain',
    'es_PE': 'Spanish_Spain',
    'es_PR': 'Spanish_Spain',
    'es_PY': 'Spanish_Spain',
    'es_SV': 'Spanish_Spain',
    'es_UY': 'Spanish_Spain',
    'es_VE': 'Spanish_Spain',
    'sv_SE': 'Swedish_Sweden',
    'ta_IN': 'English_Australia',
    'th_TH': 'Thai_Thailand',
    'tr_TR': 'Turkish_Turkey',
    'uk_UA': 'Ukrainian_Ukraine',
    'vi_VN': 'Vietnamese_Viet Nam',
    'tlh_TLH': 'Klingon',

}

class UNIX_LINE_TERMINATOR(csv.excel):
    lineterminator = '\n'

csv.register_dialect("UNIX", UNIX_LINE_TERMINATOR)

#
# Warning: better use self.pool.get('ir.translation')._get_source if you can
#
def translate(cr, name, source_type, lang, source=None):
    if source and name:
        cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s and src=%s', (lang, source_type, str(name), source))
    elif name:
        cr.execute('select value from ir_translation where lang=%s and type=%s and name=%s', (lang, source_type, str(name)))
    elif source:
        cr.execute('select value from ir_translation where lang=%s and type=%s and src=%s', (lang, source_type, source))
    res_trans = cr.fetchone()
    res = res_trans and res_trans[0] or False
    return res

class GettextAlias(object):

    def _get_db(self):
        # find current DB based on thread/worker db name (see netsvc)
        db_name = getattr(threading.currentThread(), 'dbname', None)
        if db_name:
            return sql_db.db_connect(db_name)

    def _get_cr(self, frame, allow_create=True):
        is_new_cr = False
        cr = frame.f_locals.get('cr', frame.f_locals.get('cursor'))
        if not cr:
            s = frame.f_locals.get('self', {})
            cr = getattr(s, 'cr', None)
        if not cr and allow_create:
            db = self._get_db()
            if db:
                cr = db.cursor()
                is_new_cr = True
        return cr, is_new_cr

    def _get_uid(self, frame):
        return frame.f_locals.get('uid') or frame.f_locals.get('user')

    def _get_lang(self, frame):
        lang = None
        ctx = frame.f_locals.get('context')
        if not ctx:
            kwargs = frame.f_locals.get('kwargs')
            if kwargs is None:
                args = frame.f_locals.get('args')
                if args and isinstance(args, (list, tuple)) \
                        and isinstance(args[-1], dict):
                    ctx = args[-1]
            elif isinstance(kwargs, dict):
                ctx = kwargs.get('context')
        if ctx:
            lang = ctx.get('lang')
        s = frame.f_locals.get('self', {})
        if not lang:
            c = getattr(s, 'localcontext', None)
            if c:
                lang = c.get('lang')
        if not lang:
            # Last resort: attempt to guess the language of the user
            # Pitfall: some operations are performed in sudo mode, and we
            #          don't know the originial uid, so the language may
            #          be wrong when the admin language differs.
            pool = getattr(s, 'pool', None)
            (cr, dummy) = self._get_cr(frame, allow_create=False)
            uid = self._get_uid(frame)
            if pool and cr and uid:
                lang = pool.get('res.users').context_get(cr, uid)['lang']
        return lang

    def __call__(self, source):
        res = source
        cr = None
        is_new_cr = False
        try:
            frame = inspect.currentframe()
            if frame is None:
                return source
            frame = frame.f_back
            if not frame:
                return source
            lang = self._get_lang(frame)
            if lang:
                cr, is_new_cr = self._get_cr(frame)
                if cr:
                    # Try to use ir.translation to benefit from global cache if possible
                    pool = pooler.get_pool(cr.dbname)
                    res = pool.get('ir.translation')._get_source(cr, SUPERUSER_ID, None, ('code','sql_constraint'), lang, source)
                else:
                    _logger.debug('no context cursor detected, skipping translation for "%r"', source)
            else:
                _logger.debug('no translation language detected, skipping translation for "%r" ', source)
        except Exception:
            _logger.debug('translation went wrong for "%r", skipped', source)
                # if so, double-check the root/base translations filenames
        finally:
            if cr and is_new_cr:
                cr.close()
        return res

_ = GettextAlias()

def quote(s):
    """Returns quoted PO term string, with special PO characters escaped"""
    assert r"\n" not in s, "Translation terms may not include escaped newlines ('\\n'), please use only literal newlines! (in '%s')" % s
    return '"%s"' % s.replace('\\','\\\\') \
                     .replace('"','\\"') \
                     .replace('\n', '\\n"\n"')

re_escaped_char = re.compile(r"(\\.)")
re_escaped_replacements = {'n': '\n', }

def _sub_replacement(match_obj):
    return re_escaped_replacements.get(match_obj.group(1)[1], match_obj.group(1)[1])

def unquote(str):
    """Returns unquoted PO term string, with special PO characters unescaped"""
    return re_escaped_char.sub(_sub_replacement, str[1:-1])

# class to handle po files
class TinyPoFile(object):
    def __init__(self, buffer):
        self.buffer = buffer

    def warn(self, msg, *args):
        _logger.warning(msg, *args)

    def __iter__(self):
        self.buffer.seek(0)
        self.lines = self._get_lines()
        self.lines_count = len(self.lines)

        self.first = True
        self.extra_lines= []
        return self

    def _get_lines(self):
        lines = self.buffer.readlines()
        # remove the BOM (Byte Order Mark):
        if len(lines):
            lines[0] = unicode(lines[0], 'utf8').lstrip(unicode( codecs.BOM_UTF8, "utf8"))

        lines.append('') # ensure that the file ends with at least an empty line
        return lines

    def cur_line(self):
        return self.lines_count - len(self.lines)

    def next(self):
        trans_type = name = res_id = source = trad = None
        if self.extra_lines:
            trans_type, name, res_id, source, trad, comments = self.extra_lines.pop(0)
            if not res_id:
                res_id = '0'
        else:
            comments = []
            targets = []
            line = None
            fuzzy = False
            while not line:
                if 0 == len(self.lines):
                    raise StopIteration()
                line = self.lines.pop(0).strip()
            while line.startswith('#'):
                if line.startswith('#~ '):
                    break
                if line.startswith('#.'):
                    line = line[2:].strip()
                    if not line.startswith('module:'):
                        comments.append(line)
                elif line.startswith('#:'):
                    for lpart in line[2:].strip().split(' '):
                        trans_info = lpart.strip().split(':',2)
                        if trans_info and len(trans_info) == 2:
                            # looks like the translation trans_type is missing, which is not
                            # unexpected because it is not a GetText standard. Default: 'code'
                            trans_info[:0] = ['code']
                        if trans_info and len(trans_info) == 3:
                            # this is a ref line holding the destination info (model, field, record)
                            targets.append(trans_info)
                elif line.startswith('#,') and (line[2:].strip() == 'fuzzy'):
                    fuzzy = True
                line = self.lines.pop(0).strip()
            while not line:
                # allow empty lines between comments and msgid
                line = self.lines.pop(0).strip()
            if line.startswith('#~ '):
                while line.startswith('#~ ') or not line.strip():
                    if 0 == len(self.lines):
                        raise StopIteration()
                    line = self.lines.pop(0)
                # This has been a deprecated entry, don't return anything
                return self.next()

            if not line.startswith('msgid'):
                raise Exception("malformed file: bad line: %s" % line)
            source = unquote(line[6:])
            line = self.lines.pop(0).strip()
            if not source and self.first:
                # if the source is "" and it's the first msgid, it's the special
                # msgstr with the informations about the traduction and the
                # traductor; we skip it
                self.extra_lines = []
                while line:
                    line = self.lines.pop(0).strip()
                return self.next()

            while not line.startswith('msgstr'):
                if not line:
                    raise Exception('malformed file at %d'% self.cur_line())
                source += unquote(line)
                line = self.lines.pop(0).strip()

            trad = unquote(line[7:])
            line = self.lines.pop(0).strip()
            while line:
                trad += unquote(line)
                line = self.lines.pop(0).strip()

            if targets and not fuzzy:
                trans_type, name, res_id = targets.pop(0)
                for t, n, r in targets:
                    if t == trans_type == 'code': continue
                    self.extra_lines.append((t, n, r, source, trad, comments))

        self.first = False

        if name is None:
            if not fuzzy:
                self.warn('Missing "#:" formated comment at line %d for the following source:\n\t%s',
                        self.cur_line(), source[:30])
            return self.next()
        return trans_type, name, res_id, source, trad, '\n'.join(comments)

    def write_infos(self, modules):
        import openerp.release as release
        self.buffer.write("# Translation of %(project)s.\n" \
                          "# This file contains the translation of the following modules:\n" \
                          "%(modules)s" \
                          "#\n" \
                          "msgid \"\"\n" \
                          "msgstr \"\"\n" \
                          '''"Project-Id-Version: %(project)s %(version)s\\n"\n''' \
                          '''"Report-Msgid-Bugs-To: \\n"\n''' \
                          '''"POT-Creation-Date: %(now)s\\n"\n'''        \
                          '''"PO-Revision-Date: %(now)s\\n"\n'''         \
                          '''"Last-Translator: <>\\n"\n''' \
                          '''"Language-Team: \\n"\n'''   \
                          '''"MIME-Version: 1.0\\n"\n''' \
                          '''"Content-Type: text/plain; charset=UTF-8\\n"\n'''   \
                          '''"Content-Transfer-Encoding: \\n"\n'''       \
                          '''"Plural-Forms: \\n"\n'''    \
                          "\n"

                          % { 'project': release.description,
                              'version': release.version,
                              'modules': reduce(lambda s, m: s + "#\t* %s\n" % m, modules, ""),
                              'now': datetime.utcnow().strftime('%Y-%m-%d %H:%M')+"+0000",
                            }
                          )

    def write(self, modules, tnrs, source, trad, comments=None):

        plurial = len(modules) > 1 and 's' or ''
        self.buffer.write("#. module%s: %s\n" % (plurial, ', '.join(modules)))

        if comments:
            self.buffer.write(''.join(('#. %s\n' % c for c in comments)))

        code = False
        for typy, name, res_id in tnrs:
            self.buffer.write("#: %s:%s:%s\n" % (typy, name, res_id))
            if typy == 'code':
                code = True

        if code:
            # only strings in python code are python formated
            self.buffer.write("#, python-format\n")

        if not isinstance(trad, unicode):
            trad = unicode(trad, 'utf8')
        if not isinstance(source, unicode):
            source = unicode(source, 'utf8')

        msg = "msgid %s\n"      \
              "msgstr %s\n\n"   \
                  % (quote(source), quote(trad))
        self.buffer.write(msg.encode('utf8'))

# Methods to export the translation file

def trans_export(lang, modules, buffer, format, cr):

    def _process(format, modules, rows, buffer, lang):
        if format == 'csv':
            writer = csv.writer(buffer, 'UNIX')
            # write header first
            writer.writerow(("module","type","name","res_id","src","value"))
            for module, type, name, res_id, src, trad, comments in rows:
                # Comments are ignored by the CSV writer
                writer.writerow((module, type, name, res_id, src, trad))
        elif format == 'po':
            writer = TinyPoFile(buffer)
            writer.write_infos(modules)

            # we now group the translations by source. That means one translation per source.
            grouped_rows = {}
            for module, type, name, res_id, src, trad, comments in rows:
                row = grouped_rows.setdefault(src, {})
                row.setdefault('modules', set()).add(module)
                if not row.get('translation') and trad != src:
                    row['translation'] = trad
                row.setdefault('tnrs', []).append((type, name, res_id))
                row.setdefault('comments', set()).update(comments)

            for src, row in grouped_rows.items():
                if not lang:
                    # translation template, so no translation value
                    row['translation'] = ''
                elif not row.get('translation'):
                    row['translation'] = src
                writer.write(row['modules'], row['tnrs'], src, row['translation'], row['comments'])

        elif format == 'tgz':
            rows_by_module = {}
            for row in rows:
                module = row[0]
                rows_by_module.setdefault(module, []).append(row)
            tmpdir = tempfile.mkdtemp()
            for mod, modrows in rows_by_module.items():
                tmpmoddir = join(tmpdir, mod, 'i18n')
                os.makedirs(tmpmoddir)
                pofilename = (lang if lang else mod) + ".po" + ('t' if not lang else '')
                buf = file(join(tmpmoddir, pofilename), 'w')
                _process('po', [mod], modrows, buf, lang)
                buf.close()

            tar = tarfile.open(fileobj=buffer, mode='w|gz')
            tar.add(tmpdir, '')
            tar.close()

        else:
            raise Exception(_('Unrecognized extension: must be one of '
                '.csv, .po, or .tgz (received .%s).' % format))

    trans_lang = lang
    if not trans_lang and format == 'csv':
        # CSV files are meant for translators and they need a starting point,
        # so we at least put the original term in the translation column
        trans_lang = 'en_US'
    translations = trans_generate(lang, modules, cr)
    modules = set([t[0] for t in translations[1:]])
    _process(format, modules, translations, buffer, lang)
    del translations

def trans_parse_xsl(de):
    return list(set(trans_parse_xsl_aux(de, False)))

def trans_parse_xsl_aux(de, t):
    res = []

    for n in de:
        t = t or n.get("t")
        if t:
                if isinstance(n, SKIPPED_ELEMENT_TYPES) or n.tag.startswith('{http://www.w3.org/1999/XSL/Transform}'):
                    continue
                if n.text:
                    l = n.text.strip().replace('\n',' ')
                    if len(l):
                        res.append(l.encode("utf8"))
                if n.tail:
                    l = n.tail.strip().replace('\n',' ')
                    if len(l):
                        res.append(l.encode("utf8"))
        res.extend(trans_parse_xsl_aux(n, t))
    return res

def trans_parse_rml(de):
    res = []
    for n in de:
        for m in n:
            if isinstance(m, SKIPPED_ELEMENT_TYPES) or not m.text:
                continue
            string_list = [s.replace('\n', ' ').strip() for s in re.split('\[\[.+?\]\]', m.text)]
            for s in string_list:
                if s:
                    res.append(s.encode("utf8"))
        res.extend(trans_parse_rml(n))
    return res

def trans_parse_view(de):
    res = []
    if not isinstance(de, SKIPPED_ELEMENT_TYPES) and de.text and de.text.strip():
        res.append(de.text.strip().encode("utf8"))
    if de.tail and de.tail.strip():
        res.append(de.tail.strip().encode("utf8"))
    if de.tag == 'attribute' and de.get("name") == 'string':
        if de.text:
            res.append(de.text.encode("utf8"))
    if de.get("string"):
        res.append(de.get('string').encode("utf8"))
    if de.get("help"):
        res.append(de.get('help').encode("utf8"))
    if de.get("sum"):
        res.append(de.get('sum').encode("utf8"))
    if de.get("confirm"):
        res.append(de.get('confirm').encode("utf8"))
    if de.get("placeholder"):
        res.append(de.get('placeholder').encode("utf8"))
    for n in de:
        res.extend(trans_parse_view(n))
    return res

# tests whether an object is in a list of modules
def in_modules(object_name, modules):
    if 'all' in modules:
        return True

    module_dict = {
        'ir': 'base',
        'res': 'base',
        'workflow': 'base',
    }
    module = object_name.split('.')[0]
    module = module_dict.get(module, module)
    return module in modules

def babel_extract_qweb(fileobj, keywords, comment_tags, options):
    """Babel message extractor for qweb template files.
    :param fileobj: the file-like object the messages should be extracted from
    :param keywords: a list of keywords (i.e. function names) that should
                     be recognized as translation functions
    :param comment_tags: a list of translator tags to search for and
                         include in the results
    :param options: a dictionary of additional options (optional)
    :return: an iterator over ``(lineno, funcname, message, comments)``
             tuples
    :rtype: ``iterator``
    """
    result = []
    def handle_text(text, lineno):
        text = (text or "").strip()
        if len(text) > 1: # Avoid mono-char tokens like ':' ',' etc.
            result.append((lineno, None, text, []))

    # not using elementTree.iterparse because we need to skip sub-trees in case
    # the ancestor element had a reason to be skipped
    def iter_elements(current_element):
        for el in current_element:
            if isinstance(el, SKIPPED_ELEMENT_TYPES): continue
            if "t-js" not in el.attrib and \
                    not ("t-jquery" in el.attrib and "t-operation" not in el.attrib) and \
                    not ("t-translation" in el.attrib and el.attrib["t-translation"].strip() == "off"):
                handle_text(el.text, el.sourceline)
                for att in ('title', 'alt', 'label', 'placeholder'):
                    if att in el.attrib:
                        handle_text(el.attrib[att], el.sourceline)
                iter_elements(el)
            handle_text(el.tail, el.sourceline)

    tree = etree.parse(fileobj)
    iter_elements(tree.getroot())

    return result

def trans_generate(lang, modules, cr):
    dbname = cr.dbname

    pool = pooler.get_pool(dbname)
    trans_obj = pool.get('ir.translation')
    model_data_obj = pool.get('ir.model.data')
    uid = 1
    l = pool.models.items()
    l.sort()

    query = 'SELECT name, model, res_id, module'    \
            '  FROM ir_model_data'

    query_models = """SELECT m.id, m.model, imd.module
            FROM ir_model AS m, ir_model_data AS imd
            WHERE m.id = imd.res_id AND imd.model = 'ir.model' """

    if 'all_installed' in modules:
        query += ' WHERE module IN ( SELECT name FROM ir_module_module WHERE state = \'installed\') '
        query_models += " AND imd.module in ( SELECT name FROM ir_module_module WHERE state = 'installed') "
    query_param = None
    if 'all' not in modules:
        query += ' WHERE module IN %s'
        query_models += ' AND imd.module in %s'
        query_param = (tuple(modules),)
    query += ' ORDER BY module, model, name'
    query_models += ' ORDER BY module, model'

    cr.execute(query, query_param)

    _to_translate = []
    def push_translation(module, type, name, id, source, comments=None):
        tuple = (module, source, name, id, type, comments or [])
        # empty and one-letter terms are ignored, they probably are not meant to be
        # translated, and would be very hard to translate anyway.
        if not source or len(source.strip()) <= 1:
            _logger.debug("Ignoring empty or 1-letter source term: %r", tuple)
            return
        if tuple not in _to_translate:
            _to_translate.append(tuple)

    def encode(s):
        if isinstance(s, unicode):
            return s.encode('utf8')
        return s

    for (xml_name,model,res_id,module) in cr.fetchall():
        module = encode(module)
        model = encode(model)
        xml_name = "%s.%s" % (module, encode(xml_name))

        if not pool.get(model):
            _logger.error("Unable to find object %r", model)
            continue

        exists = pool.get(model).exists(cr, uid, res_id)
        if not exists:
            _logger.warning("Unable to find object %r with id %d", model, res_id)
            continue
        obj = pool.get(model).browse(cr, uid, res_id)

        if model=='ir.ui.view':
            d = etree.XML(encode(obj.arch))
            for t in trans_parse_view(d):
                push_translation(module, 'view', encode(obj.model), 0, t)
        elif model=='ir.actions.wizard':
            service_name = 'wizard.'+encode(obj.wiz_name)
            import openerp.netsvc as netsvc
            if netsvc.Service._services.get(service_name):
                obj2 = netsvc.Service._services[service_name]
                for state_name, state_def in obj2.states.iteritems():
                    if 'result' in state_def:
                        result = state_def['result']
                        if result['type'] != 'form':
                            continue
                        name = "%s,%s" % (encode(obj.wiz_name), state_name)

                        def_params = {
                            'string': ('wizard_field', lambda s: [encode(s)]),
                            'selection': ('selection', lambda s: [encode(e[1]) for e in ((not callable(s)) and s or [])]),
                            'help': ('help', lambda s: [encode(s)]),
                        }

                        # export fields
                        if not result.has_key('fields'):
                            _logger.warning("res has no fields: %r", result)
                            continue
                        for field_name, field_def in result['fields'].iteritems():
                            res_name = name + ',' + field_name

                            for fn in def_params:
                                if fn in field_def:
                                    transtype, modifier = def_params[fn]
                                    for val in modifier(field_def[fn]):
                                        push_translation(module, transtype, res_name, 0, val)

                        # export arch
                        arch = result['arch']
                        if arch and not isinstance(arch, UpdateableStr):
                            d = etree.XML(arch)
                            for t in trans_parse_view(d):
                                push_translation(module, 'wizard_view', name, 0, t)

                        # export button labels
                        for but_args in result['state']:
                            button_name = but_args[0]
                            button_label = but_args[1]
                            res_name = name + ',' + button_name
                            push_translation(module, 'wizard_button', res_name, 0, button_label)

        elif model=='ir.model.fields':
            try:
                field_name = encode(obj.name)
            except AttributeError, exc:
                _logger.error("name error in %s: %s", xml_name, str(exc))
                continue
            objmodel = pool.get(obj.model)
            if not objmodel or not field_name in objmodel._columns:
                continue
            field_def = objmodel._columns[field_name]

            name = "%s,%s" % (encode(obj.model), field_name)
            push_translation(module, 'field', name, 0, encode(field_def.string))

            if field_def.help:
                push_translation(module, 'help', name, 0, encode(field_def.help))

            if field_def.translate:
                ids = objmodel.search(cr, uid, [])
                obj_values = objmodel.read(cr, uid, ids, [field_name])
                for obj_value in obj_values:
                    res_id = obj_value['id']
                    if obj.name in ('ir.model', 'ir.ui.menu'):
                        res_id = 0
                    model_data_ids = model_data_obj.search(cr, uid, [
                        ('model', '=', model),
                        ('res_id', '=', res_id),
                        ])
                    if not model_data_ids:
                        push_translation(module, 'model', name, 0, encode(obj_value[field_name]))

            if hasattr(field_def, 'selection') and isinstance(field_def.selection, (list, tuple)):
                for dummy, val in field_def.selection:
                    push_translation(module, 'selection', name, 0, encode(val))

        elif model=='ir.actions.report.xml':
            name = encode(obj.report_name)
            fname = ""
            if obj.report_rml:
                fname = obj.report_rml
                parse_func = trans_parse_rml
                report_type = "report"
            elif obj.report_xsl:
                fname = obj.report_xsl
                parse_func = trans_parse_xsl
                report_type = "xsl"
            if fname and obj.report_type in ('pdf', 'xsl'):
                try:
                    report_file = misc.file_open(fname)
                    try:
                        d = etree.parse(report_file)
                        for t in parse_func(d.iter()):
                            push_translation(module, report_type, name, 0, t)
                    finally:
                        report_file.close()
                except (IOError, etree.XMLSyntaxError):
                    _logger.exception("couldn't export translation for report %s %s %s", name, report_type, fname)

        for field_name,field_def in obj._table._columns.items():
            if field_def.translate:
                name = model + "," + field_name
                try:
                    trad = getattr(obj, field_name) or ''
                except:
                    trad = ''
                push_translation(module, 'model', name, xml_name, encode(trad))

        # End of data for ir.model.data query results

    cr.execute(query_models, query_param)

    def push_constraint_msg(module, term_type, model, msg):
        if not hasattr(msg, '__call__'):
            push_translation(encode(module), term_type, encode(model), 0, encode(msg))

    def push_local_constraints(module, model, cons_type='sql_constraints'):
        """Climb up the class hierarchy and ignore inherited constraints
           from other modules"""
        term_type = 'sql_constraint' if cons_type == 'sql_constraints' else 'constraint'
        msg_pos = 2 if cons_type == 'sql_constraints' else 1
        for cls in model.__class__.__mro__:
            if getattr(cls, '_module', None) != module:
                continue
            constraints = getattr(cls, '_local_' + cons_type, [])
            for constraint in constraints:
                push_constraint_msg(module, term_type, model._name, constraint[msg_pos])

    for (_, model, module) in cr.fetchall():
        model_obj = pool.get(model)

        if not model_obj:
            _logger.error("Unable to find object %r", model)
            continue

        if model_obj._constraints:
            push_local_constraints(module, model_obj, 'constraints')

        if model_obj._sql_constraints:
            push_local_constraints(module, model_obj, 'sql_constraints')

    def get_module_from_path(path, mod_paths=None):
        if not mod_paths:
            # First, construct a list of possible paths
            def_path = os.path.abspath(os.path.join(config.config['root_path'], 'addons'))     # default addons path (base)
            ad_paths= map(lambda m: os.path.abspath(m.strip()),config.config['addons_path'].split(','))
            mod_paths=[def_path]
            for adp in ad_paths:
                mod_paths.append(adp)
                if not os.path.isabs(adp):
                    mod_paths.append(adp)
                elif adp.startswith(def_path):
                    mod_paths.append(adp[len(def_path)+1:])
        for mp in mod_paths:
            if path.startswith(mp) and (os.path.dirname(path) != mp):
                path = path[len(mp)+1:]
                return path.split(os.path.sep)[0]
        return 'base'   # files that are not in a module are considered as being in 'base' module

    modobj = pool.get('ir.module.module')
    installed_modids = modobj.search(cr, uid, [('state', '=', 'installed')])
    installed_modules = map(lambda m: m['name'], modobj.read(cr, uid, installed_modids, ['name']))

    root_path = os.path.join(config.config['root_path'], 'addons')

    apaths = map(os.path.abspath, map(str.strip, config.config['addons_path'].split(',')))
    if root_path in apaths:
        path_list = apaths
    else :
        path_list = [root_path,] + apaths

    # Also scan these non-addon paths
    for bin_path in ['osv', 'report' ]:
        path_list.append(os.path.join(config.config['root_path'], bin_path))

    _logger.debug("Scanning modules at paths: ", path_list)

    mod_paths = []

    def verified_module_filepaths(fname, path, root):
        fabsolutepath = join(root, fname)
        frelativepath = fabsolutepath[len(path):]
        display_path = "addons%s" % frelativepath
        module = get_module_from_path(fabsolutepath, mod_paths=mod_paths)
        if ('all' in modules or module in modules) and module in installed_modules:
            return module, fabsolutepath, frelativepath, display_path
        return None, None, None, None

    def babel_extract_terms(fname, path, root, extract_method="python", trans_type='code',
                               extra_comments=None, extract_keywords={'_': None}):
        module, fabsolutepath, _, display_path = verified_module_filepaths(fname, path, root)
        extra_comments = extra_comments or []
        if module:
            src_file = open(fabsolutepath, 'r')
            try:
                for extracted in extract.extract(extract_method, src_file,
                                                 keywords=extract_keywords):
                    # Babel 0.9.6 yields lineno, message, comments
                    # Babel 1.3 yields lineno, message, comments, context
                    lineno, message, comments = extracted[:3]
                    push_translation(module, trans_type, display_path, lineno,
                                     encode(message), comments + extra_comments)
            except Exception:
                _logger.exception("Failed to extract terms from %s", fabsolutepath)
            finally:
                src_file.close()

    for path in path_list:
        _logger.debug("Scanning files of modules at %s", path)
        for root, dummy, files in osutil.walksymlinks(path):
            for fname in fnmatch.filter(files, '*.py'):
                babel_extract_terms(fname, path, root)
            # mako provides a babel extractor: http://docs.makotemplates.org/en/latest/usage.html#babel
            for fname in fnmatch.filter(files, '*.mako'):
                babel_extract_terms(fname, path, root, 'mako', trans_type='report')
            # Javascript source files in the static/src/js directory, rest is ignored (libs)
            if fnmatch.fnmatch(root, '*/static/src/js*'):
                for fname in fnmatch.filter(files, '*.js'):
                    babel_extract_terms(fname, path, root, 'javascript',
                                        extra_comments=[WEB_TRANSLATION_COMMENT],
                                        extract_keywords={'_t': None, '_lt': None})
            # QWeb template files
            if fnmatch.fnmatch(root, '*/static/src/xml*'):
                for fname in fnmatch.filter(files, '*.xml'):
                    babel_extract_terms(fname, path, root, 'openerp.tools.translate:babel_extract_qweb',
                                        extra_comments=[WEB_TRANSLATION_COMMENT])

    out = []
    _to_translate.sort()
    # translate strings marked as to be translated
    for module, source, name, id, type, comments in _to_translate:
        trans = '' if not lang else trans_obj._get_source(cr, uid, name, type, lang, source)
        out.append([module, type, name, id, source, encode(trans) or '', comments])
    return out

def trans_load(cr, filename, lang, verbose=True, module_name=None, context=None):
    try:
        fileobj = misc.file_open(filename)
        _logger.info("loading %s", filename)
        fileformat = os.path.splitext(filename)[-1][1:].lower()
        result = trans_load_data(cr, fileobj, fileformat, lang, verbose=verbose, module_name=module_name, context=context)
        fileobj.close()
        return result
    except IOError:
        if verbose:
            _logger.error("couldn't read translation file %s", filename)
        return None

def trans_load_data(cr, fileobj, fileformat, lang, lang_name=None, verbose=True, module_name=None, context=None):
    """Populates the ir_translation table."""
    if verbose:
        _logger.info('loading translation file for language %s', lang)
    if context is None:
        context = {}
    db_name = cr.dbname
    pool = pooler.get_pool(db_name)
    lang_obj = pool.get('res.lang')
    trans_obj = pool.get('ir.translation')
    iso_lang = misc.get_iso_codes(lang)
    try:
        ids = lang_obj.search(cr, SUPERUSER_ID, [('code','=', lang)])

        if not ids:
            # lets create the language with locale information
            lang_obj.load_lang(cr, SUPERUSER_ID, lang=lang, lang_name=lang_name)

        # now, the serious things: we read the language file
        fileobj.seek(0)
        if fileformat == 'csv':
            reader = csv.reader(fileobj, quotechar='"', delimiter=',')
            # read the first line of the file (it contains columns titles)
            for row in reader:
                f = row
                break
        elif fileformat == 'po':
            reader = TinyPoFile(fileobj)
            f = ['type', 'name', 'res_id', 'src', 'value', 'comments']
        else:
            _logger.error('Bad file format: %s', fileformat)
            raise Exception(_('Bad file format'))

        # read the rest of the file
        line = 1
        irt_cursor = trans_obj._get_import_cursor(cr, SUPERUSER_ID, context=context)

        for row in reader:
            line += 1
            # skip empty rows and rows where the translation field (=last fiefd) is empty
            #if (not row) or (not row[-1]):
            #    continue

            # dictionary which holds values for this line of the csv file
            # {'lang': ..., 'type': ..., 'name': ..., 'res_id': ...,
            #  'src': ..., 'value': ..., 'module':...}
            dic = dict.fromkeys(('name', 'res_id', 'src', 'type', 'imd_model', 'imd_name', 'module', 'value', 'comments'))
            dic['lang'] = lang
            for i, field in enumerate(f):
                dic[field] = row[i]

            # This would skip terms that fail to specify a res_id
            if not dic.get('res_id'):
                continue

            res_id = dic.pop('res_id')
            if res_id and isinstance(res_id, (int, long)) \
                or (isinstance(res_id, basestring) and res_id.isdigit()):
                    dic['res_id'] = int(res_id)
                    dic['module'] = module_name
            else:
                tmodel = dic['name'].split(',')[0]
                if '.' in res_id:
                    tmodule, tname = res_id.split('.', 1)
                else:
                    tmodule = False
                    tname = res_id
                dic['imd_model'] = tmodel
                dic['imd_name'] =  tname
                dic['module'] = tmodule
                dic['res_id'] = None

            irt_cursor.push(dic)

        irt_cursor.finish()
        trans_obj.clear_caches()
        if verbose:
            _logger.info("translation file loaded succesfully")
    except IOError:
        filename = '[lang: %s][format: %s]' % (iso_lang or 'new', fileformat)
        _logger.exception("couldn't read translation file %s", filename)

def get_locales(lang=None):
    if lang is None:
        lang = locale.getdefaultlocale()[0]

    if os.name == 'nt':
        lang = _LOCALE2WIN32.get(lang, lang)

    def process(enc):
        ln = locale._build_localename((lang, enc))
        yield ln
        nln = locale.normalize(ln)
        if nln != ln:
            yield nln

    for x in process('utf8'): yield x

    prefenc = locale.getpreferredencoding()
    if prefenc:
        for x in process(prefenc): yield x

        prefenc = {
            'latin1': 'latin9',
            'iso-8859-1': 'iso8859-15',
            'cp1252': '1252',
        }.get(prefenc.lower())
        if prefenc:
            for x in process(prefenc): yield x

    yield lang

def resetlocale():
    # locale.resetlocale is bugged with some locales.
    for ln in get_locales():
        try:
            return locale.setlocale(locale.LC_ALL, ln)
        except locale.Error:
            continue

def load_language(cr, lang):
    """Loads a translation terms for a language.
    Used mainly to automate language loading at db initialization.

    :param lang: language ISO code with optional _underscore_ and l10n flavor (ex: 'fr', 'fr_BE', but not 'fr-BE')
    :type lang: str
    """
    pool = pooler.get_pool(cr.dbname)
    language_installer = pool.get('base.language.install')
    uid = 1
    oid = language_installer.create(cr, uid, {'lang': lang})
    language_installer.lang_install(cr, uid, [oid], context=None)

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


text:
<android.support.v4.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/swipe_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="56dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <it.gmariotti.cardslib.library.view.CardListView
            android:id="@+id/main_cardlist_nearby"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:clipToPadding="false"
            android:paddingTop="8dp"
            app:list_card_layout_resourceID="@layout/native_list_card_layout"/>

        <com.melnykov.fab.FloatingActionButton
            android:id="@+id/main_fab_addspot"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="16dp"
            android:src="@drawable/ic_action_addspot"
            app:fab_colorNormal="@color/colorPrimary"
            app:fab_colorPressed="@color/colorPrimaryLight"
            app:fab_colorRipple="@color/colorRippleLight"
            android:elevation="8dp"/>

    </RelativeLayout>

</android.support.v4.widget.SwipeRefreshLayout>

redpajama_set_name: RedPajamaGithub


text:
'use strict';

// ------------- imported from ./index.js ---------------
const config = require('../config');
const jwt = require('jsonwebtoken');
const logger = require('../utils/logger-winston');
const Utils = require('../utils/util');

module.exports.restAuthenticationMiddleware = function (req, res, next) {
  logger.warn('REST restAuthenticationMiddleware - req.session.authToken', req.session.authToken);

  // For testing purposes it could be useful to bypass this authentication middleware
  // to be able to modify the session.
  // There are some tests that are using this bypass to cover all statements and
  // branches.
  // ATTENTION - USE THIS FEATURE ONLY FOR TESTING PURPOSES!!!!!!!
  if (config.isDisableRestAuthMiddleware() && (config.isTest() || config.isCI() )) {
    // authentication middleware DISABLED
    // logger not required here
    console.warn('REST restAuthMiddleware disabled - because you are running this app with both ' +
      'DISABLE_REST_AUTH_MIDDLEWARE === yes and (config.NODE_ENV === test or config.CI === yes)');
    return next();
  }

  try {
    if (!req.session.authToken) {
      logger.error('REST restAuthenticationMiddleware - req.session.authToken not valid');
      return Utils.sendJSONres(res, 403, 'No token provided');
    }
    const authToken = JSON.parse(req.session.authToken);
    const token = authToken.token;
    logger.debug('REST restAuthenticationMiddleware - parsed token', token);
    if (!token) {
      logger.error('REST restAuthenticationMiddleware - Token not found');
      return Utils.sendJSONres(res, 404, 'Token not found');
    }

    jwt.verify(token, config.JWT_SECRET, (err, decoded) => {
      if (err) {
        logger.error('REST restAuthenticationMiddleware - jwt.verify error', err);
        return Utils.sendJSONres(res, 401, 'Jwt not valid or corrupted');
      }

      if (!decoded) {
        logger.error('REST restAuthenticationMiddleware - decoded is not valid (but before err was ok - WTF!!!)');
        return Utils.sendJSONres(res, 500, 'Impossible to check if jwt is valid - decoded is not valid');
      }

      logger.debug('REST restAuthenticationMiddleware - Token is valid', token);

      try {
        let isJwtValidDate = Utils.isJwtValidDate(decoded);
        logger.debug('REST restAuthenticationMiddleware - isJwtValidDate', isJwtValidDate);

        if (!isJwtValidDate) {
          logger.error('REST restAuthenticationMiddleware - jwt has an invalid data');
          return Utils.sendJSONres(res, 404, 'Data is not valid');
        }

        logger.debug('REST restAuthenticationMiddleware - systemDate valid');
        return next();

      } catch (err2) {
        logger.error('REST restAuthenticationMiddleware - exception thrown by isJwtValidDate', err2);
        return Utils.sendJSONres(res, 500, 'Impossible to check if jwt is valid');
      }
    });
  } catch (err) {
    logger.error('REST restAuthenticationMiddleware - exception catched', err);
    return Utils.sendJSONres(res, 403, 'No token provided');
  }
};


text:
/*eslint no-console: 0 */

const neo4j = require('node-neo4j')
const makeApp = require('./app')

const DB_URL = process.env.GRAPHENEDB_URL
const db = new neo4j(DB_URL)

const PORT = process.env.PORT || 1337

const app = makeApp(db);

app.listen(PORT, () => {
  console.log('Listening on ' + PORT)
})


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- Root Context: defines shared resources visible to all other web components -->

    <bean id="configurator" class="com.civilizer.config.Configurator"/>

    <import resource="classpath:datasource-context.xml" />

</beans>


text:
'use strict';

angular.module('plagueheartApp')
    .controller('MemberDetailController', function ($scope, $rootScope, $stateParams, entity, Member, Company) {
        $scope.member = entity;
        $scope.load = function (id) {
            Member.get({id: id}, function(result) {
                $scope.member = result;
            });
        };
        var unsubscribe = $rootScope.$on('plagueheartApp:memberUpdate', function(event, result) {
            $scope.member = result;
        });
        $scope.$on('$destroy', unsubscribe);

    });


text:
package org.ngrinder.infra.report;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Date;

import org.junit.Test;
import org.ngrinder.infra.config.Config;

public class PeriodicCollectDataToGAServiceTest {

	@Test
	public void testReport() {
		Config configMock = mock(Config.class);
		when(configMock.isUsageReportEnabled()).thenReturn(true);
		when(configMock.getVersion()).thenReturn("test-0.0.1");
		PeriodicCollectDataToGAService gaService = new PeriodicCollectDataToGAService() {
			@Override
			protected int getUsage(Date start, Date end) {
				return 10;
			}

			protected void doRandomDelay() {
				// No delay for unit test.
			};
		};
		gaService.setConfig(configMock);
		gaService.reportUsage();
	}

}


text:
<?php

$l['redirect_width'] = "50%";
$l['lastvisit_never'] = "Jamais";

$l['toplinks_memberlist'] = "Liste des membres";
$l['toplinks_search'] = "Recherche";
$l['toplinks_calendar'] = "Calendrier";
$l['toplinks_help'] = "Aide";
$l['toplinks_portal'] = "Portail";
$l['bottomlinks_contactus'] = "Contact";
$l['bottomlinks_returntop'] = "Retourner en haut";
$l['bottomlinks_returncontent'] = "Retourner au contenu";
$l['bottomlinks_syndication'] = "Syndication RSS";
$l['bottomlinks_litemode'] = "Version bas-débit (Archivé)";

$l['welcome_usercp'] = "Configuration";
$l['welcome_modcp'] = "Modération";
$l['welcome_admin'] = "Administration";
$l['welcome_logout'] = "Déconnexion";
$l['welcome_login'] = "Identification";
$l['welcome_register'] = "S'enregistrer";
$l['welcome_open_buddy_list'] = "Liste de contacts";
$l['welcome_newposts'] = "Nouveaux messages";
$l['welcome_todaysposts'] = "Messages d'aujourd'hui";
$l['welcome_pms'] = "Messages Privés";
$l['welcome_pms_usage'] = "(Nouveaux {1}, Total {2})";
$l['welcome_back'] = "Bienvenue, {1}. Dernière visite : {2}";
$l['welcome_guest'] = "Bienvenue, Visiteur !";
$l['welcome_current_time'] = "Date actuelle : {1}";

$l['moved_prefix'] = "Déplacé :";
$l['sticky_prefix'] = "Épinglé :";
$l['poll_prefix'] = "Sondage :";
$l['announcement_prefix'] = "Annonce :";

$l['forumbit_announcements'] = "Annonces";
$l['forumbit_stickies'] = "Discussions importantes";
$l['forumbit_forum'] = "Forum";
$l['forumbit_threads'] = "Discussions";
$l['forumbit_posts'] = "Messages";
$l['forumbit_lastpost'] = "Dernier message";
$l['forumbit_moderated_by'] = "Modéré par :";
$l['new_posts'] = "Le forum contient de nouveaux messages.";
$l['no_new_posts'] = "Le forum ne contient pas de nouveaux messages.";
$l['click_mark_read'] = "Cliquer pour marquer ce forum comme lu";
$l['forum_locked'] = "Le forum est fermé.";
$l['lastpost_never'] = "Jamais";
$l['viewing_one'] = " (1 utilisateur parcourant)";
$l['viewing_multiple'] = " ({1} utilisateurs parcourant)";
$l['by'] = "par";
$l['more_subforums'] = "et {1} de plus.";

$l['password_required'] = "Mot de passe requis";
$l['forum_password_note'] = "Un mot de passe est requis pour accéder à ce forum.";
$l['enter_password_below'] = "Veuillez entrer le mot de passe :";
$l['verify_forum_password'] = "Vérifier le mot de passe du forum";
$l['wrong_forum_password'] = "Le mot de passe que vous avez entré est incorrect. Veuillez réessayer.";

$l['reset_button'] = "Réinitialiser";
$l['username'] = "Nom d'utilisateur :";
$l['password'] = "Mot de passe :";
$l['login_username'] = "Nom d'utilisateur";
$l['login_password'] = "Mot de passe";
$l['lost_password'] = "Mot de passe oublié ?";
$l['remember_me'] = "Se rappeler";
$l['remember_me_desc'] = "Si coché, vos identifiants seront mémorisés sur cet ordinateur, sinon vous serez déconnecté chaque fois que vous fermerez le navigateur.";

$l['month_1'] = "Janvier";
$l['month_2'] = "Février";
$l['month_3'] = "Mars";
$l['month_4'] = "Avril";
$l['month_5'] = "Mai";
$l['month_6'] = "Juin";
$l['month_7'] = "Juillet";
$l['month_8'] = "Août";
$l['month_9'] = "Septembre";
$l['month_10'] = "Octobre";
$l['month_11'] = "Novembre";
$l['month_12'] = "Décembre";

$l['sunday'] = "Dimanche";
$l['monday'] = "Lundi";
$l['tuesday'] = "Mardi";
$l['wednesday'] = "Mercredi";
$l['thursday'] = "Jeudi";
$l['friday'] = "Vendredi";
$l['saturday'] = "Samedi";
$l['short_monday'] = "L";
$l['short_tuesday'] = "M";
$l['short_wednesday'] = "M";
$l['short_thursday'] = "J";
$l['short_friday'] = "V";
$l['short_saturday'] = "S";
$l['short_sunday'] = "D";

$l['yes'] = "Oui";
$l['no'] = "Non";

$l['and'] = "et";

$l['attachments'] = "Pièces jointes";
$l['attachments_desc'] = "Vous pouvez attacher des pièces jointes à ce message. Sélectionnez le fichier à droite et cliquez sur 'Ajouter une pièce jointe' pour l'uploader.";
$l['remove_attachment'] = "Supprimer";
$l['approve_attachment'] = "Approuver";
$l['unapprove_attachment'] = "Désapprouver";
$l['insert_attachment_post'] = "Insérer dans le message";
$l['new_attachment'] = "Nouvelle pièce jointe :";
$l['add_attachment'] = "Ajouter une pièce jointe";
$l['update_attachment'] = "Mettre à jour la pièce jointe";
$l['post_preview'] = "Aperçu";
$l['change_user'] = "Changer d'utilisateur";
$l['post_icon'] = "Icône du message";
$l['no_post_icon'] = "pas d'icône";
$l['thread_subscription_method'] = "S'abonner à une discussion :
Spécifiez le type d'email de notification et l'abonnement à la discussion que vous voulez avoir pour cette discussion (réservé aux utilisateurs enregistrés).";
$l['no_subscribe'] = "Ne pas s'abonner à cette discussion.";
$l['no_email_subscribe'] = "S'abonner sans recevoir d'email de notification des nouvelles réponses.";
$l['instant_email_subscribe'] = "S'abonner et recevoir les emails de notification des nouvelles réponses.";

$l['today'] = "Aujourd'hui";
$l['yesterday'] = "Hier";
$l['error'] = "Message du forum";

$l['multipage_pages'] = "Pages ({1}) :";
$l['multipage_last'] = "Dernière";
$l['multipage_first'] = "Première";
$l['multipage_next'] = "Suivante";
$l['multipage_previous'] = "Précédente";
$l['multipage_link_start'] = " ...";
$l['multipage_link_end'] = "... ";

$l['editor_title_bold'] = "Insérer du texte en gras";
$l['editor_title_italic'] = "Insérer du texte en italique";
$l['editor_title_underline'] = "Insérer du texte souligné";
$l['editor_title_left'] = "Aligner le texte à gauche";
$l['editor_title_center'] = "Aligner le texte au centre";
$l['editor_title_right'] = "Aligner le texte à droite";
$l['editor_title_justify'] = "Justifier le texte";
$l['editor_title_numlist'] = "Insérer une liste numérotée";
$l['editor_title_bulletlist'] = "Insérer une liste à puces";
$l['editor_title_image'] = "Insérer une image";
$l['editor_title_hyperlink'] = "Insérer un lien hypertexte";
$l['editor_title_email'] = "Insérer une adresse email";
$l['editor_title_quote'] = "Insérer une citation";
$l['editor_title_code'] = "Insérer du code formaté";
$l['editor_title_php'] = "Insérer du code PHP formaté";
$l['editor_title_close_tags'] = "Fermer les balises MyCode que vous avez éventuellement ouvertes";
$l['editor_enter_list_item'] = "Entrez un élément de la liste. Cliquez sur annuler ou n'écrivez rien pour fermer la liste.";
$l['editor_enter_url'] = "Veuillez entre l'URL du site.";
$l['editor_enter_url_title'] = "Optionnellement, vous pouvez aussi entrer un titre pour l'URL.";
$l['editor_enter_email'] = "Veuillez entrer l'adresse email que vous voulez insérer.";
$l['editor_enter_email_title'] = "Optionnellement, vous pouvez aussi entrer un titre pour l'adresse email.";
$l['editor_enter_image'] = "Veuillez entrer l'URL de l'image à insérer.";
$l['editor_enter_video_url'] = "Entrez l'URL de la vidéo.";
$l['editor_video_dailymotion'] = "Dailymotion";
$l['editor_video_googlevideo'] = "Google Video";
$l['editor_video_metacafe'] = "MetaCafe";
$l['editor_video_myspacetv'] = "MySpace TV";
$l['editor_video_vimeo'] = "Vimeo";
$l['editor_video_yahoo'] = "Yahoo Video";
$l['editor_video_youtube'] = "YouTube";
$l['editor_size_xx_small'] = "Vraiment Petit";
$l['editor_size_x_small'] = "Très petit";
$l['editor_size_small'] = "Petit";
$l['editor_size_medium'] = "Moyen";
$l['editor_size_large'] = "Grand";
$l['editor_size_x_large'] = "Très grand";
$l['editor_size_xx_large'] = "Vraiment grand";
$l['editor_font'] = "Police";
$l['editor_size'] = "Taille du texte";
$l['editor_color'] = "Couleur du texte";

$l['quote'] = "Citation :";
$l['wrote'] = "a écrit :";
$l['code'] = "Code :";
$l['php_code'] = "Code PHP :";
$l['posted_image'] = "[Image: {1}]";
$l['linkback'] = "Message original";

$l['at'] = "à";
$l['na'] = "N/A";
$l['guest'] = "Visiteur";
$l['unknown'] = "Inconnu";
$l['never'] = "Jamais";
$l['postbit_posts'] = "Messages :";
$l['postbit_group'] = "Groupe :";
$l['postbit_joined'] = "Inscription :";
$l['postbit_status'] = "Statut :";
$l['postbit_attachments'] = "Pièce(s) jointe(s)";
$l['postbit_attachment_size'] = "Taille :";
$l['postbit_attachment_downloads'] = "Téléchargements :";
$l['postbit_attachments_images'] = "Image(s)";
$l['postbit_attachments_thumbnails'] = "Miniature(s)";
$l['postbit_unapproved_attachments'] = "{1} pièces jointes non approuvées.";
$l['postbit_unapproved_attachment'] = "1 pièce jointe non approuvée.";
$l['postbit_status_online'] = "En ligne";
$l['postbit_status_offline'] = "Hors ligne";
$l['postbit_status_away'] = "Absent";
$l['postbit_edited'] = "Ce message a été modifié le : {1} {2} par";
$l['postbit_ipaddress'] = "Adresse IP :";
$l['postbit_ipaddress_logged'] = "Notée";
$l['postbit_post'] = "Message :";
$l['postbit_reputation'] = "Réputation :";
$l['postbit_website'] = "Visiter le site internet de cet utilisateur";
$l['postbit_email'] = "Envoyer un email à cet utilisateur";
$l['postbit_find'] = "Trouver tous les messages de cet utilisateur";
$l['postbit_report'] = "Signaler ce message à un modérateur";
$l['postbit_quote'] = "Citer ce message dans une réponse";
$l['postbit_qdelete'] = "Supprimer ce message";
$l['postbit_profile'] = "Voir le profil de cet utilisateur";
$l['postbit_pm'] = "Envoyer un message privé à cet utilisateur";
$l['postbit_edit'] = "Éditer ce message";
$l['postbit_multiquote'] = "Citer ce message dans une nouvelle page de réponse";
$l['postbit_quick_edit'] = "Édition rapide";
$l['postbit_full_edit'] = "Édition complète";
$l['postbit_show_ignored_post'] = "Afficher ce message";
$l['postbit_currently_ignoring_user'] = "Le contenu de ce message est caché car {1} est dans votre liste d'ignorés.";
$l['postbit_warning_level'] = "Niveau d'avertissement :";
$l['postbit_warn'] = "Avertir l'auteur pour ce message";

$l['forumjump'] = "Aller à :";
$l['forumjump_select'] = "Choisissez un forum :";
$l['forumjump_pms'] = "Messages privés";
$l['forumjump_usercp'] = "Panneau de configuration";
$l['forumjump_wol'] = "Qui est en ligne";
$l['forumjump_search'] = "Recherche";
$l['forumjump_home'] = "Accueil du forum";

$l['redirect'] = "Vous allez être redirigé";
$l['unknown_error'] = "Une erreur inconnue s'est produite.";

$l['smilieinsert'] = "Smileys";
$l['smilieinsert_getmore'] = "plus";
$l['on'] = "Oui";
$l['off'] = "Non";
$l['unread_report'] = "Pour la modération : Il y a 1 message reporté.";
$l['unread_reports'] = "Pour la modération : Il y a {1} messages reportés.";
$l['pending_joinrequest'] = "Pour le chef de groupe : vous avez une demande d'adhésion à un groupe en attente.";
$l['pending_joinrequests'] = "Pour le chef de groupe : vous avez {1} demandes d'adhésion à un groupe en attente.";

$l['year'] = "An";
$l['year_short'] = "y";
$l['years'] = "Ans";
$l['years_short'] = "y";
$l['month'] = "Mois";
$l['month_short'] = "m";
$l['months'] = "Mois";
$l['months_short'] = "m";
$l['week'] = "Semaine";
$l['week_short'] = "w";
$l['weeks'] = "Semaines";
$l['weeks_short'] = "w";
$l['day'] = "Jour";
$l['day_short'] = "d";
$l['days'] = "Jours";
$l['days_short'] = "d";
$l['hour'] = "Heure";
$l['hour_short'] = "h";
$l['hours'] = "Heures";
$l['hours_short'] = "h";
$l['minute'] = "Minute";
$l['minute_short'] = "m";
$l['minutes'] = "Minutes";
$l['minutes_short'] = "m";
$l['second'] = "Seconde";
$l['second_short'] = "s";
$l['seconds'] = "Secondes";
$l['seconds_short'] = "s";
$l['permanent'] = "Permanent";
$l['save_draft'] = "Sauvegarder comme brouillon";
$l['go'] = "Valider";
$l['bbclosed_warning'] = "Le statut de votre forum est défini comme fermé.";
$l['banned_warning'] = "Votre compte est banni.";
$l['banned_warning2'] = "Raison du bannissement";
$l['banned_warning3'] = "Le bannissement sera levé";
$l['banned_lifted_never'] = "Jamais";
$l['powered_by'] = "Moteur";
$l['copyright'] = "Copyright";
$l['attach_quota'] = "Vous utilisez {1} du total alloué à vos pièces jointes ({2})";
$l['view_attachments'] = "[Voir mes pièces jointes]";
$l['unlimited'] = "Illimité";

$l['click_hold_edit'] = "(Cliquez et maintenez enfoncé pour éditer le titre)";

$l['guest_count'] = "1 visiteur";
$l['guest_count_multiple'] = "{1} visiteurs";

$l['size_yb'] = "Yo";
$l['size_zb'] = "Zo";
$l['size_eb'] = "Eo";
$l['size_pb'] = "Po";
$l['size_tb'] = "To";
$l['size_gb'] = "Go";
$l['size_mb'] = "Mo";
$l['size_kb'] = "Ko";
$l['size_bytes'] = "octets";

$l['slaps'] = "donne une baffe à";
$l['with_trout'] = "qui lui laisse une énorme marque rouge sur la joue !";

$l['mybb_engine'] = "Moteur MyBB";
$l['quickdelete_confirm'] = "Êtes-vous sûr de vouloir supprimer ce message ?";
$l['newpm_notice_one'] = "Vous avez un message privé non lu de {1} intitulé {3}";
$l['newpm_notice_multiple'] = "Vous avez {1} messages privés non lus. Le plus récent est de {2} intitulé {4}";
$l['deleteevent_confirm'] = "Êtes-vous sûr de vouloir supprimer cet événement ?";
$l['removeattach_confirm'] = "Êtes-vous sûr de vouloir supprimer la pièce jointe sélectionnée ?";

$l['latest_threads'] = "Dernières Discussions";

$l['folder_inbox'] = "Boîte de réception";
$l['folder_sent_items'] = "Messages envoyés";
$l['folder_drafts'] = "Brouillons";
$l['folder_trash'] = "Corbeille";
$l['folder_untitled'] = "Dossier sans nom";

$l['standard_mod_tools'] = "Outils standard";
$l['custom_mod_tools'] = "Outils personnalisés";

$l['error_loadlimit'] = "La charge limite du serveur a été atteinte. Veuillez revenir plus tard, une fois que le serveur sera moins chargé.";
$l['error_boardclosed'] = "Ce forum est fermé. L'administration en a spécifié la raison ci-dessous.";
$l['error_banned'] = "Vous êtes banni. Vous ne pouvez pas poster, lire de discussion ou accéder au forum. Veuillez contacter l'administrateur si vous avez des questions.";
$l['error_cannot_upload_php_post'] = "Impossible d'uploader le fichier - Trop gros pour la directive php post_max_size. Veuillez cliquer sur le bouton retour.";
$l['error_database_repair'] = "MyBB est en train de réparer automatiquement une table corrompue.";

$l['unknown_user_trigger'] = "Une erreur inconnue s'est produite.";
$l['warnings'] = "Les avertissements suivants se sont produits :";

$l['ajax_loading'] = "Chargement.
Veuillez patienter...";
$l['saving_changes'] = "Sauvegarde des changements...";
$l['refresh'] = "Actualiser";
$l['select_language'] = "Sélection rapide de langue";

$l['invalid_post_code'] = "Erreur de code d'autorisation. Accédez-vous à cette fonction correctement ? Veuillez revenir en arrière et réessayer.";

$l['timezone_gmt_minus_1200'] = "(GMT -12:00) Eniwetok, Kwajalein";
$l['timezone_gmt_minus_1100'] = "(GMT -11:00) Nome, Ile Midway, Samoa";
$l['timezone_gmt_minus_1000'] = "(GMT -10:00) Hawaii";
$l['timezone_gmt_minus_900'] = "(GMT -9:00) Alaska";
$l['timezone_gmt_minus_800'] = "(GMT -8:00) Heure Pacifique";
$l['timezone_gmt_minus_700'] = "(GMT -7:00) Heure Montagne";
$l['timezone_gmt_minus_600'] = "(GMT -6:00) Heure Centrale, Mexico City";
$l['timezone_gmt_minus_500'] = "(GMT -5:00) Heure de l'Est, Bogota, Lima, Quito";
$l['timezone_gmt_minus_450'] = "(GMT -4:30) Venezuela (Septembre)";
$l['timezone_gmt_minus_400'] = "(GMT -4:00) Heure Atlantique, Caracas, La Paz";
$l['timezone_gmt_minus_350'] = "(GMT -3:30) Newfoundland";
$l['timezone_gmt_minus_300'] = "(GMT -3:00) Brésil, Buenos Aires, Georgetown, Iles Falkland";
$l['timezone_gmt_minus_200'] = "(GMT -2:00) Atlantique-Centre, Iles Ascension, Ste Hélène";
$l['timezone_gmt_minus_100'] = "(GMT -1:00) Açores, Iles du Cap Vert";
$l['timezone_gmt'] = "(GMT) Casablanca, Dublin, Edimbourg, Londres, Lisbonne, Monrovia";
$l['timezone_gmt_100'] = "(GMT +1:00) Berlin, Bruxelles, Copenhague, Madrid, Paris, Rome";
$l['timezone_gmt_200'] = "(GMT +2:00) Kaliningrad, Afrique du Sud, Varsovie";
$l['timezone_gmt_300'] = "(GMT +3:00) Baghdad, Riyadh, Moscou, Nairobi";
$l['timezone_gmt_350'] = "(GMT +3:30) Téhéran";
$l['timezone_gmt_400'] = "(GMT +4:00) Abu Dhabi, Bakou, Muscate, Tbilissi";
$l['timezone_gmt_450'] = "(GMT +4:30) Kaboul";
$l['timezone_gmt_500'] = "(GMT +5:00) Islamabad, Karachi, Tachkent";
$l['timezone_gmt_550'] = "(GMT +5:30) Mumbai, Calcutta, Madras, New Delhi";
$l['timezone_gmt_600'] = "(GMT +6:00) Almaty, Colomba, Dhakra";
$l['timezone_gmt_700'] = "(GMT +7:00) Bangkok, Hanoï, Djakarta";
$l['timezone_gmt_800'] = "(GMT +8:00) Pékin, Hong-Kong, Perth, Singapour, Taipei";
$l['timezone_gmt_900'] = "(GMT +9:00) Osaka, Sapporo, Séoul, Tokyo, Yakoutsk";
$l['timezone_gmt_950'] = "(GMT +9:30) Adelaïde, Darwin";
$l['timezone_gmt_1000'] = "(GMT +10:00) Melbourne, Papouasie Nouvelle-Guinée, Sydney, Vladivostok";
$l['timezone_gmt_1100'] = "(GMT +11:00) Magadan, Nouvelle Calédonie, Iles Solomon";
$l['timezone_gmt_1200'] = "(GMT +12:00) Auckland, Wellington, Fidji, Iles Marshall";
$l['timezone_gmt_short'] = "GMT {1}({2})";

$l['missing_task'] = "Erreur : Le fichier de tâche n'existe pas";
$l['task_backup_cannot_write_backup'] = "Erreur : La tâche de sauvegarde de la base de données ne peut pas écrire dans le dossier backups.";
$l['task_backup_ran'] = "La tâche de sauvegarde de la base de données a été exécutée.";
$l['task_checktables_ran'] = "La tâche de vérification des tables a été exécutée sans trouver de table corrompue.";
$l['task_checktables_ran_found'] = "Avertissement : La tâche de vérification des tables a été exécutée et a réparé {1} table(s).";
$l['task_dailycleanup_ran'] = "La tâche de nettoyage journalière a été exécutée.";
$l['task_hourlycleanup_ran'] = "La tâche de nettoyage horaire a été exécutée.";
$l['task_logcleanup_ran'] = "La tâche de suppression des suivis a été exécutée et a supprimé tous les anciens suivis.";
$l['task_promotions_ran'] = "La tâche de promotions de groupes a été exécutée.";
$l['task_threadviews_ran'] = "La tâche d'affichage des discussions a été exécutée.";
$l['task_usercleanup_ran'] = "La tâche de nettoyage journalier a été exécutée.";
$l['task_massmail_ran'] = "La tâche de message colletif a été exécutée.";
$l['task_userpruning_ran'] = "La tâche de suppression d'utilisateur a été exécutée.";
$l['task_massmail_ran'] = "La tâche du modération différée a été exécutée.";
$l['task_massmail_ran_errors'] = "Un ou plusieurs problèmes sont survenus lors de l'envoi à to \"{1}\":
{2}";

$l['dismiss_notice'] = "Annuler cet avertissement";

$l['next'] = "Suivant";
$l['previous'] = "Précédent";
$l['delete'] = "Supprimer";
$l['massmail_username'] = "Nom d'utilisateur";
$l['email_addr'] = "Adresse email";
$l['board_name'] = "Nom du forum";
$l['board_url'] = "URL du forum";

$l['comma'] = ", ";
?>


text:
package kfs.kfsUtils.kfsSsh;

import com.jcraft.jsch.*;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

/**
 *
 * @author pavedrim
 */
public abstract class kfsSsh implements UserInfo {

    private final JSch ssh;
    private Session session;
    private ChannelSftp channel;

    public kfsSsh() throws kfsSshException {
        ssh = new JSch();
        session = null;
        channel = null;
    }

    public void connect2() throws kfsSshException {
        try {
            session = ssh.getSession(getUser(), getHost(), getPort());
        } catch (JSchException ex) {
            throw new kfsSshException("Cannot get session for " + getUser() + "@" + getHost(), ex);
        }
        session.setUserInfo(this);
        try {
            session.connect();
        } catch (JSchException ex) {
            throw new kfsSshException("Cannot connect for " + getUser() + "@" + getHost(), ex);
        }
    }

    public void connect() throws kfsSshException {
        if (session == null) {
            connect2();
        }
        if (channel == null) {
            Channel ch;
            try {
                ch = session.openChannel("sftp");
            } catch (JSchException ex) {
                throw new kfsSshException("Cannot open chanel for sftp", ex);
            }
            try {
                ch.connect();
            } catch (JSchException ex) {
                throw new kfsSshException("Cannot connect on chanel sftp", ex);
            }
            channel = (ChannelSftp) ch;
        }
    }

    public InputStream getStream(String remoteFile) throws kfsSshException {
        if (channel == null) {
            connect();
        }
        try {
            return channel.get(remoteFile);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot open input stream for file " + remoteFile, ex);
        }
    }

    public OutputStream put_owerwrite(String remoteFile) throws kfsSshException {
        if (channel == null) {
            connect();
        }
        try {
            return channel.put(remoteFile, ChannelSftp.OVERWRITE);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot put file " + remoteFile, ex);
        }
    }

    public void put_append(InputStream input, String remoteFile) throws //
            kfsSshException {
        if (channel == null) {
            connect();
        }
        try {
            channel.put(input, remoteFile, ChannelSftp.APPEND);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot append file " + remoteFile, ex);
        }
    }

    public void get(String file, OutputStream out) throws kfsSshException {
        if (channel == null) {
            connect();
        }
        try {
            channel.get(file, out);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot get file " + file, ex);
        }
    }

    public String[] ls(String remoteFolder) throws kfsSshException {
        if (channel == null) {
            connect();
        }
        ArrayList<String> al = new ArrayList<String>();
        Vector v = null;
        try {
            v = channel.ls(remoteFolder);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot list folder " + remoteFolder, ex);
        }
        if (v != null) {
            for (Object o : v) {
                if (o != null) {
                    ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) o;
                    al.add(le.getFilename());
                }
            }
        }
        return al.toArray(new String[0]);
    }

    public List<String> listFilesByDate(String remoteFolder, FilenameFilter filter, long fromTime, long toTime) throws kfsSshException {
        if (channel == null) {
            connect();
        }
        Vector v = null;
        try {
            v = channel.ls(remoteFolder);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot list folder " + remoteFolder, ex);
        }
        ArrayList<String> ret = new ArrayList<String>();
        if (v != null) {
            for (Iterator it = v.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o != null) {
                    ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) o;
                    if (le.getFilename().startsWith(".")) {
                        continue;
                    }
                    if (le.getAttrs().isDir()) {
                        continue;
                    }
                    if ((filter == null) || (filter.accept(null, le.getFilename()))) {
                        long mtime = 1000L*((long)le.getAttrs().getMTime());
                        if ((fromTime <= mtime) && (toTime >= mtime)) {
                            ret.add(le.getFilename());
                        }
                    }
                }
            }
        }
        return ret;
    }

    public String[] lsl(String remoteFolder) throws kfsSshException {
        if (channel == null) {
            connect();
        }

        SortingList<String> al = new SortingList<String>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        Vector v = null;
        try {
            v = channel.ls(remoteFolder);
        } catch (SftpException ex) {
            throw new kfsSshException("Cannot list folder " + remoteFolder, ex);
        }
        if (v != null) {
            for (Iterator it = v.iterator(); it.hasNext();) {
                Object o = it.next();
                if (o != null) {
                    ChannelSftp.LsEntry le = (ChannelSftp.LsEntry) o;
                    if (le.getFilename().startsWith(".")) {
                        continue;
                    }
                    al.add(String.format("| %1$tm-%1$td %1$tR | %2$10d | %3$-30s |", //
                            new java.util.Date(le.getAttrs().getMTime() * 1000L),//
                            le.getAttrs().getSize(), //
                            (le.getAttrs().isDir() ? "/" : "") + le.getFilename()));
                }
            }
        }
        ArrayList<String> s = new ArrayList<String>();
        s.add("|-------------|------------|--------------------------------|");
        s.add("|     time    |   size [B] | name                           |");
        s.add("|-------------|------------|--------------------------------|");
        s.addAll(al);
        s.add("|-------------|------------|--------------------------------|");
        return s.toArray(new String[0]);
    }

    public void done() {
        if (channel != null) {
            channel.exit();
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
        channel = null;
        session = null;
    }

    public void execute(String cmd, InputStream in, OutputStream out, OutputStream err) throws kfsSshException {
        if (session == null) {
            connect2();
        }
        ChannelExec exCh;
        try {
            exCh = (ChannelExec) session.openChannel("exec");
        } catch (JSchException ex) {
            throw new kfsSshException("Cannot execute " + cmd, ex);
        }
        if (exCh != null) {
            try {
                exCh.setCommand(cmd);
                exCh.setInputStream(in);
                exCh.setErrStream(err);
                try {
                    exCh.connect();
                } catch (JSchException ex) {
                    throw new kfsSshException("Cannot execute " + cmd, ex);
                }
                try {
                    in = exCh.getInputStream();
                } catch (IOException ex) {
                    throw new kfsSshException("Cannot execute " + cmd, ex);
                }
                byte[] tmp = new byte[1024];
                while (true) {
                    try {
                        while (in.available() > 0) {
                            int i = 0;
                            try {
                                i = in.read(tmp, 0, 1024);
                            } catch (IOException ex) {
                                throw new kfsSshException("Cannot read " + i, ex);
                            }
                            if (i < 0) {
                                break;
                            }
                            try {
                                out.write(tmp, 0, i);
                            } catch (IOException ex) {
                                throw new kfsSshException("Cannot write " + i, ex);
                            }
                        }
                    } catch (IOException ex) {
                        throw new kfsSshException("Cannot read avialable", ex);
                    }
                    if (exCh.isClosed()) {
                        //System.out.println("exit-status: " + exCh.getExitStatus());
                        break;
                    }
                }

            } finally {
                exCh.disconnect();
            }
        }

    }

    public int getPort() {
        return 22;
    }

    @Override
    public String getPassphrase() {
        return null;
    }

    @Override
    public boolean promptPassword(String message) {
        return true;
    }

    @Override
    public boolean promptPassphrase(String message) {
        return true;
    }

    @Override
    public boolean promptYesNo(String message) {
        return true;
    }

    @Override
    public void showMessage(String message) {
    }

    public abstract String getUser();

    public abstract String getHost();

    @Override
    public abstract String getPassword();
}


text:
package org.apache.taverna.activities.spreadsheet;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

import java.util.Arrays;

import org.junit.Before;
import org.junit.Test;

/**
 * Unit tests for {@link net.sf.taverna.t2.activities.spreadsheet.Range}.
 *
 * @author David Withers
 */
public class RangeTest {

	private Range range;

	@Before
	public void setUp() throws Exception {
		range = new Range(1, 5);
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#Range(int, int)}.
	 */
	@Test
	public void testRangeIntInt() {
		Range range = new Range(3, 9);
		assertEquals(3, range.getStart());
		assertEquals(9, range.getEnd());
	}

	/**
	 * Test method for
	 * {@link net.sf.taverna.t2.activities.spreadsheet.Range#Range(int, int, net.sf.taverna.t2.activities.spreadsheet.Range)}
	 * .
	 */
	@Test
	public void testRangeIntIntRange() {
		Range range = new Range(0, 12, new Range(3, 9));
		assertEquals(0, range.getStart());
		assertEquals(12, range.getEnd());
		assertTrue(range.contains(0));
		assertTrue(range.contains(2));
		assertFalse(range.contains(5));
	}

	/**
	 * Test method for
	 * {@link net.sf.taverna.t2.activities.spreadsheet.Range#Range(int, int, java.util.List)}.
	 */
	@Test
	public void testRangeIntIntListOfRange() {
		Range range = new Range(-2, 12, Arrays.asList(new Range(3, 5), new Range(10, 11)));
		assertEquals(-2, range.getStart());
		assertEquals(12, range.getEnd());
		assertTrue(range.contains(-2));
		assertTrue(range.contains(-0));
		assertTrue(range.contains(6));
		assertTrue(range.contains(12));
		assertFalse(range.contains(4));
		assertFalse(range.contains(11));
	}

	/**
	 * Test method for
	 * {@link net.sf.taverna.t2.activities.spreadsheet.Range#Range(net.sf.taverna.t2.activities.spreadsheet.Range)}
	 * .
	 */
	@Test
	public void testRangeRange() {
		Range rangeCopy = new Range(range);
		assertEquals(rangeCopy, range);
		assertEquals(range.getStart(), rangeCopy.getStart());
		assertEquals(range.getEnd(), rangeCopy.getEnd());
		range = new Range(0, 7, range);
		rangeCopy = new Range(range);
		assertFalse(rangeCopy.equals(new Range(2,3)));
		assertEquals(rangeCopy, range);
		assertEquals(range.getStart(), rangeCopy.getStart());
		assertEquals(range.getEnd(), rangeCopy.getEnd());
		assertArrayEquals(range.getRangeValues(), rangeCopy.getRangeValues());
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#contains(int)}.
	 */
	@Test
	public void testContains() {
		assertTrue(range.contains(2));
		assertFalse(range.contains(7));
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#getRangeValues()}.
	 */
	@Test
	public void testGetRangeValues() {
		assertArrayEquals(new int[] { 1, 2, 3, 4, 5 }, range.getRangeValues());
		Range range2 = new Range(0, 7, range);
		assertArrayEquals(new int[] { 0, 6, 7 }, range2.getRangeValues());
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#getStart()}.
	 */
	@Test
	public void testGetStart() {
		assertEquals(1, range.getStart());
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#setStart(int)}.
	 */
	@Test
	public void testSetStart() {
		range.setStart(2);
		assertEquals(2, range.getStart());
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#getEnd()}.
	 */
	@Test
	public void testGetEnd() {
		assertEquals(5, range.getEnd());
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#setEnd(int)}.
	 */
	@Test
	public void testSetEnd() {
		range.setEnd(7);
		assertEquals(7, range.getEnd());
	}

	/**
	 * Test method for
	 * {@link net.sf.taverna.t2.activities.spreadsheet.Range#addExclude(net.sf.taverna.t2.activities.spreadsheet.Range)}
	 * .
	 */
	@Test
	public void testAddExclude() {
		range.addExclude(new Range(4, 4));
		assertTrue(range.contains(2));
		assertTrue(range.contains(5));
		assertFalse(range.contains(4));
	}

	/**
	 * Test method for
	 * {@link net.sf.taverna.t2.activities.spreadsheet.Range#removeExclude(net.sf.taverna.t2.activities.spreadsheet.Range)}
	 * .
	 */
	@Test
	public void testRemoveExclude() {
		range.addExclude(new Range(4, 4));
		range.removeExclude(new Range(4, 4));
		assertTrue(range.contains(4));
	}

	/**
	 * Test method for {@link net.sf.taverna.t2.activities.spreadsheet.Range#toString()}.
	 */
	@Test
	public void testToString() {
		assertEquals("[1..5]", range.toString());
	}

}


text:
package methods

import (
	"fmt"
	"log"
	"strings"
	"unicode"
)

const qsReceiverName = "qs"
const qsDbName = qsReceiverName + ".db"

// retQuerySetMethod

type retQuerySetMethod struct {
	qsTypeName string
}

// GetReturnValuesDeclaration gets return values declaration
func (m retQuerySetMethod) GetReturnValuesDeclaration() string {
	return m.qsTypeName
}

func newRetQuerySetMethod(qsTypeName string) retQuerySetMethod {
	return retQuerySetMethod{
		qsTypeName: qsTypeName,
	}
}

type GetDBMethod struct {
	namedMethod
	baseQuerySetMethod
	constRetMethod
	noArgsMethod
	constBodyMethod
}

func NewGetDBMethod(qsTypeName string) GetDBMethod {
	return GetDBMethod{
		namedMethod:        newNamedMethod("GetDB"),
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		constRetMethod:     newConstRetMethod("*gorm.DB"),
		constBodyMethod:    newConstBodyMethod("return qs.db"),
	}
}

// baseQuerySetMethod

type baseQuerySetMethod struct {
	structMethod
}

func newBaseQuerySetMethod(qsTypeName string) baseQuerySetMethod {
	return baseQuerySetMethod{
		structMethod: newStructMethod(qsReceiverName, qsTypeName),
	}
}

// chainedQuerySetMethod
type chainedQuerySetMethod struct {
	baseQuerySetMethod
	retQuerySetMethod
}

func newChainedQuerySetMethod(qsTypeName string) chainedQuerySetMethod {
	return chainedQuerySetMethod{
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		retQuerySetMethod:  newRetQuerySetMethod(qsTypeName),
	}
}

// FieldOperationNoArgsMethod is for unary operations: preload, orderby, etc
type FieldOperationNoArgsMethod struct {
	qsCallGormMethod
	onFieldMethod
	noArgsMethod
	chainedQuerySetMethod
}

func newFieldOperationNoArgsMethod(ctx QsFieldContext, transformFieldName bool) FieldOperationNoArgsMethod {

	gormArgName := ctx.fieldName()
	if transformFieldName {
		gormArgName = ctx.fieldDBName()
	}

	r := FieldOperationNoArgsMethod{
		onFieldMethod:         ctx.onFieldMethod(),
		qsCallGormMethod:      newQsCallGormMethod(ctx.operationName, `"%s"`, gormArgName),
		chainedQuerySetMethod: ctx.chainedQuerySetMethod(),
	}
	r.setFieldNameFirst(false) // UserPreload -> PreloadUser
	return r
}

// LowercaseFirstRune lowercases first rune of string
func LowercaseFirstRune(s string) string {
	r := []rune(s)
	r[0] = unicode.ToLower(r[0])
	return string(r)
}

// StructOperationOneArgMethod is for struct operations with one arg
type StructOperationOneArgMethod struct {
	namedMethod
	chainedQuerySetMethod
	oneArgMethod
	qsCallGormMethod
}

func newStructOperationOneArgMethod(name, argTypeName, qsTypeName string) StructOperationOneArgMethod {
	argName := strings.ToLower(name)
	return StructOperationOneArgMethod{
		namedMethod:           newNamedMethod(name),
		chainedQuerySetMethod: newChainedQuerySetMethod(qsTypeName),
		oneArgMethod:          newOneArgMethod(argName, argTypeName),
		qsCallGormMethod:      newQsCallGormMethod(name, argName),
	}
}

type qsCallGormMethod struct {
	callGormMethod
}

func (m qsCallGormMethod) GetBody() string {
	return wrapToGormScope(m.callGormMethod.GetBody())
}

func newQsCallGormMethod(name, argsFmt string, argsArgs ...interface{}) qsCallGormMethod {
	return qsCallGormMethod{
		callGormMethod: newCallGormMethod(name, fmt.Sprintf(argsFmt, argsArgs...), qsDbName),
	}
}

// BinaryFilterMethod is a binary filter method
type BinaryFilterMethod struct {
	chainedQuerySetMethod
	onFieldMethod
	oneArgMethod
	qsCallGormMethod
}

// NewBinaryFilterMethod create new binary filter method
func NewBinaryFilterMethod(ctx QsFieldContext) BinaryFilterMethod {
	argName := fieldNameToArgName(ctx.fieldName())
	return BinaryFilterMethod{
		onFieldMethod:         ctx.onFieldMethod(),
		oneArgMethod:          newOneArgMethod(argName, ctx.fieldTypeName()),
		chainedQuerySetMethod: ctx.chainedQuerySetMethod(),
		qsCallGormMethod: newQsCallGormMethod("Where", "\"%s %s\", %s",
			ctx.fieldDBName(), getWhereCondition(ctx.operationName), argName),
	}
}

// InFilterMethod filters with IN condition
type InFilterMethod struct {
	chainedQuerySetMethod
	onFieldMethod
	nArgsMethod
	qsCallGormMethod
}

func (m InFilterMethod) GetBody() string {
	tmpl := `if len(%s) == 0 {
	qs.db.AddError(errors.New("must at least pass one %s in %s"))
	return qs.w(qs.db)
	}
	`
	return fmt.Sprintf(tmpl, m.getArgName(0), m.getArgName(0), m.GetMethodName()) + m.qsCallGormMethod.GetBody()
}

func newInFilterMethodImpl(ctx QsFieldContext, operationName, sql string) InFilterMethod {
	ctx = ctx.WithOperationName(operationName)
	argName := fieldNameToArgName(ctx.fieldName())
	args := newNArgsMethod(
		newOneArgMethod(argName, "..."+ctx.fieldTypeName()),
	)
	return InFilterMethod{
		onFieldMethod:         ctx.onFieldMethod(),
		nArgsMethod:           args,
		chainedQuerySetMethod: ctx.chainedQuerySetMethod(),
		qsCallGormMethod: newQsCallGormMethod("Where", "\"%s %s (?)\", %s",
			ctx.fieldDBName(), sql, argName),
	}
}

// NewInFilterMethod create new IN filter method
func NewInFilterMethod(ctx QsFieldContext) InFilterMethod {
	return newInFilterMethodImpl(ctx, "In", "IN")
}

// NewNotInFilterMethod create new NOT IN filter method
func NewNotInFilterMethod(ctx QsFieldContext) InFilterMethod {
	return newInFilterMethodImpl(ctx, "NotIn", "NOT IN")
}

func getWhereCondition(name string) string {
	nameToOp := map[string]string{
		"eq":      "=",
		"ne":      "!=",
		"lt":      "<",
		"lte":     "<=",
		"gt":      ">",
		"gte":     ">=",
		"like":    "LIKE",
		"notlike": "NOT LIKE",
	}
	op := nameToOp[name]
	if op == "" {
		log.Fatalf("no operation for filter %q", name)
	}

	return fmt.Sprintf("%s ?", op)
}

// UnaryFilterMethod represents unary filter
type UnaryFilterMethod struct {
	onFieldMethod
	noArgsMethod
	chainedQuerySetMethod
	qsCallGormMethod
}

func newUnaryFilterMethod(ctx QsFieldContext, op string) UnaryFilterMethod {
	r := UnaryFilterMethod{
		onFieldMethod: ctx.onFieldMethod(),
		qsCallGormMethod: newQsCallGormMethod("Where", `"%s %s"`,
			ctx.fieldDBName(), op),
		chainedQuerySetMethod: ctx.chainedQuerySetMethod(),
	}
	return r
}

// unaryFilerMethod

// SelectMethod is a select field (all, one, etc)
type SelectMethod struct {
	namedMethod
	oneArgMethod
	baseQuerySetMethod
	gormErroredMethod
}

func newSelectMethod(name, gormName, argTypeName, qsTypeName string) SelectMethod {
	return SelectMethod{
		namedMethod:        newNamedMethod(name),
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		oneArgMethod:       newOneArgMethod("ret", argTypeName),
		gormErroredMethod:  newGormErroredMethod(gormName, "ret", qsDbName),
	}
}

// GetUpdaterMethod creates GetUpdater method
type GetUpdaterMethod struct {
	baseQuerySetMethod
	namedMethod
	noArgsMethod
	constRetMethod
	constBodyMethod
}

// NewGetUpdaterMethod creates GetUpdaterMethod
func NewGetUpdaterMethod(qsTypeName, updaterTypeMethod string) GetUpdaterMethod {
	return GetUpdaterMethod{
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		namedMethod:        newNamedMethod("GetUpdater"),
		constRetMethod:     newConstRetMethod(updaterTypeMethod),
		constBodyMethod:    newConstBodyMethod("return New%s(%s)", updaterTypeMethod, qsDbName),
	}
}

// DeleteMethod creates Delete method
type DeleteMethod struct {
	baseQuerySetMethod

	namedMethod
	noArgsMethod

	gormErroredMethod
}

// NewDeleteMethod creates Delete method
func NewDeleteMethod(qsTypeName, structTypeName string) DeleteMethod {
	return DeleteMethod{

		namedMethod:        newNamedMethod("Delete"),
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		gormErroredMethod:  newGormErroredMethod("Delete", structTypeName+"{}", qsDbName),
	}
}

// DeleteNumMethod creates DeleteNum method
type DeleteNumMethod struct {
	namedMethod
	baseQuerySetMethod

	noArgsMethod
	constBodyMethod
	constRetMethod
}

// NewDeleteNumMethod delete row count
func NewDeleteNumMethod(qsTypeName, structTypeName string) DeleteNumMethod {
	return DeleteNumMethod{
		namedMethod:        newNamedMethod("DeleteNum"),
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		constRetMethod:     newConstRetMethod("(int64, error)"),
		constBodyMethod: newConstBodyMethod(
			strings.Join([]string{
				"db := qs.db.Delete(" + structTypeName + "{}" + ")",
				"return db.RowsAffected, db.Error",
			}, "\n"),
		),
	}
}

// DeleteNumUnscopedMethod creates DeleteNumUnscoped method for performing hard deletes
type DeleteNumUnscopedMethod struct {
	namedMethod
	baseQuerySetMethod

	noArgsMethod
	constBodyMethod
	constRetMethod
}

// NewDeleteNumUnscopedMethod delete row count for hard deletes
func NewDeleteNumUnscopedMethod(qsTypeName, structTypeName string) DeleteNumUnscopedMethod {
	return DeleteNumUnscopedMethod{
		namedMethod:        newNamedMethod("DeleteNumUnscoped"),
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		constRetMethod:     newConstRetMethod("(int64, error)"),
		constBodyMethod: newConstBodyMethod(
			strings.Join([]string{
				"db := qs.db.Unscoped().Delete(" + structTypeName + "{}" + ")",
				"return db.RowsAffected, db.Error",
			}, "\n"),
		),
	}
}

// CountMethod creates Count method
type CountMethod struct {
	baseQuerySetMethod
	namedMethod
	noArgsMethod
	constRetMethod
	constBodyMethod
}

// NewCountMethod returns new CountMethod
func NewCountMethod(qsTypeName string) CountMethod {
	return CountMethod{
		baseQuerySetMethod: newBaseQuerySetMethod(qsTypeName),
		namedMethod:        newNamedMethod("Count"),
		constRetMethod:     newConstRetMethod("(int, error)"),
		constBodyMethod: newConstBodyMethod(`var count int
			err := %s.Count(&count).Error
			return count, err`, qsDbName),
	}
}

// Concrete methods

// NewPreloadMethod creates new Preload method
func NewPreloadMethod(ctx QsFieldContext) FieldOperationNoArgsMethod {
	r := newFieldOperationNoArgsMethod(ctx.WithOperationName("Preload"), false)
	return r
}

// NewOrderAscByMethod creates new OrderBy method ascending
func NewOrderAscByMethod(ctx QsFieldContext) FieldOperationNoArgsMethod {
	r := newFieldOperationNoArgsMethod(ctx.WithOperationName("OrderAscBy"), true)
	r.setGormMethodName("Order")
	r.setGormMethodArgs(fmt.Sprintf(`"%s ASC"`, ctx.fieldDBName()))
	return r
}

// NewOrderDescByMethod creates new OrderBy method descending
func NewOrderDescByMethod(ctx QsFieldContext) FieldOperationNoArgsMethod {
	r := newFieldOperationNoArgsMethod(ctx.WithOperationName("OrderDescBy"), true)
	r.setGormMethodName("Order")
	r.setGormMethodArgs(fmt.Sprintf(`"%s DESC"`, ctx.fieldDBName()))
	return r
}

// NewLimitMethod creates Limit method
func NewLimitMethod(qsTypeName string) StructOperationOneArgMethod {
	return newStructOperationOneArgMethod("Limit", "int", qsTypeName)
}

// NewOffsetMethod creates Offset method
func NewOffsetMethod(qsTypeName string) StructOperationOneArgMethod {
	return newStructOperationOneArgMethod("Offset", "int", qsTypeName)
}

// NewAllMethod creates All method
func NewAllMethod(structName, qsTypeName string) SelectMethod {
	return newSelectMethod("All", "Find", fmt.Sprintf("*[]%s", structName), qsTypeName)
}

// NewOneMethod creates One method
func NewOneMethod(structName, qsTypeName string) SelectMethod {
	r := newSelectMethod("One", "First", fmt.Sprintf("*%s", structName), qsTypeName)
	const doc = `// One is used to retrieve one result. It returns gorm.ErrRecordNotFound
	// if nothing was fetched`
	r.setDoc(doc)
	return r
}

// NewIsNullMethod create IsNull method
func NewIsNullMethod(ctx QsFieldContext) UnaryFilterMethod {
	return newUnaryFilterMethod(ctx.WithOperationName("IsNull"), "IS NULL")
}

// NewIsNotNullMethod create IsNotNull method
func NewIsNotNullMethod(ctx QsFieldContext) UnaryFilterMethod {
	return newUnaryFilterMethod(ctx.WithOperationName("IsNotNull"), "IS NOT NULL")
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

    <meta name="twitter:site" content="@metroui">
    <meta name="twitter:creator" content="@pimenov_sergey">
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Metro 4 Components Library">
    <meta name="twitter:description" content="Metro 4 is an open source toolkit for developing with HTML, CSS, and JS. Quickly prototype your ideas or build your entire app with responsive grid system, extensive prebuilt components, and powerful plugins built on jQuery.">
    <meta name="twitter:image" content="https://metroui.org.ua/images/m4-logo-social.png">

    <meta property="og:url" content="https://metroui.org.ua/v4/index.html">
    <meta property="og:title" content="Metro 4 Components Library">
    <meta property="og:description" content="Metro 4 is an open source toolkit for developing with HTML, CSS, and JS. Quickly prototype your ideas or build your entire app with responsive grid system, extensive prebuilt components, and powerful plugins built on jQuery.">
    <meta property="og:type" content="website">
    <meta property="og:image" content="https://metroui.org.ua/images/m4-logo-social.png">
    <meta property="og:image:secure_url" content="https://metroui.org.ua/images/m4-logo-social.png">
    <meta property="og:image:type" content="image/png">
    <meta property="og:image:width" content="968">
    <meta property="og:image:height" content="504">

    <meta name="author" content="Sergey Pimenov">
    <meta name="description" content="The most popular HTML, CSS, and JS library in Metro style.">
    <meta name="keywords" content="HTML, CSS, JS, Metro, CSS3, Javascript, HTML5, UI, Library, Web, Development, Framework">

    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
    <link rel="icon" href="favicon.ico" type="image/x-icon">

    <link href="metro/css/metro-all.css" rel="stylesheet">
    <link href="highlight/styles/github.css" rel="stylesheet">
    <link href="docsearch/docsearch.min.css" rel="stylesheet">
    <link href="css/site.css" rel="stylesheet">

    <title>Configuring - Metro 4 :: Popular HTML, CSS and JS library</title>

Table of contents

Configuring

About

Meta options

Initialization

Configuring

                    Use meta options to configuring Metro 4.

About

                    You can set up the global options of Metro 4 with meta tags.

                    <meta name="metro4:init" content="true">
                    <meta name="metro4:locale" content="de-DE">
                    <meta name="metro4:week_start" content="1">

Meta options

                        Meta
                        Value
                        Desc

                        metro4:init
                        true | false
                        Determines whether Metro 4 is automatically initialized

                        metro4:locale
                        string
                        Determines default locale

                        metro4:week_start
                        0 | 1
                        Determines week start 0 - sunday, 1 - monday

                        metro4:animation_duration
                        integer
                        Value in milliseconds for animation duration

                        metro4:callback_timeout
                        integer
                        Reserved for feature

                        metro4:timeout
                        integer
                        Value in milliseconds, used for notify and toasts

Metro 4 initialization

                    By default Metro 4 init immediately after loading, without waiting for all DOM content is load. If you need wait for all DOM content is load, you must:

Set <meta name="metro4:init" content="false">

Manually init Metro 4 with method: Metro.init()


text:
using System;
using KInspector.Core;

namespace KInspector.Modules.Modules.Setup
{
    public class SmtpServersSetupModule : IModule
    {
        public ModuleMetadata GetModuleMetadata()
        {
            return new ModuleMetadata
            {
                Name = "Disable enabled SMTP servers",
                Comment = @"Disables SMTP servers defined either in the Settings or SMTP servers application.

The servers are disabled by setting their server address to invalid value, so that servers disabled by the audit can be identified.",
                SupportedVersions = new[] {
                    new Version("8.0"),
                    new Version("8.1"),
                    new Version("8.2")
                },
                Category = "Setup",
            };
        }

        public ModuleResults GetResults(InstanceInfo instanceInfo)
        {
            var dbService = instanceInfo.DBService;
            var results = dbService.ExecuteAndGetDataSetFromFile("Setup/SmtpServerSetupModule.sql");

            return new ModuleResults
            {
                Result = results
            };
        }
    }
}