text:
import re
import traceback
from . import pylexotron, util

Hint = pylexotron.Hint

class CqlParsingRuleSet(pylexotron.ParsingRuleSet):
    keywords = set((
        'select', 'from', 'where', 'and', 'key', 'insert', 'update', 'with',
        'limit', 'using', 'consistency', 'one', 'quorum', 'all', 'any',
        'local_quorum', 'each_quorum', 'two', 'three', 'use', 'count', 'set',
        'begin', 'apply', 'batch', 'truncate', 'delete', 'in', 'create',
        'keyspace', 'schema', 'columnfamily', 'table', 'index', 'on', 'drop',
        'primary', 'into', 'values', 'timestamp', 'ttl', 'alter', 'add', 'type',
        'first', 'reversed'
    ))

    columnfamily_options = (
        # (CQL option name, Thrift option name (or None if same))
        ('comment', None),
        ('comparator', 'comparator_type'),
        ('read_repair_chance', None),
        ('gc_grace_seconds', None),
        ('default_validation', 'default_validation_class'),
        ('min_compaction_threshold', None),
        ('max_compaction_threshold', None),
        ('replicate_on_write', None),
        ('compaction_strategy_class', 'compaction_strategy'),
    )

    obsolete_cf_options = (
        ('key_cache_size', None),
        ('row_cache_size', None),
        ('row_cache_save_period_in_seconds', None),
        ('key_cache_save_period_in_seconds', None),
        ('memtable_throughput_in_mb', None),
        ('memtable_operations_in_millions', None),
        ('memtable_flush_after_mins', None),
        ('row_cache_provider', None),
    )

    all_columnfamily_options = columnfamily_options + obsolete_cf_options

    columnfamily_map_options = (
        ('compaction_strategy_options', None,
            ()),
        ('compression_parameters', 'compression_options',
            ('sstable_compression', 'chunk_length_kb', 'crc_check_chance')),
    )

    available_compression_classes = (
        'DeflateCompressor',
        'SnappyCompressor',
    )

    available_compaction_classes = (
        'LeveledCompactionStrategy',
        'SizeTieredCompactionStrategy'
    )

    cql_type_to_apache_class = {
        'ascii': 'AsciiType',
        'bigint': 'LongType',
        'blob': 'BytesType',
        'boolean': 'BooleanType',
        'counter': 'CounterColumnType',
        'decimal': 'DecimalType',
        'double': 'DoubleType',
        'float': 'FloatType',
        'int': 'Int32Type',
        'text': 'UTF8Type',
        'timestamp': 'DateType',
        'uuid': 'UUIDType',
        'varchar': 'UTF8Type',
        'varint': 'IntegerType'
    }

    apache_class_to_cql_type = dict((v,k) for (k,v) in cql_type_to_apache_class.items())

    cql_types = sorted(cql_type_to_apache_class.keys())

    replication_strategies = (
        'SimpleStrategy',
        'OldNetworkTopologyStrategy',
        'NetworkTopologyStrategy'
    )

    consistency_levels = (
        'ANY',
        'ONE',
        'TWO',
        'THREE',
        'QUORUM',
        'ALL',
        'LOCAL_QUORUM',
        'EACH_QUORUM'
    )

    # if a term matches this, it shouldn't need to be quoted to be valid cql
    valid_cql_word_re = re.compile(r"^(?:[a-z][a-z0-9_]*|-?[0-9][0-9.]*)$", re.I)

    def __init__(self, *args, **kwargs):
        pylexotron.ParsingRuleSet.__init__(self, *args, **kwargs)

        # note: commands_end_with_newline may be extended by callers.
        self.commands_end_with_newline = set()
        self.set_keywords_as_syntax()

    def completer_for(self, rulename, symname):
        def registrator(f):
            def completerwrapper(ctxt):
                cass = ctxt.get_binding('cassandra_conn', None)
                if cass is None:
                    return ()
                return f(ctxt, cass)
            completerwrapper.func_name = 'completerwrapper_on_' + f.func_name
            self.register_completer(completerwrapper, rulename, symname)
            return completerwrapper
        return registrator

    def explain_completion(self, rulename, symname, explanation=None):
        if explanation is None:
            explanation = '<%s>' % (symname,)
        @self.completer_for(rulename, symname)
        def explainer(ctxt, cass):
            return [Hint(explanation)]
        return explainer

    def set_keywords_as_syntax(self):
        syntax = []
        for k in self.keywords:
            syntax.append('<K_%s> ::= "%s" ;' % (k.upper(), k))
        self.append_rules('\n'.join(syntax))

    def cql_massage_tokens(self, toklist):
        curstmt = []
        output = []

        term_on_nl = False

        for t in toklist:
            if t[0] == 'endline':
                if term_on_nl:
                    t = ('endtoken',) + t[1:]
                else:
                    # don't put any 'endline' tokens in output
                    continue
            curstmt.append(t)
            if t[0] == 'endtoken':
                term_on_nl = False
                output.extend(curstmt)
                curstmt = []
            else:
                if len(curstmt) == 1:
                    # first token in statement; command word
                    cmd = t[1].lower()
                    term_on_nl = bool(cmd in self.commands_end_with_newline)

        output.extend(curstmt)
        return output

    def cql_parse(self, text, startsymbol='Start'):
        tokens = self.lex(text)
        tokens = self.cql_massage_tokens(tokens)
        return self.parse(startsymbol, tokens, init_bindings={'*SRC*': text})

    def cql_whole_parse_tokens(self, toklist, srcstr=None, startsymbol='Start'):
        return self.whole_match(startsymbol, toklist, srcstr=srcstr)

    def cql_split_statements(self, text):
        tokens = self.lex(text)
        tokens = self.cql_massage_tokens(tokens)
        stmts = util.split_list(tokens, lambda t: t[0] == 'endtoken')
        output = []
        in_batch = False
        for stmt in stmts:
            if in_batch:
                output[-1].extend(stmt)
            else:
                output.append(stmt)
            if len(stmt) > 1 \
            and stmt[0][0] == 'identifier' and stmt[1][0] == 'identifier' \
            and stmt[1][1].lower() == 'batch':
                if stmt[0][1].lower() == 'begin':
                    in_batch = True
                elif stmt[0][1].lower() == 'apply':
                    in_batch = False
        return output, in_batch

    def cql_complete_single(self, text, partial, init_bindings={}, ignore_case=True,
                            startsymbol='Start'):
        tokens = (self.cql_split_statements(text)[0] or [[]])[-1]
        bindings = init_bindings.copy()

        # handle some different completion scenarios- in particular, completing
        # inside a string literal
        prefix = None
        dequoter = util.identity
        lasttype = None
        if tokens:
            lasttype = tokens[-1][0]
            if lasttype == 'unclosedString':
                prefix = self.token_dequote(tokens[-1])
                tokens = tokens[:-1]
                partial = prefix + partial
                dequoter = self.dequote_value
                requoter = self.escape_value
            elif lasttype == 'unclosedName':
                prefix = self.token_dequote(tokens[-1])
                tokens = tokens[:-1]
                partial = prefix + partial
                dequoter = self.dequote_name
                requoter = self.escape_name
            elif lasttype == 'unclosedComment':
                return []
        bindings['partial'] = partial
        bindings['*LASTTYPE*'] = lasttype
        bindings['*SRC*'] = text

        # find completions for the position
        completions = self.complete(startsymbol, tokens, bindings)

        hints, strcompletes = util.list_bifilter(pylexotron.is_hint, completions)

        # it's possible to get a newline token from completion; of course, we
        # don't want to actually have that be a candidate, we just want to hint
        if '\n' in strcompletes:
            strcompletes.remove('\n')
            if partial == '':
                hints.append(Hint('<enter>'))

        # find matches with the partial word under completion
        if ignore_case:
            partial = partial.lower()
            f = lambda s: s and dequoter(s).lower().startswith(partial)
        else:
            f = lambda s: s and dequoter(s).startswith(partial)
        candidates = filter(f, strcompletes)

        if prefix is not None:
            # dequote, re-escape, strip quotes: gets us the right quoted text
            # for completion. the opening quote is already there on the command
            # line and not part of the word under completion, and readline
            # fills in the closing quote for us.
            candidates = [requoter(dequoter(c))[len(prefix)+1:-1] for c in candidates]

            # the above process can result in an empty string; this doesn't help for
            # completions
            candidates = filter(None, candidates)

        # prefix a space when desirable for pleasant cql formatting
        if tokens:
            newcandidates = []
            for c in candidates:
                if self.want_space_between(tokens[-1], c) \
                and prefix is None \
                and not text[-1].isspace() \
                and not c[0].isspace():
                    c = ' ' + c
                newcandidates.append(c)
            candidates = newcandidates

        # append a space for single, complete identifiers
        if len(candidates) == 1 and candidates[0][-1].isalnum()  \
                                and lasttype != 'unclosedString' \
                                and lasttype != 'unclosedName':
            candidates[0] += ' '
        return candidates, hints

    @staticmethod
    def want_space_between(tok, following):
        if following in (',', ')', ':'):
            return False
        if tok[0] == 'op' and tok[1] in (',', ')', '='):
            return True
        if tok[0] == 'stringLiteral' and following[0] != ';':
            return True
        if tok[0] == 'star' and following[0] != ')':
            return True
        if tok[0] == 'endtoken':
            return True
        if tok[1][-1].isalnum() and following[0] != ',':
            return True
        return False

    def cql_complete(self, text, partial, cassandra_conn=None, ignore_case=True, debug=False,
                     startsymbol='Start'):
        init_bindings = {'cassandra_conn': cassandra_conn}
        if debug:
            init_bindings['*DEBUG*'] = True
            print "cql_complete(%r, partial=%r)" % (text, partial)

        completions, hints = self.cql_complete_single(text, partial, init_bindings,
                                                      startsymbol=startsymbol)

        if hints:
            hints = [h.text for h in hints]
            hints.append('')

        if len(completions) == 1 and len(hints) == 0:
            c = completions[0]
            if debug:
                print "** Got one completion: %r. Checking for further matches...\n" % (c,)
            if not c.isspace():
                new_c = self.cql_complete_multiple(text, c, init_bindings, startsymbol=startsymbol)
                completions = [new_c]
            if debug:
                print "** New list of completions: %r" % (completions,)

        return hints + completions

    def cql_complete_multiple(self, text, first, init_bindings, startsymbol='Start'):
        debug = init_bindings.get('*DEBUG*', False)
        try:
            completions, hints = self.cql_complete_single(text + first, '', init_bindings,
                                                          startsymbol=startsymbol)
        except Exception:
            if debug:
                print "** completion expansion had a problem:"
                traceback.print_exc()
            return first
        if hints:
            if not first[-1].isspace():
                first += ' '
            if debug:
                print "** completion expansion found hints: %r" % (hints,)
            return first
        if len(completions) == 1 and completions[0] != '':
            if debug:
                print "** Got another completion: %r." % (completions[0],)
            if completions[0][0] in (',', ')', ':') and first[-1] == ' ':
                first = first[:-1]
            first += completions[0]
        else:
            common_prefix = util.find_common_prefix(completions)
            if common_prefix == '':
                return first
            if common_prefix[0] in (',', ')', ':') and first[-1] == ' ':
                first = first[:-1]
            if debug:
                print "** Got a partial completion: %r." % (common_prefix,)
            first += common_prefix
        if debug:
            print "** New total completion: %r. Checking for further matches...\n" % (first,)
        return self.cql_complete_multiple(text, first, init_bindings, startsymbol=startsymbol)

    @classmethod
    def cql_typename(cls, classname):
        fq_classname = 'org.apache.cassandra.db.marshal.'
        if classname.startswith(fq_classname):
            classname = classname[len(fq_classname):]
        try:
            return cls.apache_class_to_cql_type[classname]
        except KeyError:
            return cls.escape_value(classname)

    @classmethod
    def find_validator_class(cls, cqlname):
        return cls.cql_type_to_apache_class[cqlname]

    @classmethod
    def is_valid_cql_word(cls, s):
        return cls.valid_cql_word_re.match(s) is not None and s.lower() not in cls.keywords

    @staticmethod
    def cql_extract_orig(toklist, srcstr):
        # low end of span for first token, to high end of span for last token
        return srcstr[toklist[0][2][0]:toklist[-1][2][1]]

    @staticmethod
    def token_dequote(tok):
        if tok[0] == 'stringLiteral':
            # strip quotes
            return tok[1][1:-1].replace("''", "'")
        if tok[0] == 'unclosedString':
            # strip one quote
            return tok[1][1:].replace("''", "'")
        if tok[0] == 'unclosedComment':
            return ''
        return tok[1]

    @staticmethod
    def token_is_word(tok):
        return tok[0] == 'identifier'

    @classmethod
    def cql2_maybe_escape_name(cls, name):
        if cls.is_valid_cql_word(name):
            return name
        return cls.cql2_escape_name(name)

    # XXX: this doesn't really belong here.
    @classmethod
    def is_counter_col(cls, cfdef, colname):
        col_info = [cm for cm in cfdef.column_metadata if cm.name == colname]
        return bool(col_info and cls.cql_typename(col_info[0].validation_class) == 'counter')

    @staticmethod
    def cql2_dequote_value(cqlword):
        cqlword = cqlword.strip()
        if cqlword == '':
            return cqlword
        if cqlword[0] == "'":
            cqlword = cqlword[1:-1].replace("''", "'")
        return cqlword

    @staticmethod
    def cql2_escape_value(value):
        if value is None:
            return 'NULL' # this totally won't work
        if isinstance(value, bool):
            value = str(value).lower()
        elif isinstance(value, float):
            return '%f' % value
        elif isinstance(value, int):
            return str(value)
        return "'%s'" % value.replace("'", "''")

    # use _name for keyspace, cf, and column names, and _value otherwise.
    # also use the cql2_ prefix when dealing with cql2, or leave it off to
    # get whatever behavior is default for this CqlParsingRuleSet.
    cql2_dequote_name = dequote_name = dequote_value = cql2_dequote_value
    cql2_escape_name = escape_name = escape_value = cql2_escape_value
    maybe_escape_name = cql2_maybe_escape_name
    dequote_any = cql2_dequote_value

CqlRuleSet = CqlParsingRuleSet()

# convenience for remainder of module
shorthands = ('completer_for', 'explain_completion',
              'dequote_value', 'dequote_name',
              'escape_value', 'escape_name',
              'maybe_escape_name')

for shorthand in shorthands:
    globals()[shorthand] = getattr(CqlRuleSet, shorthand)

# BEGIN SYNTAX/COMPLETION RULE DEFINITIONS

syntax_rules = r'''
<Start> ::= <CQL_Statement>*
          ;

<CQL_Statement> ::= [statements]=<statementBody> ";"
                  ;

# the order of these terminal productions is significant:
<endline> ::= /\n/ ;

JUNK ::= /([ \t\r\f\v]+|(--|[/][/])[^\n\r]*([\n\r]|$)|[/][*].*?[*][/])/ ;

<stringLiteral> ::= /'([^']|'')*'/ ;
<float> ::=         /-?[0-9]+\.[0-9]+/ ;
<integer> ::=       /-?[0-9]+/ ;
<uuid> ::=          /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/ ;
<identifier> ::=    /[a-z][a-z0-9_]*/ ;
<colon> ::=         ":" ;
<star> ::=          "*" ;
<range> ::=         ".." ;
<endtoken> ::=      ";" ;
<op> ::=            /[-+=,().]/ ;
<cmp> ::=           /[<>]=?/ ;

<unclosedString>  ::= /'([^']|'')*/ ;
<unclosedComment> ::= /[/][*][^\n]*$/ ;

<symbol> ::= <star>
           | <range>
           | <op>
           | <cmp>
           ;
<name> ::= <identifier>
         | <stringLiteral>
         | <integer>
         ;
<term> ::= <stringLiteral>
         | <integer>
         | <float>
         | <uuid>
         ;
<colname> ::= <term>
            | <identifier>
            | nocomplete=<K_KEY>
            ;

<statementBody> ::= <useStatement>
                  | <selectStatement>
                  | <dataChangeStatement>
                  | <schemaChangeStatement>
                  ;

<dataChangeStatement> ::= <insertStatement>
                        | <updateStatement>
                        | <deleteStatement>
                        | <truncateStatement>
                        | <batchStatement>
                        ;

<schemaChangeStatement> ::= <createKeyspaceStatement>
                          | <createColumnFamilyStatement>
                          | <createIndexStatement>
                          | <dropKeyspaceStatement>
                          | <dropColumnFamilyStatement>
                          | <dropIndexStatement>
                          | <alterTableStatement>
                          ;

<consistencylevel> ::= cl=<identifier> ;

<storageType> ::= typename=( <identifier> | <stringLiteral> ) ;

<keyspaceName> ::= ksname=<name> ;

<columnFamilyName> ::= ( ksname=<name> "." )? cfname=<name> ;
'''

@completer_for('colname', 'nocomplete')
def nocomplete(ctxt, cass):
    return ()

@completer_for('consistencylevel', 'cl')
def cl_completer(ctxt, cass):
    return CqlRuleSet.consistency_levels

@completer_for('storageType', 'typename')
def storagetype_completer(ctxt, cass):
    return CqlRuleSet.cql_types

@completer_for('keyspaceName', 'ksname')
def ks_name_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_keyspace_names())

@completer_for('columnFamilyName', 'ksname')
def cf_ks_name_completer(ctxt, cass):
    return [maybe_escape_name(ks) + '.' for ks in cass.get_keyspace_names()]

@completer_for('columnFamilyName', 'cfname')
def cf_name_completer(ctxt, cass):
    ks = ctxt.get_binding('ksname', None)
    if ks is not None:
        ks = dequote_name(ks)
    try:
        cfnames = cass.get_columnfamily_names(ks)
    except Exception:
        if ks is None:
            return ()
        raise
    return map(maybe_escape_name, cfnames)

def get_cfdef(ctxt, cass):
    ks = ctxt.get_binding('ksname', None)
    cf = ctxt.get_binding('cfname')
    return cass.get_columnfamily(cf, ksname=ks)

syntax_rules += r'''
<useStatement> ::= "USE" ksname=<keyspaceName>
                 ;
<selectStatement> ::= "SELECT" <whatToSelect>
                        "FROM" cf=<columnFamilyName>
                          ("USING" "CONSISTENCY" selcl=<consistencylevel>)?
                          ("WHERE" <selectWhereClause>)?
                          ("LIMIT" <integer>)?
                    ;
<selectWhereClause> ::= <relation> ("AND" <relation>)*
                      | keyname=<colname> "IN" "(" <term> ("," <term>)* ")"
                      ;
<relation> ::= [rel_lhs]=<colname> ("=" | "<" | ">" | "<=" | ">=") <colname>
             ;
<whatToSelect> ::= colname=<colname> ("," colname=<colname>)*
                 | ("FIRST" <integer>)? "REVERSED"? (rangestart=<colname> ".." rangeend=<colname>
                                                     | "*")
                 | "COUNT" countparens="(" "*" ")"
                 ;
'''

@completer_for('selectStatement', 'selcl')
def select_statement_consistencylevel(ctxt, cass):
    return [cl for cl in CqlRuleSet.consistency_levels if cl != 'ANY']

@completer_for('selectWhereClause', 'keyname')
def select_where_keyname_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    return [cfdef.key_alias if cfdef.key_alias is not None else 'KEY']

@completer_for('relation', 'rel_lhs')
def select_relation_lhs_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    return map(maybe_escape_name, cass.filterable_column_names(cfdef))

@completer_for('whatToSelect', 'countparens')
def select_count_parens_completer(ctxt, cass):
    return ['(*)']

explain_completion('whatToSelect', 'colname')
explain_completion('whatToSelect', 'rangestart', '<range_start>')
explain_completion('whatToSelect', 'rangeend', '<range_end>')

syntax_rules += r'''
<insertStatement> ::= "INSERT" "INTO" cf=<columnFamilyName>
                               "(" keyname=<colname> ","
                                   [colname]=<colname> ( "," [colname]=<colname> )* ")"
                      "VALUES" "(" <term> "," <term> ( "," <term> )* ")"
                      ( "USING" [insertopt]=<usingOption>
                                ( "AND" [insertopt]=<usingOption> )* )?
                    ;
<usingOption> ::= "CONSISTENCY" <consistencylevel>
                | "TIMESTAMP" <integer>
                | "TTL" <integer>
                ;
'''

@completer_for('insertStatement', 'keyname')
def insert_keyname_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    return [cfdef.key_alias if cfdef.key_alias is not None else 'KEY']

explain_completion('insertStatement', 'colname')

@completer_for('insertStatement', 'insertopt')
def insert_option_completer(ctxt, cass):
    opts = set('CONSISTENCY TIMESTAMP TTL'.split())
    for opt in ctxt.get_binding('insertopt', ()):
        opts.discard(opt.split()[0])
    return opts

syntax_rules += r'''
<updateStatement> ::= "UPDATE" cf=<columnFamilyName>
                        ( "USING" [updateopt]=<usingOption>
                                  ( "AND" [updateopt]=<usingOption> )* )?
                        "SET" <assignment> ( "," <assignment> )*
                        "WHERE" <updateWhereClause>
                    ;
<assignment> ::= updatecol=<colname> "=" update_rhs=<colname>
                                         ( counterop=( "+" | "-"? ) <integer> )?
               ;
<updateWhereClause> ::= updatefiltercol=<colname> "=" <term>
                      | updatefilterkey=<colname> filter_in="IN" "(" <term> ( "," <term> )* ")"
                      ;
'''

@completer_for('updateStatement', 'updateopt')
def insert_option_completer(ctxt, cass):
    opts = set('CONSISTENCY TIMESTAMP TTL'.split())
    for opt in ctxt.get_binding('updateopt', ()):
        opts.discard(opt.split()[0])
    return opts

@completer_for('assignment', 'updatecol')
def update_col_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    colnames = map(maybe_escape_name, [cm.name for cm in cfdef.column_metadata])
    return colnames + [Hint('<colname>')]

@completer_for('assignment', 'update_rhs')
def update_countername_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    curcol = dequote_name(ctxt.get_binding('updatecol', ''))
    return [maybe_escape_name(curcol)] if CqlRuleSet.is_counter_col(cfdef, curcol) else [Hint('<term>')]

@completer_for('assignment', 'counterop')
def update_counterop_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    curcol = dequote_name(ctxt.get_binding('updatecol', ''))
    return ['+', '-'] if CqlRuleSet.is_counter_col(cfdef, curcol) else []

@completer_for('updateWhereClause', 'updatefiltercol')
def update_filtercol_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    return map(maybe_escape_name, cass.filterable_column_names(cfdef))

@completer_for('updateWhereClause', 'updatefilterkey')
def update_filterkey_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    return [cfdef.key_alias if cfdef.key_alias is not None else 'KEY']

@completer_for('updateWhereClause', 'filter_in')
def update_filter_in_completer(ctxt, cass):
    cfdef = get_cfdef(ctxt, cass)
    fk = ctxt.get_binding('updatefilterkey')
    return ['IN'] if fk in ('KEY', cfdef.key_alias) else []

syntax_rules += r'''
<deleteStatement> ::= "DELETE" ( [delcol]=<colname> ( "," [delcol]=<colname> )* )?
                        "FROM" cf=<columnFamilyName>
                        ( "USING" [delopt]=<deleteOption> ( "AND" [delopt]=<deleteOption> )* )?
                        "WHERE" <updateWhereClause>
                    ;
<deleteOption> ::= "CONSISTENCY" <consistencylevel>
                 | "TIMESTAMP" <integer>
                 ;
'''

@completer_for('deleteStatement', 'delopt')
def delete_opt_completer(ctxt, cass):
    opts = set('CONSISTENCY TIMESTAMP'.split())
    for opt in ctxt.get_binding('delopt', ()):
        opts.discard(opt.split()[0])
    return opts

explain_completion('deleteStatement', 'delcol', '<column_to_delete>')

syntax_rules += r'''
<batchStatement> ::= "BEGIN" "BATCH"
                        ( "USING" [batchopt]=<usingOption>
                                  ( "AND" [batchopt]=<usingOption> )* )?
                        [batchstmt]=<batchStatementMember> ";"
                            ( [batchstmt]=<batchStatementMember> ";" )*
                     "APPLY" "BATCH"
                   ;
<batchStatementMember> ::= <insertStatement>
                         | <updateStatement>
                         | <deleteStatement>
                         ;
'''

@completer_for('batchStatement', 'batchopt')
def batch_opt_completer(ctxt, cass):
    opts = set('CONSISTENCY TIMESTAMP'.split())
    for opt in ctxt.get_binding('batchopt', ()):
        opts.discard(opt.split()[0])
    return opts

syntax_rules += r'''
<truncateStatement> ::= "TRUNCATE" cf=<columnFamilyName>
                      ;
'''

syntax_rules += r'''
<createKeyspaceStatement> ::= "CREATE" "KEYSPACE" ksname=<name>
                                 "WITH" [optname]=<optionName> "=" [optval]=<optionVal>
                                 ( "AND" [optname]=<optionName> "=" [optval]=<optionVal> )*
                            ;
<optionName> ::= <identifier> ( ":" ( <identifier> | <integer> ) )?
               ;
<optionVal> ::= <stringLiteral>
              | <identifier>
              | <integer>
              ;
'''

explain_completion('createKeyspaceStatement', 'ksname', '<new_keyspace_name>')

@completer_for('createKeyspaceStatement', 'optname')
def create_ks_opt_completer(ctxt, cass):
    exist_opts = ctxt.get_binding('optname', ())
    try:
        stratopt = exist_opts.index('strategy_class')
    except ValueError:
        return ['strategy_class =']
    vals = ctxt.get_binding('optval')
    stratclass = dequote_value(vals[stratopt])
    if stratclass in ('SimpleStrategy',
                      'org.apache.cassandra.locator.SimpleStrategy',
                      'OldNetworkTopologyStrategy',
                      'org.apache.cassandra.locator.OldNetworkTopologyStrategy'):
        return ['strategy_options:replication_factor =']
    return [Hint('<strategy_option_name>')]

@completer_for('createKeyspaceStatement', 'optval')
def create_ks_optval_completer(ctxt, cass):
    exist_opts = ctxt.get_binding('optname', (None,))
    if exist_opts[-1] == 'strategy_class':
        return map(escape_value, CqlRuleSet.replication_strategies)
    return [Hint('<option_value>')]

syntax_rules += r'''
<createColumnFamilyStatement> ::= "CREATE" ( "COLUMNFAMILY" | "TABLE" ) cf=<name>
                                    "(" keyalias=<colname> <storageType> "PRIMARY" "KEY"
                                        ( "," colname=<colname> <storageType> )* ")"
                                   ( "WITH" [cfopt]=<cfOptionName> "=" [optval]=<cfOptionVal>
                                     ( "AND" [cfopt]=<cfOptionName> "=" [optval]=<cfOptionVal> )* )?
                                ;

<cfOptionName> ::= cfoptname=<identifier> ( cfoptsep=":" cfsubopt=( <identifier> | <integer> ) )?
                 ;

<cfOptionVal> ::= <identifier>
                | <stringLiteral>
                | <integer>
                | <float>
                ;
'''

explain_completion('createColumnFamilyStatement', 'keyalias', '<new_key_name>')
explain_completion('createColumnFamilyStatement', 'cf', '<new_table_name>')
explain_completion('createColumnFamilyStatement', 'colname', '<new_column_name>')

@completer_for('cfOptionName', 'cfoptname')
def create_cf_option_completer(ctxt, cass):
    return [c[0] for c in CqlRuleSet.columnfamily_options] + \
           [c[0] + ':' for c in CqlRuleSet.columnfamily_map_options]

@completer_for('cfOptionName', 'cfoptsep')
def create_cf_suboption_separator(ctxt, cass):
    opt = ctxt.get_binding('cfoptname')
    if any(opt == c[0] for c in CqlRuleSet.columnfamily_map_options):
        return [':']
    return ()

@completer_for('cfOptionName', 'cfsubopt')
def create_cf_suboption_completer(ctxt, cass):
    opt = ctxt.get_binding('cfoptname')
    if opt == 'compaction_strategy_options':
        # try to determine the strategy class in use
        prevopts = ctxt.get_binding('cfopt', ())
        prevvals = ctxt.get_binding('optval', ())
        for prevopt, prevval in zip(prevopts, prevvals):
            if prevopt == 'compaction_strategy_class':
                csc = dequote_value(prevval)
                break
        else:
            cf = ctxt.get_binding('cf')
            try:
                csc = cass.get_columnfamily(cf).compaction_strategy
            except Exception:
                csc = ''
        csc = csc.split('.')[-1]
        if csc == 'SizeTieredCompactionStrategy':
            return ['min_sstable_size']
        elif csc == 'LeveledCompactionStrategy':
            return ['sstable_size_in_mb']
    for optname, _, subopts in CqlRuleSet.columnfamily_map_options:
        if opt == optname:
            return subopts
    return ()

def create_cf_option_val_completer(ctxt, cass):
    exist_opts = ctxt.get_binding('cfopt')
    this_opt = exist_opts[-1]
    if this_opt == 'compression_parameters:sstable_compression':
        return map(escape_value, CqlRuleSet.available_compression_classes)
    if this_opt == 'compaction_strategy_class':
        return map(escape_value, CqlRuleSet.available_compaction_classes)
    if any(this_opt == opt[0] for opt in CqlRuleSet.obsolete_cf_options):
        return ["'<obsolete_option>'"]
    if this_opt in ('comparator', 'default_validation'):
        return CqlRuleSet.cql_types
    if this_opt == 'read_repair_chance':
        return [Hint('<float_between_0_and_1>')]
    if this_opt == 'replicate_on_write':
        return [Hint('<yes_or_no>')]
    if this_opt in ('min_compaction_threshold', 'max_compaction_threshold', 'gc_grace_seconds'):
        return [Hint('<integer>')]
    return [Hint('<option_value>')]

completer_for('createColumnFamilyStatement', 'optval') \
    (create_cf_option_val_completer)

syntax_rules += r'''
<createIndexStatement> ::= "CREATE" "INDEX" indexname=<identifier>? "ON"
                               cf=<name> "(" col=<colname> ")"
                         ;
'''

explain_completion('createIndexStatement', 'indexname', '<new_index_name>')

@completer_for('createIndexStatement', 'cf')
def create_index_cf_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_columnfamily_names())

@completer_for('createIndexStatement', 'col')
def create_index_col_completer(ctxt, cass):
    cfdef = cass.get_columnfamily(dequote_name(ctxt.get_binding('cf')))
    colnames = [md.name for md in cfdef.column_metadata if md.index_name is None]
    return map(maybe_escape_name, colnames)

syntax_rules += r'''
<dropKeyspaceStatement> ::= "DROP" "KEYSPACE" ksname=<keyspaceName>
                          ;
'''

@completer_for('dropKeyspaceStatement', 'ksname')
def drop_ks_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_keyspace_names())

syntax_rules += r'''
<dropColumnFamilyStatement> ::= "DROP" ( "COLUMNFAMILY" | "TABLE" ) cf=<name>
                              ;
'''

@completer_for('dropColumnFamilyStatement', 'cf')
def drop_cf_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_columnfamily_names())

syntax_rules += r'''
<dropIndexStatement> ::= "DROP" "INDEX" indexname=<name>
                       ;
'''

@completer_for('dropIndexStatement', 'indexname')
def drop_index_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_index_names())

syntax_rules += r'''
<alterTableStatement> ::= "ALTER" ( "COLUMNFAMILY" | "TABLE" ) cf=<name> <alterInstructions>
                        ;
<alterInstructions> ::= "ALTER" existcol=<name> "TYPE" <storageType>
                      | "ADD" newcol=<name> <storageType>
                      | "DROP" existcol=<name>
                      | "WITH" [cfopt]=<cfOptionName> "=" [optval]=<cfOptionVal>
                        ( "AND" [cfopt]=<cfOptionName> "=" [optval]=<cfOptionVal> )*
                      ;
'''

@completer_for('alterTableStatement', 'cf')
def alter_table_cf_completer(ctxt, cass):
    return map(maybe_escape_name, cass.get_columnfamily_names())

@completer_for('alterInstructions', 'existcol')
def alter_table_col_completer(ctxt, cass):
    cfdef = cass.get_columnfamily(dequote_name(ctxt.get_binding('cf')))
    cols = [md.name for md in cfdef.column_metadata]
    if cfdef.key_alias is not None:
        cols.append(cfdef.key_alias)
    return map(maybe_escape_name, cols)

explain_completion('alterInstructions', 'newcol', '<new_column_name>')

completer_for('alterInstructions', 'optval') \
    (create_cf_option_val_completer)

# END SYNTAX/COMPLETION RULE DEFINITIONS

CqlRuleSet.append_rules(syntax_rules)


text:
<?xml version="1.0" encoding="utf-8"?>
<!--Generated by crowdin.com-->
<resources>
  <string-array name="pref_volumeButtonNavigation_labels">
    <item>"Jangan gunakan"</item>
    <item>Berpindah ayat</item>
    <item>Berpindah pasal</item>
  </string-array>
</resources>

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="separator">#FF909090</color>
<color name="selected">#FFCC00</color>
<color name="white">#FFF</color>
</resources>


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Troubleshooting Deployments | Microsoft Orleans Documentation </title>
    <meta name="viewport" content="width=device-width">
    <meta name="title" content="Troubleshooting Deployments | Microsoft Orleans Documentation ">
    <meta name="generator" content="docfx 2">

    <link rel="shortcut icon" href="../../favicon.ico">
    <link rel="stylesheet" href="../../styles/docfx.vendor.css">
    <link rel="stylesheet" href="../../styles/docfx.css">
    <link rel="stylesheet" href="../../styles/main.css">
    <meta property="docfx:navrel" content="../../toc.html">
    <meta property="docfx:tocrel" content="../toc.html">

    <meta property="docfx:rel" content="../../">

              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbar">
                Toggle navigation

              </button>

              <form class="navbar-form navbar-right" role="search" id="search">

                  <input type="text" class="form-control" id="search-query" placeholder="Search" autocomplete="off">

              </form>

Search Results for

          Show / Hide Table of Contents

Troubleshooting Deployments

This page gives some general guidelines for troubleshooting any issues that occur while deploying to Azure Cloud Services.
These are very common issues to watch out for. Be sure to check the logs for more information.

Getting a SiloUnavailableException

First check to make sure that you are actually starting the silos before attempting to initialize the client. Sometimes the
silos take a long time to start so it can be beneficial to try to initialize the client multiple times. If it still throws an
exception, then there might be another issue with the silos.

Check the silo configuration and make sure that the silos are starting up properly.

Common Connection String Issues

Using the local connection string when deploying to Azure – the website will fail to connect

Using different connection strings for the silos and the front end (web and worker roles) – the website will fail to
initialize the client because it cannot connect to the silos

The connection string configuration can be checked in the Azure Portal. The logs may not display properly if the connection
strings are not set up correctly.

Modifying the Configuration Files Improperly

Make sure that the proper endpoints are configured in the ServiceDefinition.csdef file or else the deployment will not work.
It will give errors saying that it cannot get the endpoint information.

Missing Logs

Make sure that the connection strings are set up properly.

It is likely that the Web.config file in the web role or the app.config file in the worker role were modified improperly.
Incorrect versions in these files can cause issues with the deployment. Be careful when dealing with updates.

Version Issues

Make sure that the same version of Orleans is used in every project in the solution. Not doing this can lead to the worker
role recycling. Check the logs for more information. Visual Studio provides some silo startup error messages in the deployment history.

Role Keeps Recycling

Check that all the appropriate Orleans assemblies are in the solution and have Copy Local set to True.

Check the logs to see if there is an unhandled exception while initializing.

Make sure that the connection strings are correct.

Check the Azure Cloud Services troubleshooting pages for more information.

How to Check Logs

Use the cloud explorer in Visual Studio to navigate to the appropriate storage table or blob in the storage account. The WADLogsTable is a good starting point for looking at the logs.

You might only be logging errors. If you want informational logs as well, you will need to modify the configuration to set the logging severity level.

Programmatic configuration:

When creating a ClusterConfiguration object, set config.Defaults.DefaultTraceLevel = Severity.Info.

When creating a ClientConfiguration object, set config.DefaultTraceLevel = Severity.Info.

Declarative configuration:

Add <Tracing DefaultTraceLevel="Info" /> to the OrleansConfiguration.xml and/or the ClientConfiguration.xml files.

In the diagnostics.wadcfgx file for the web and worker roles, make sure to set the scheduledTransferLogLevelFilter attribute in the Logs element to Information, as this is an additional layer of trace filtering that defines which traces are sent to the WADLogsTable in Azure Storage.

You can find more information about this in the Configuration Guide.

Compatibility with ASP.NET

The razor view engine included in ASP.NET uses the same code generation assemblies as Orleans (Microsoft.CodeAnalysis and Microsoft.CodeAnalysis.CSharp). This can present a version compatibility problem at runtime.

To resolve this, try upgrading Microsoft.CodeDom.Providers.DotNetCompilerPlatform (this is the NuGet package ASP.NET uses to include the above assemblies) to the latest version, and setting binding redirects like this:

<dependentAssembly>
  <assemblyIdentity name="Microsoft.CodeAnalysis.CSharp" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="1.3.1.0" />
</dependentAssembly>
<dependentAssembly>
  <assemblyIdentity name="Microsoft.CodeAnalysis" publicKeyToken="31bf3856ad364e35" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="1.3.1.0" />
</dependentAssembly>

                    Improve this Doc

In This Article

              Back to top

            Generated by DocFX


text:
package com.nagopy.android.xposed.utilities;

import android.content.Context;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;

import com.nagopy.android.xposed.utilities.XposedModules.InitZygote;
import com.nagopy.android.xposed.utilities.XposedModules.XMinSdkVersion;
import com.nagopy.android.xposed.utilities.XposedModules.XposedModule;
import com.nagopy.android.xposed.utilities.setting.ModActionBarSettingsGen;

import de.robv.android.xposed.IXposedHookZygoteInit.StartupParam;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedHelpers;

/**
 * アクションバーを下に移動するモジュール.
 */
@XposedModule(setting = ModActionBarSettingsGen.class)
@XMinSdkVersion(Build.VERSION_CODES.KITKAT)
public class ModActionBar {

    @InitZygote
    public static void initZygote(StartupParam startupParam,
            final ModActionBarSettingsGen mSettings) throws Throwable {
        if (!mSettings.actionBarBottomEnable) {
            return;
        }

        // for KitKat
        // アクションバーを下に表示
        Class<?> clsActionBarOverlayLayout = XposedHelpers.findClass(
                "com.android.internal.widget.ActionBarOverlayLayout", null);
        XposedHelpers.findAndHookMethod(clsActionBarOverlayLayout, "onLayout", boolean.class,
                int.class, int.class, int.class, int.class,
                new XC_MethodHook() {
                    @Override
                    protected void afterHookedMethod(MethodHookParam param) throws Throwable {
                        Context context = (Context) XposedHelpers.callMethod(param.thisObject,
                                "getContext");
                        String packageName = context.getPackageName();

                        if (!mSettings.actionBarBottomPackages.contains(packageName)) {
                            // 対象に含まれない場合、何もしない
                            return;
                        }

                        // ActionBarのViewを取得
                        int action_bar_container = context.getResources().getIdentifier(
                                "action_bar_container", "id", "android");
                        View actionBar = (View) XposedHelpers.callMethod(param.thisObject,
                                "findViewById", action_bar_container);
                        // アクションバーの高さをとっておく
                        final int actionBarHeight = actionBar.getMeasuredHeight();

                        // 下のアクションバーを取っとく
                        int split_action_bar = context.getResources().getIdentifier(
                                "split_action_bar", "id", "android");

                        // パラメータの値を取得
                        int left = (Integer) param.args[1];
                        int top = (Integer) param.args[2];
                        int right = (Integer) param.args[3];
                        int bottom = (Integer) param.args[4];

                        final int parentLeft = (Integer) XposedHelpers.callMethod(
                                param.thisObject,
                                "getPaddingLeft");
                        @SuppressWarnings("unused")
                        final int parentRight = right - left
                                - (Integer) XposedHelpers.callMethod(param.thisObject,
                                        "getPaddingRight");

                        final int parentTop = (Integer) XposedHelpers.callMethod(
                                param.thisObject,
                                "getPaddingTop");
                        final int parentBottom = bottom - top
                                - (Integer) XposedHelpers.callMethod(param.thisObject,
                                        "getPaddingBottom");

                        int count = (Integer) XposedHelpers.callMethod(param.thisObject,
                                "getChildCount");
                        for (int i = 0; i < count; i++) {
                            final View child = (View) XposedHelpers.callMethod(
                                    param.thisObject,
                                    "getChildAt", i);
                            if (child.getVisibility() != View.GONE) {
                                final MarginLayoutParams marginLayoutParams = (MarginLayoutParams) child
                                        .getLayoutParams();

                                final int w = child.getMeasuredWidth();
                                final int h = child.getMeasuredHeight();

                                int childLeft = parentLeft + marginLayoutParams.leftMargin;
                                int childTop;
                                if (child.getId() == split_action_bar) {
                                    // もともと下のアクションバーの場合
                                    childTop = parentBottom - h
                                            - marginLayoutParams.bottomMargin;
                                    childTop -= actionBarHeight;
                                } else if (child.getId() == action_bar_container) {
                                    // アクションバーの場合
                                    childTop = parentBottom - h
                                            - marginLayoutParams.bottomMargin;
                                } else if (child.getId() == android.R.id.content) {
                                    // メインのViewの場合
                                    childTop = parentTop + marginLayoutParams.topMargin
                                            - actionBarHeight;
                                } else {
                                    // それ以外
                                    childTop = parentTop + marginLayoutParams.topMargin;
                                }

                                child.layout(childLeft, childTop, childLeft + w, childTop
                                        + h);
                            }
                        }
                    }
                });
    }

}


text:
import logging
log = logging.getLogger(__name__)

import botologist.plugin

class Client:
	def __init__(self, name):
		self.name = name
		self.channels = {}

		self.error_handler = None
		self.on_connect = []
		self.on_disconnect = []
		self.on_join = []
		self.on_privmsg = []
		self.on_kick = []

	@property
	def nick(self):
		return self.name

	def add_channel(self, channel):
		self.channels[channel.name] = channel

	def _parse_messages(self, message):
		if isinstance(message, bytes):
			message = message.decode('utf-8')
		if isinstance(message, str):
			message = message.split('\n')
		return message

	def send_msg(self, target, message):
		raise NotImplementedError('method send_msg must be defined')

	def run_forever(self):
		raise NotImplementedError('method run_forever must be defined')

	def stop(self):
		for callback in self.on_disconnect:
			callback()

	def _wrap_error_handler(self, func):
		if self.error_handler:
			return self.error_handler.wrap(func)
		return func

class Channel:
	def __init__(self, name):
		self.name = name
		self.users = []

		self.commands = {}
		self.joins = []
		self.kicks = []
		self.replies = []
		self.tickers = []
		self.admins = []
		self.http_handlers = []
		self.plugins = []

	@property
	def channel(self):
		log.warning('Channel.channel is deprecated! use Channel.name instead')
		return self.name

	def register_plugin(self, plugin):
		assert isinstance(plugin, botologist.plugin.Plugin)
		self.plugins.append(plugin.__class__.__name__)
		for cmd, callback in plugin.commands.items():
			self.commands[cmd] = callback
		for join_callback in plugin.joins:
			self.joins.append(join_callback)
		for kick_callback in plugin.kicks:
			self.kicks.append(kick_callback)
		for reply_callback in plugin.replies:
			self.replies.append(reply_callback)
		for tick_callback in plugin.tickers:
			self.tickers.append(tick_callback)
		for http_handler in plugin.http_handlers:
			self.http_handlers.append(http_handler)

	def add_user(self, user):
		assert isinstance(user, User)
		if self.find_user(user=user):
			log.info('user %r already present in channel, not adding', user)
			return
		self.users.append(user)

	def find_user(self, **kwargs):
		users = self.find_users(**kwargs)
		if len(users) > 1:
			log.warning('more than 1 user matched criteria %r in channel %s',
				kwargs, self.name)
		return users[0] if users else None

	def find_users(self, user=None, name=None, identifier=None):
		assert user or name or identifier

		if user:
			identifier = user.identifier
			name = user.name

		return self._find_users(name, identifier)

	def _find_users(self, name, identifier):
		users = []

		if identifier and name:
			for user in self.users:
				if user.identifier == identifier and user.name == name:
					users.append(user)
			return users

		for user in self.users:
			if identifier and user.identifier == identifier:
				log.debug('user %r matches identifier %r', user, identifier)
				users.append(user)
			elif name and user.name == name:
				log.debug('user %r matches name %r', user, name)
				users.append(user)

		return users

	def remove_user(self, user=None, name=None, identifier=None):
		assert user or name or identifier

		users = self.find_users(user, name, identifier)
		for user in users:
			log.debug('removing user %r from %s', user, self.name)
			self.users.remove(user)

class User:
	def __init__(self, name, identifier):
		self.name = name
		self.identifier = identifier

	@property
	def nick(self):
		return self.name

	def __eq__(self, other):
		if not isinstance(other, self.__class__):
			return False
		if self.name and other.name:
			return other.name == self.name and other.identifier == self.identifier
		return other.identifier == self.identifier

class Message:
	def __init__(self, body, user, target):
		self.body = body
		self.words = body.strip().split()
		assert isinstance(user, User)
		self.user = user
		self.target = target
		self.channel = None
		self.is_private = False

	@property
	def message(self):
		return self.body


text:
<?xml version = '1.0' encoding = 'UTF-8'?>
<Table class="oracle.dbtools.crest.model.design.relational.Table" directorySegmentName="seg_0" id="F539E6B8-85B8-5A07-F853-40FC5C135C7A" schemaObject="066420E9-A71D-E368-8AD4-4AC7A4F6E26E" name="INMUEBLE">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMOBILIARIA</sourceObjSchema>
<sourceObjName>INMUEBLE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<allowColumnReorder>false</allowColumnReorder>
<existDependencyGenerateInDDl>true</existDependencyGenerateInDDl>
<parsed>true</parsed>
<columns itemClass="oracle.dbtools.crest.model.design.relational.Column">
<Column name="INMUEBLE_ID" id="5BDBCC67-054A-83CD-465A-2F27DBF2A2EA">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_ID</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,8,0</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="INMUEBLE_ADDRESS" id="FB089AC4-FECE-BEC8-A610-A2A8A3F92FAF">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_ADDRESS</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
<associations>
<colAssociation fkAssociation="2834EE40-3B35-E73F-7333-39160EF049B8" referredColumn="3C6B8289-6BD9-81C0-15FD-A8C7C9091B62"/>
</associations>
</Column>
<Column name="INMUEBLE_TYPE" id="46B21433-86C5-F4E6-5349-B33FAA0C3908">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_TYPE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
<associations>
<colAssociation fkAssociation="AE8F5BA9-7A8F-EDE5-4C75-6617D6D1B50A" referredColumn="7A99A74E-D21C-7440-FFFC-D322AD36B8D8"/>
</associations>
</Column>
<Column name="NO_ROOMS" id="68568F85-830B-B52B-E370-52CD351BBACF">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>NO_ROOMS</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>2</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,2,0</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="PRICE" id="117A0049-B0D5-D7D2-2F1A-2CA915457731">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>PRICE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>2</dataTypeScale>
<ownDataTypeParameters>,8,2</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="REGISTER_DATE" id="2174E36E-5555-4DA1-33BD-6B3AC845D346">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>REGISTER_DATE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT007</logicalDatatype>
<dataTypeSize>7</dataTypeSize>
<defaultValue>SYSDATE</defaultValue>
<ownDataTypeParameters>7,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
</Column>
<Column name="INMUEBLE_OFFICE" id="BCB5FD88-0881-9A5D-CEA9-C0D0AA855464">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_OFFICE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
<associations>
<colAssociation fkAssociation="671B7A83-BD51-9B1E-FA6C-9D7012F17DAC" referredColumn="B95C4C14-2A72-9D57-00E0-F2BA4BE8801D"/>
</associations>
</Column>
<Column name="INMUEBLE_PROPRIETOR" id="5E75A876-C4F3-9D8A-D6A3-5ED43114C26F">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_PROPRIETOR</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,8,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
<associations>
<colAssociation fkAssociation="2228522E-2FE7-5322-A3D9-238F90F96BF6" referredColumn="63CE7E9E-5450-B4C1-43AB-65A5E64AAD02"/>
</associations>
</Column>
<Column name="INMUEBLE_EMPLOYEE" id="042626D5-9845-0842-BCC2-BB83EDBBFD7F">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMUEBLE</sourceObjSchema>
<sourceObjName>INMUEBLE_EMPLOYEE</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<useDomainConstraints>false</useDomainConstraints>
<use>1</use>
<logicalDatatype>LOGDT019</logicalDatatype>
<dataTypePrecision>8</dataTypePrecision>
<dataTypeScale>0</dataTypeScale>
<ownDataTypeParameters>,,</ownDataTypeParameters>
<autoIncrementCycle>false</autoIncrementCycle>
<associations>
<colAssociation fkAssociation="C636321E-3246-745B-E4F7-099B0A81DED4" referredColumn="3201BF3F-538F-EF47-6388-28E599A7961E"/>
</associations>
</Column>
</columns>
<indexes itemClass="oracle.dbtools.crest.model.design.relational.Index">
<ind_PK_UK id="FAC2A189-0A14-68DA-62C2-A5078B4BDD80" schemaObject="066420E9-A71D-E368-8AD4-4AC7A4F6E26E" name="INMUEBLE_PK">
<sourceConnName>InmobiliariaBD</sourceConnName>
<sourceObjSchema>INMOBILIARIA</sourceObjSchema>
<sourceObjName>SYS_C007473</sourceObjName>
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<pk>true</pk>
<indexState>Primary Constraint</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="5BDBCC67-054A-83CD-465A-2F27DBF2A2EA"/>
</indexColumnUsage>
</ind_PK_UK>
<ind_PK_UK id="7EC78E4A-7518-ACFF-D7CF-99DE771EDEEA" name="INMUEBLE_EMPLOYEE_FK">
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<indexState>Foreign Key</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="042626D5-9845-0842-BCC2-BB83EDBBFD7F"/>
</indexColumnUsage>
</ind_PK_UK>
<ind_PK_UK id="A5C76DFA-FC8E-4923-1E5A-13F0EFC29026" name="INMUEBLE_PROPRIETOR_FK">
<createdBy>ley</createdBy>
<createdTime>2016-07-20 16:14:43 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<indexState>Foreign Key</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="5E75A876-C4F3-9D8A-D6A3-5ED43114C26F"/>
</indexColumnUsage>
</ind_PK_UK>
<ind_PK_UK id="9DE1FDED-BD19-AC16-7D90-8D2C649CE776" name="INMUEBLE_TYPE_FK">
<createdBy>ley</createdBy>
<createdTime>2016-07-20 18:07:36 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<indexState>Foreign Key</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="46B21433-86C5-F4E6-5349-B33FAA0C3908"/>
</indexColumnUsage>
</ind_PK_UK>
<ind_PK_UK id="5D992550-904D-EDD9-00BE-EFB0F445C8A9" name="INMUEBLE_ADDRESS_FK">
<createdBy>ley</createdBy>
<createdTime>2016-07-20 19:00:15 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<indexState>Foreign Key</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="FB089AC4-FECE-BEC8-A610-A2A8A3F92FAF"/>
</indexColumnUsage>
</ind_PK_UK>
<ind_PK_UK id="CE7F6F7B-D0CE-0B72-EEB8-5B8618C779C1" name="INMUEBLE_OFFICE_FK">
<createdBy>ley</createdBy>
<createdTime>2016-07-20 19:08:44 UTC</createdTime>
<ownerDesignName>InmobiliariaBD_DDL</ownerDesignName>
<indexState>Foreign Key</indexState>
<isSurrogateKey>false</isSurrogateKey>
<indexColumnUsage>
<colUsage columnID="BCB5FD88-0881-9A5D-CEA9-C0D0AA855464"/>
</indexColumnUsage>
</ind_PK_UK>
</indexes>
</Table>


text:
package mcjty.xnet.api.net;

import mcjty.xnet.api.keys.ConsumerId;
import mcjty.xnet.api.keys.NetworkId;
import net.minecraft.util.math.BlockPos;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Set;

/**
 * This represents the network connectivity for a given dimension. There is one IWorldBlob for
 * every dimension (that holds XNet devices). You can get a reference to the world blob
 * by calling IXnet.getWorldBlob()
 */
public interface IWorldBlob {

    /**
     * Call this to let the controller/router recalculate its internal caches in case
     * an update to a network was done. Normally XNet does this automatically but you may
     * want to call this if you have your own IConsumerProvider
     */
    void markNetworkDirty(NetworkId id);

    /**
     * Get the network ids that are valid for a given location in the world. Returns
     * an empty set if there is no network there. Note that a router can have multiple
     * networks but controllers, cables and connectors only have one
     */
    @Nonnull
    Set<NetworkId> getNetworksAt(@Nonnull BlockPos pos);

    /**
     * Find the position of the network provider (the controller or router).
     * If it is a controller you can access it by casting the tile entity
     * to IControllerContext.
     */
    @Nullable
    BlockPos getProviderPosition(@Nonnull NetworkId networkId);

    /**
     * Get all consumers (connectors) on a given network
     */
    @Nonnull
    Set<BlockPos> getConsumers(NetworkId network);

    /**
     * Get the position of a consumer
     */
    @Nullable
    BlockPos getConsumerPosition(@Nonnull ConsumerId consumer);

    /**
     * Get the consumer ID for a given position. A consumer basically corresponds
     * with a connector
     */
    @Nullable
    ConsumerId getConsumerAt(@Nonnull BlockPos pos);

}


text:
TConsoleKeys ConKeys(30); //Instance of ConsoleKeys Class Repeat set to 30 cycles
TMouse GMouse;    //Instance of the Global Mouse Handler
TMouse  EdMouse;          //!< Instance of  mouse class for the editor
TClock EngineTime;       //!< Instance of Global Time Handle

UpdatesManager::UpdatesManager()
{
	FindFreq();

}
/////////////////////////////////////////////////////////////////

void UpdatesManager::FindFreq()
{
	QueryPerformanceFrequency(&frequency);

}
////////////////////////////////////////////////////////////////

 bool UpdatesManager::UpdateStates()
{

	//Console Input - All Other Keyboard\\
	input should go inside the if statement for input
	ConKeys.HandleKeyEvent();

	double stoptime = 0.001; //Used to help keep frame rates persistant

	//Make old time the old delta time
	OldTime = deltaTime;

	//Get the start tick count
	QueryPerformanceCounter(&startcount);

	do //This do loop helps keep our frame rates persistant without limiting frame rate
	{
		//Base our updates for input on the rate of the updates.

			float s = 0;

			if(framespersec>59)
			{
				s = 1/60;
			}
			else
			{
				s = 1/30;
			}

			//NewTime is the total accumulator for  ticks passed
			//if enough time has passed, process input.
		if(EngineTime.CalcTimePassed() >= s)
		{

				//Handle Key Board input(Except for the console)

					//update the mouse position
					GMouse.UpdateMouse();
					NewTime = 0;

		}

			//Update our realtime timer for logic updates, unless the console\\
			is active, or the MainState is paused, effectively pausing logic updates.

			if(GetPause())
			{
				//Don't update the Logic timers.
			}
			else
			{
				EngineTime.UpdateTimer();
			}

			//DO Drawing

			if(!UpdateRender())
			{
				return false;
			}

			//Get the stop time for the end of the frame
			QueryPerformanceCounter(&endcount);

			//Get the difference of time from the start to the end
			deltaTime =  (double)(endcount.QuadPart - startcount.QuadPart)/(double)frequency.QuadPart;
	}

	while(deltaTime < stoptime);

	NewTime += OldTime;
	framespersec = 1.0f / deltaTime;

	//Set the key repeat speed based on frame rate
	ConKeys.repeatspeed = framespersec * 0.575;

	return true;
}
///////////////////////////////////////////////////////////////

UpdatesManager::~UpdatesManager()
{
}

///////////////////////////////////////////////////////////////

bool UpdatesManager::UpdateRender()
{

		if(!TrogWin.DrawGLScene())
		{
			return false;
		}

		SwapBuffers(TrogWin.hDC);			// Swap Buffers (Double Buffering)

	return true;
}

////////////////////////////////////////////////////////////////
void UpdatesManager::SetPause(bool arg)
{
     pausestate = arg;

}

bool UpdatesManager::GetPause()
{
	return pausestate;
}

////////////////////////////////////////////////////////////////

float UpdatesManager::GetNewTime()
{
	return NewTime;
}

/////////////////////////////////////////////////////////

float UpdatesManager::SetNewTime(float arg)
{

	return NewTime = arg;
}


text:
YUI.add('moodle-core_message-toolbox', function (Y, NAME) {

// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.

var CSS = {
    ACCESSHIDE: 'accesshide',
    MESSAGEACTIVE: 'messageactive'
};
var SELECTORS = {
    DELETEICON: '.deleteicon',
    MESSAGEACTIVE: '.messageactive',
    MESSAGEHISTORY: '.messagehistory',
    MESSAGES: '.messagecontent'
};

M.core_message = M.core_message || {};
M.core_message.toolbox = M.core_message.toolbox || {};

/**
 * This class contains the JS related to deleting messages.
 *
 * @class M.core_message.toolbox.deletemsg
 * @constructor
 */
M.core_message.toolbox.deletemsg = {

    /**
     * The area the messages are contained.
     *
     * @property messagearea
     */
    messagearea: null,

    /**
     * Initializer.
     *
     * Sets up event listeners which 'activate' and 'deactivate' a message.
     *
     * @method init
     */
    init: function() {
        this.messagearea = Y.one(SELECTORS.MESSAGEHISTORY);

        // Set the events.
        this.messagearea.delegate('hover', this.over, this.out, SELECTORS.MESSAGES);
        this.messagearea.delegate('click', this.click, SELECTORS.MESSAGES, this);
    },

    /**
     * Handles when a mouse hovers over a message.
     *
     * @private
     * @params {EventFacade} e
     * @method over
     */
    over: function(e) {
        // 'Activate' the message area we hovered on.
        e.currentTarget.addClass(CSS.MESSAGEACTIVE);
        e.currentTarget.one(SELECTORS.DELETEICON).removeClass(CSS.ACCESSHIDE);
    },

    /**
     * Handles when a mouse hovers off a message.
     *
     * @private
     * @params {EventFacade} e
     * @method out
     */
    out: function(e) {
        // 'Deactivate' the message area we hovered off.
        e.currentTarget.removeClass(CSS.MESSAGEACTIVE);
        e.currentTarget.one(SELECTORS.DELETEICON).addClass(CSS.ACCESSHIDE);
    },

    /**
     * Handles when a mouse clicks on a message.
     *
     * @private
     * @params {EventFacade} e
     * @method click
     */
    click: function(e) {
        // 'Deactivate' the currently active message (if there is one).
        var activemessage = this.messagearea.one(SELECTORS.MESSAGEACTIVE);
        if (activemessage) {
            activemessage.removeClass(CSS.MESSAGEACTIVE);
            activemessage.one(SELECTORS.DELETEICON).addClass(CSS.ACCESSHIDE);
        }
        // 'Activate' the message area we clicked on.
        e.currentTarget.addClass(CSS.MESSAGEACTIVE);
        e.currentTarget.one(SELECTORS.DELETEICON).removeClass(CSS.ACCESSHIDE);
    }
};

}, '@VERSION@');


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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <context:annotation-config/>
    <!--启用aop代理-->
    <aop:aspectj-autoproxy proxy-target-class="true"/>

    <!-- 扫描annotation类,过滤Service,Repository -->
    <context:component-scan base-package="com.neko">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/>
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/>
    </context:component-scan>

    <!-- 加载数据库属性配置文件 -->
    <context:property-placeholder location="classpath:datasource/jdbc.properties,classpath:redis/redis.properties"/>

    <!-- 配置数据库连接池(c3p0) -->
    <!--<bean id="parentDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!-- 配置主数据源(写库) -->
    <bean id="writeDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${neko.write.url}"/>
        <property name="username" value="${neko.write.username}"/>
        <property name="password" value="${neko.write.password}"/>
        <property name="driverClassName" value="${write.driverClassName}"/>
        <property name="filters" value="${write.filters}"/>
        <property name="defaultAutoCommit" value="${write.defaultAutoCommit}"/>
        <property name="maxActive" value="${write.maxActive}"/>
        <property name="initialSize" value="${write.initialSize}"/>
        <property name="maxWait" value="${write.maxWait}"/>
        <property name="minIdle" value="${write.minIdle}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${write.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${write.minEvictableIdleTimeMillis}"/>
        <property name="validationQuery" value="${write.validationQuery}"/>
        <property name="testWhileIdle" value="${write.testWhileIdle}"/>
        <property name="testOnBorrow" value="${write.testOnBorrow}"/>
        <property name="testOnReturn" value="${write.testOnReturn}"/>
        <!--
        <property name="maxOpenPreparedStatements" value="${write.maxOpenPreparedStatements}" />
        -->
        <property name="removeAbandoned" value="${write.removeAbandoned}"/> <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandonedTimeout" value="${write.removeAbandonedTimeout}"/> <!-- 1800秒,也就是30分钟 -->
        <property name="logAbandoned" value="${write.logAbandoned}"/> <!-- 关闭abanded连接时输出错误日志 -->
    </bean>
    <!-- 配置从数据源(读库) -->
    <bean id="readDataSource1" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="url" value="${neko.read.url}"/>
        <property name="username" value="${neko.read.username}"/>
        <property name="password" value="${neko.read.password}"/>
        <property name="driverClassName" value="${read.driverClassName}"/>
        <property name="filters" value="${read.filters}"/>
        <property name="defaultAutoCommit" value="${read.defaultAutoCommit}"/>
        <property name="maxActive" value="${read.maxActive}"/>
        <property name="initialSize" value="${read.initialSize}"/>
        <property name="maxWait" value="${read.maxWait}"/>
        <property name="minIdle" value="${read.minIdle}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${read.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${read.minEvictableIdleTimeMillis}"/>
        <property name="validationQuery" value="${read.validationQuery}"/>
        <property name="testWhileIdle" value="${read.testWhileIdle}"/>
        <property name="testOnBorrow" value="${read.testOnBorrow}"/>
        <property name="testOnReturn" value="${read.testOnReturn}"/>
        <!--
        <property name="maxOpenPreparedStatements" value="${read.maxOpenPreparedStatements}" />
        -->
        <property name="removeAbandoned" value="${read.removeAbandoned}"/> <!-- 打开removeAbandoned功能 -->
        <property name="removeAbandonedTimeout" value="${read.removeAbandonedTimeout}"/> <!-- 1800秒,也就是30分钟 -->
        <property name="logAbandoned" value="${read.logAbandoned}"/> <!-- 关闭abanded连接时输出错误日志 -->
    </bean>

    <bean id="readWriteDataSource" class="com.neko.dao.common.datasource.ReadWriteDataSource">
        <property name="writeDataSource" ref="writeDataSource"/>
        <property name="readDataSourceMap">
            <map>
                <entry key="readDataSource1" value-ref="readDataSource1"/>
                <entry key="readDataSource2" value-ref="readDataSource1"/>
                <entry key="readDataSource3" value-ref="readDataSource1"/>
                <entry key="readDataSource4" value-ref="readDataSource1"/>
            </map>
        </property>
    </bean>
    <!-- MapperScanner配置.自动去搜索mapper里的对象,并注入.  -->
    <!-- 注意,没有必要去指定SqlSessionFactory或SqlSessionTemplate,
    因为MapperScannerConfigurer将会创建 MapperFactoryBean,之后自动装配。
    但是,如果你使 用了一个以上的DataSource,那 么自动装配可能会失效。
    这种情况下,你可以使用 sqlSessionFactoryBeanName或sqlSessionTemplateBeanName
    属性来设置正确的 bean名称来使用。 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.neko.dao.mapper,com.neko.dao.mapping"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="readWriteDataSource"/>
        <property name="configLocation" value="classpath:datasource/sqlMapConfig.xml"/>
        <property name="mapperLocations" value="classpath*:com/neko/dao/mapping/*.xml"/>
    </bean>

    <!-- 配置读写分离 -->
    <bean id="readWriteDataSourceTransactionProcessor"
          class="com.neko.dao.common.datasource.ReadWriteDataSourceProcessor">
        <property name="forceChoiceReadWhenWrite" value="true"/>
    </bean>

    <!-- 配置事务分离切面 -->
    <aop:config expose-proxy="true">
        <!-- 只对业务逻辑层实施事务  * com.ssjk.service.*.*(..)-->
        <aop:pointcut id="txPointcut" expression="execution(* com.neko.service.*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
        <aop:aspect order="-2147483648" ref="readWriteDataSourceTransactionProcessor">
            <aop:around pointcut-ref="txPointcut" method="determineReadOrWriteDB"/>
        </aop:aspect>
    </aop:config>

    <!-- 使用annotation定义事务 (使用注解定义事务) -->
    <!-- 使用JDBC事物 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="readWriteDataSource"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="readWriteDataSource"/>
    </bean>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="create*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="merge*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="put*" read-only="true"/>
            <tx:method name="query*" read-only="true"/>
            <tx:method name="use*" read-only="true"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="count*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="list*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!--<!– 该 BeanPostProcessor 将自动起作用,对标注 @Autowired 的 Bean 进行自动注入 –>-->
    <!--<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>-->
    <!--<bean id="propertyConfigurer" class="com.ssjk.website.util.PropertyPlaceholder">-->
    <!--<property name="locations">-->
    <!--<list>-->
    <!--<value>classpath:httpClient.properties</value>-->
    <!--</list>-->
    <!--</property>-->
    <!--</bean>-->
    <import resource="spring-redis.xml"/>
</beans>


text:
<% if (appDescription.length > 0) { %>
<%= appDescription %>
<% } %>

<% if (appAuthor.length > 0) { %>
This project was created by <%= appAuthor %> <% if (appEmail.length > 0) { %>(<%= appEmail %>)<% } %>
<% } %>

## Version
<%= appVersion %>

## License
<%= appLicense %>


text:
"""This module contains unit tests for the ```privacy``` module."""

import os
import unittest
import uuid

from .. import util

class TestFileToDataUriScheme(unittest.TestCase):

    def test_none_filename(self):
        self.assertIsNone(util.file_to_data_uri_scheme(None))

    def test_empty_filename(self):
        self.assertIsNone(util.file_to_data_uri_scheme(''))

    def test_filename_does_not_exist(self):
        self.assertIsNone(util.file_to_data_uri_scheme(uuid.uuid4().hex))

    def test_zero_byte_file(self):
        filename = os.path.join(
            os.path.dirname(__file__),
            'data',
            'empty.txt')
        self.assertIsNone(util.file_to_data_uri_scheme(filename))

    def test_png(self):
        filename = os.path.join(
            os.path.dirname(__file__),
            'data',
            'screenshot.png')
        self.assertTrue(util.file_to_data_uri_scheme(filename).startswith('data:image/png;base64,'))

    def test_pdf(self):
        filename = os.path.join(
            os.path.dirname(__file__),
            'data',
            'python-magic-pypi.pdf')
        self.assertTrue(util.file_to_data_uri_scheme(filename).startswith('data:application/pdf;base64,'))

    def test_json(self):
        filename = os.path.join(
            os.path.dirname(__file__),
            'data',
            'crawl-output.json')
        self.assertTrue(util.file_to_data_uri_scheme(filename).startswith('data:application/json;base64,'))

    def test_txt(self):
        filename = os.path.join(
            os.path.dirname(__file__),
            'data',
            'chrome-driver-log.txt')
        self.assertTrue(util.file_to_data_uri_scheme(filename).startswith('data:text/plain;base64,'))


text:
tmpjob=$(mktemp -p .)
chmod +x $tmpjob
echo "command to execute:"
# $@ input is base64 encoded string of command to execute
eval $@

echo "$@" "|bash" > $tmpjob
bash $tmpjob
res=$?
rm $tmpjob

if [ $res != 0 ]; then
    echo "[Error] Execution failed with error code: $res"
    exit $res
fi


text:
/**
 * Key Difference by banned keys.
 * ```
 *    module.exports(['stuff.boost', 'stuff.score'], {name : 'ron swanson',  stuff : { boost : 1, score : 2, hits: 10}, age : 32});
 *    // expected output should be
 *    ["name", "stuff.hits", "age"]
 * ```
 * @type {*|exports|module.exports}
 */

var addressObjectKeys = require('../helpers/addressObjectKeys');

module.exports = function keyDifference (keys, object, stop_if_key_exists, void_function) {
    var allKeys;

    stop_if_key_exists = stop_if_key_exists || '';
    void_function = void_function || function () { return true; };
    allKeys = addressObjectKeys(object, stop_if_key_exists, void_function);

    return allKeys.filter(function (path) {
        return keys.indexOf(path) !== -1;
    });
};


text:
Unlike a traditional system cron that schedules tasks for specific times, WP-Cron will only process pending tasks during a request.

## Uncategorized

**Add Custom Interval**

```php
function example_add_cron_interval( $schedules ) {
	$schedules['five_seconds'] = array(
		'interval' => 5,
		'display'  => esc_html__( 'Every Five Seconds' ),
	);
	return $schedules;
}
add_filter( 'cron_schedules', 'example_add_cron_interval' );
```

See https://developer.wordpress.org/reference/hooks/cron_schedules/.

**Functions**

- wp_clear_scheduled_hook( string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_clear_scheduled_hook/
- wp_get_ready_cron_jobs()
	+ https://developer.wordpress.org/reference/functions/wp_get_ready_cron_jobs/
- wp_get_schedule( string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_get_schedule/
- wp_get_scheduled_event( string $hook, array $args = array(), int|null $timestamp = null )
	+ https://developer.wordpress.org/reference/functions/wp_get_scheduled_event/
- wp_get_schedules()
	+ https://developer.wordpress.org/reference/functions/wp_get_schedules/
- wp_next_scheduled( string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_next_scheduled/
- wp_reschedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_reschedule_event/
- wp_schedule_event( int $timestamp, string $recurrence, string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_schedule_single_event/
- wp_schedule_single_event( int $timestamp, string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_schedule_event/
- wp_unschedule_event( int $timestamp, string $hook, array $args = array() )
	+ https://developer.wordpress.org/reference/functions/wp_unschedule_event/
- wp_unschedule_hook( string $hook )
	+ https://developer.wordpress.org/reference/functions/wp_unschedule_hook/

**Misc**

Cron information is stored in the `cron` option in the `wp_options` table.

**Plugins Known Not to Clean Up Their Cron Jobs on Deletion**

- Updraft Plus
- WP Optimize
- Yoast

**Other Related Hooks**

**Filters**

- https://developer.wordpress.org/reference/hooks/cron_request/
- https://developer.wordpress.org/reference/hooks/cron_schedules/
- https://developer.wordpress.org/reference/hooks/get_schedule/
- https://developer.wordpress.org/reference/hooks/pre_clear_scheduled_hook/
- https://developer.wordpress.org/reference/hooks/pre_get_ready_cron_jobs/
- https://developer.wordpress.org/reference/hooks/pre_get_scheduled_event/
- https://developer.wordpress.org/reference/hooks/pre_reschedule_event/
- https://developer.wordpress.org/reference/hooks/pre_schedule_event/
- https://developer.wordpress.org/reference/hooks/pre_unschedule_event/
- https://developer.wordpress.org/reference/hooks/pre_unschedule_hook/
- https://developer.wordpress.org/reference/hooks/schedule_event/

**Running WP-Cron**

To run WP-Cron, regardless of whether `DISABLE_WP_CRON` is set to true, hit the https://domain.com/wp-cron.php?doing_wp_cron URL.

```sh
wget -q -O - https://domain.com/wp-cron.php?doing_wp_cron >/dev/null 2>&1
```


text:
namespace chromecast {
class CastCrashReporterClientAndroid;

class CrashHandler {
 public:
  // Initializes the crash handler for attempting to upload crash dumps with
  // the current process's log file.
  // Must not be called more than once.
  static void Initialize(const std::string& process_type,
                         const base::FilePath& log_file_path);

  // Returns the directory location for crash dumps.
  static bool GetCrashDumpLocation(base::FilePath* crash_dir);

 private:
  CrashHandler(const std::string& process_type,
               const base::FilePath& log_file_path);
  ~CrashHandler();

  void Initialize();

  // Starts a thread to periodically check for uploads
  void InitializeUploader();

  // Path to the current process's log file.
  base::FilePath log_file_path_;

  // Location to which crash dumps should be written.
  base::FilePath crash_dump_path_;

  std::string process_type_;

  std::unique_ptr<CastCrashReporterClientAndroid> crash_reporter_client_;

  DISALLOW_COPY_AND_ASSIGN(CrashHandler);
};

}  // namespace chromecast

#endif  // CHROMECAST_APP_ANDROID_CRASH_HANDLER_H_


text:
package io.opensec.six.oval.model.windows;

import io.opensec.six.oval.model.sc.EntityItemStringType;

/**
 * The EntityItemRegistryType defines the different values
 * that are valid for the type entity of a registry item.
 *
 * @author  Akihito Nakamura, AIST
 * @see OVAL Language
 */
public class EntityItemRegistryTypeType
    extends EntityItemStringType
{

    /**
     * Constructor.
     */
    public EntityItemRegistryTypeType()
    {
    }

    public EntityItemRegistryTypeType(
                    final String content
                    )
    {
        super( content );
    }

    //**************************************************************
    //  EntityItemBase
    //**************************************************************

    @Override
    public void setContent(
                    final String content
                    )
    {
        if (content != null) {
            // validation
            RegistryTypeEnumeration.fromValue( content );
        }

        super.setContent( content );
    }

    //**************************************************************
    //  java.lang.Object
    //**************************************************************

    @Override
    public int hashCode()
    {
        return super.hashCode();
    }

    @Override
    public boolean equals(
                    final Object obj
                    )
    {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof EntityItemRegistryTypeType)) {
            return false;
        }

        return super.equals( obj );
    }

}
// EntityItemRegistryTypeType


text:
namespace ServiceRegister.Store.CodeFirst.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class ShorterServiceNames : ServiceRegisterDbMigration
    {
        public override void Up()
        {
            AlterColumn("servicelanguagespecification", "name", c => c.String(maxLength: 100));
            AlterColumn("servicelanguagespecification", "alternatename", c => c.String(maxLength: 100));
        }

        public override void Down()
        {
            AlterColumn("servicelanguagespecification", "alternatename", c => c.String(maxLength: 500));
            AlterColumn("servicelanguagespecification", "name", c => c.String(maxLength: 500));
        }
    }
}


text:
module V1
  class EventSpeakersController < ApplicationController

    # GET /event_speakers/:id
    def show
      @event_speaker = EventSpeaker.find(params[:id])
      event = @event_speaker.event_session.event
      raise ApiAccessEvanta::PermissionDenied if !event.show_speakers?(current_user)
      raise ApiAccessEvanta::PermissionDenied if event.group.private? && !current_user.event_user_or_group_member?(event)
      raise ActiveRecord::RecordNotFound if event.group.secret? && !current_user.event_user_or_group_member?(event)
      render json: @event_speaker, serailizer: EventSpeakerSerializer
    end

    # GET /event_speakers/event_session/:event_session_id
    def show_session_speakers
      event_session = EventSession.find(params[:event_session_id])
      raise ApiAccessEvanta::PermissionDenied if !event_session.event.show_speakers?(current_user)
      @event_speakers = event_session.speakers
      render json: @event_speakers, each_serailizer: EventSpeakerShortSerializer
    end

    # GET /event_speakers/event/:event_id
    def show_event_speakers
      event = Event.find(params[:event_id])
      raise ApiAccessEvanta::PermissionDenied if !event.show_speakers?(current_user)
      render json: event.event_speakers, each_serailizer: EventSpeakerShortSerializer
    end

  end
end


text:
package org.axonframework.eventsourcing.eventstore.jpa;

import org.axonframework.common.AxonConfigurationException;
import org.junit.Test;
import org.mockito.Mockito;

import javax.persistence.PersistenceException;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

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

/**
 * @author Martin Tilma
 */
public class SQLErrorCodesResolverTest {

    @Test
    public void testIsDuplicateKey() throws Exception {
        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(new ArrayList<>());

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                new RuntimeException()));

        assertFalse(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingSetDuplicateKeyCodes() throws Exception {
        List<Integer> errorCodes = new ArrayList<>();
        errorCodes.add(-104);
        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(errorCodes);

        SQLException sqlException = new SQLException("test", "error", errorCodes.get(0));

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingDataSource() throws Exception {
        String databaseProductName = "HSQL Database Engine";
        DataSource dataSource = createMockDataSource(databaseProductName);

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(dataSource);

        SQLException sqlException = new SQLException("test", "error", -104);

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingAS400DataSource() throws Exception {
        String databaseProductName = "DB2 UDB for AS/400";
        DataSource dataSource = createMockDataSource(databaseProductName);

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(dataSource);

        SQLException sqlException = new SQLException("test", "error", -803);

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingProductName() throws Exception {
        String databaseProductName = "HSQL Database Engine";

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(databaseProductName);

        SQLException sqlException = new SQLException("test", "error", -104);

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingCustomProperties() throws Exception {
        Properties props = new Properties();
        props.setProperty("MyCustom_Database_Engine.duplicateKeyCodes", "-104");

        String databaseProductName = "MyCustom Database Engine";
        DataSource dataSource = createMockDataSource(databaseProductName);

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(props, dataSource);

        SQLException sqlException = new SQLException("test", "error", -104);

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test(expected = AxonConfigurationException.class)
    public void testInitialization_UnknownProductName() throws Exception {
        DataSource dataSource = createMockDataSource("Some weird unknown DB type");

        new SQLErrorCodesResolver(dataSource);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingSqlState() throws Exception {
        Properties props = new Properties();
        props.setProperty("MyCustom_Database_Engine.duplicateKeyCodes", "-104");

        String databaseProductName = "MyCustom Database Engine";

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(props, databaseProductName);

        SQLException sqlException = new SQLException("test", "-104");

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertTrue(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingNonIntSqlState() throws Exception {
        Properties props = new Properties();
        props.setProperty("MyCustom_Database_Engine.duplicateKeyCodes", "-104");

        String databaseProductName = "MyCustom Database Engine";

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(props, databaseProductName);

        SQLException sqlException = new SQLException("test", "thisIsNotAnInt");

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertFalse(isDuplicateKey);
    }

    @Test
    public void testIsDuplicateKey_isDuplicateKey_usingNonNullSqlState() throws Exception {
        Properties props = new Properties();
        props.setProperty("MyCustom_Database_Engine.duplicateKeyCodes", "-104");

        String databaseProductName = "MyCustom Database Engine";

        SQLErrorCodesResolver sqlErrorCodesResolver = new SQLErrorCodesResolver(props, databaseProductName);

        SQLException sqlException = new SQLException("test", (String) null);

        boolean isDuplicateKey = sqlErrorCodesResolver.isDuplicateKeyViolation(new PersistenceException("error",
                                                                                sqlException));

        assertFalse(isDuplicateKey);
    }

    private DataSource createMockDataSource(String databaseProductName) throws SQLException {
        DataSource dataSource = Mockito.mock(DataSource.class);
        Connection connection = Mockito.mock(Connection.class);
        DatabaseMetaData databaseMetaData = Mockito.mock(DatabaseMetaData.class);

        Mockito.when(databaseMetaData.getDatabaseProductName()).thenReturn(databaseProductName);
        Mockito.when(connection.getMetaData()).thenReturn(databaseMetaData);
        Mockito.when(dataSource.getConnection()).thenReturn(connection);
        return dataSource;
    }
}


text:
var group__stm32f446xx =
[
    [ "Configuration_section_for_CMSIS", "group___configuration__section__for___c_m_s_i_s.html", "group___configuration__section__for___c_m_s_i_s" ],
    [ "Peripheral_interrupt_number_definition", "group___peripheral__interrupt__number__definition.html", "group___peripheral__interrupt__number__definition" ],
    [ "Peripheral_registers_structures", "group___peripheral__registers__structures.html", "group___peripheral__registers__structures" ],
    [ "Peripheral_memory_map", "group___peripheral__memory__map.html", "group___peripheral__memory__map" ],
    [ "Peripheral_declaration", "group___peripheral__declaration.html", null ],
    [ "Exported_constants", "group___exported__constants.html", "group___exported__constants" ],
    [ "Exported_macros", "group___exported__macros.html", null ]
];


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Beih. Sydowia 1: 90 (1957)

#### Original name
Amazonia scaevolae Hansf.

### Remarks
null


text:
package mail

import (
	"errors"
	"fmt"
	"io"
	stdmail "net/mail"
)

// Sender is the interface that wraps the Send method.
//
// Send sends an email to the given addresses.
type Sender interface {
	Send(from string, to []string, msg io.WriterTo) error
}

// SendCloser is the interface that groups the Send and Close methods.
type SendCloser interface {
	Sender
	Close() error
}

// A SendFunc is a function that sends emails to the given addresses.
//
// The SendFunc type is an adapter to allow the use of ordinary functions as
// email senders. If f is a function with the appropriate signature, SendFunc(f)
// is a Sender object that calls f.
type SendFunc func(from string, to []string, msg io.WriterTo) error

// Send calls f(from, to, msg).
func (f SendFunc) Send(from string, to []string, msg io.WriterTo) error {
	return f(from, to, msg)
}

// Send sends emails using the given Sender.
func Send(s Sender, msg ...*Message) error {
	for i, m := range msg {
		if err := send(s, m); err != nil {
			return &SendError{Cause: err, Index: uint(i)}
		}
	}

	return nil
}

func send(s Sender, m *Message) error {
	from, err := m.getFrom()
	if err != nil {
		return err
	}

	to, err := m.getRecipients()
	if err != nil {
		return err
	}

	if err := s.Send(from, to, m); err != nil {
		return err
	}

	return nil
}

func (m *Message) getFrom() (string, error) {
	from := m.header["Sender"]
	if len(from) == 0 {
		from = m.header["From"]
		if len(from) == 0 {
			return "", errors.New(`gomail: invalid message, "From" field is absent`)
		}
	}

	return parseAddress(from[0])
}

func (m *Message) getRecipients() ([]string, error) {
	n := 0
	for _, field := range []string{"To", "Cc", "Bcc"} {
		if addresses, ok := m.header[field]; ok {
			n += len(addresses)
		}
	}
	list := make([]string, 0, n)

	for _, field := range []string{"To", "Cc", "Bcc"} {
		if addresses, ok := m.header[field]; ok {
			for _, a := range addresses {
				addr, err := parseAddress(a)
				if err != nil {
					return nil, err
				}
				list = addAddress(list, addr)
			}
		}
	}

	return list, nil
}

func addAddress(list []string, addr string) []string {
	for _, a := range list {
		if addr == a {
			return list
		}
	}

	return append(list, addr)
}

func parseAddress(field string) (string, error) {
	addr, err := stdmail.ParseAddress(field)
	if err != nil {
		return "", fmt.Errorf("gomail: invalid address %q: %v", field, err)
	}
	return addr.Address, nil
}