text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:toggle="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:orientation="vertical"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/bg_corners"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/about_view_back"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:background="@drawable/bg_corners" >

            <include layout="@layout/view_title_lback" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="40dp"
                android:gravity="center"
                android:text="设置"
                android:layout_centerVertical="true"
                android:textColor="@color/text_main"
                android:textSize="@dimen/text_normal" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:layout_marginTop="20dp"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_weight="1"
                    android:text="常驻通知栏"
                    android:textColor="#626262"
                    android:textSize="@dimen/text_l" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ellipsize="end"
                    android:gravity="right"
                    android:paddingLeft="10dp"
                    android:singleLine="true"
                    android:textColor="@color/textGray"
                    android:textSize="@dimen/text_normal" />

                <com.zcw.togglebutton.ToggleButton
                    android:id="@+id/as_switchbutton_notice"
                    android:layout_width="60dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"
                    android:layout_marginRight="20dp"
                    toggle:offColor="@color/white"
                    toggle:onColor="#65bd12"
                    toggle:spotColor="#fff" />
            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="18dp"
                android:layout_marginRight="18dp"
                android:background="@color/bg_line" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:gravity="center_vertical"
                android:orientation="horizontal" >

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="20dp"
                    android:layout_weight="1"
                    android:text="显示桌面悬浮窗"
                    android:textColor="#626262"
                    android:textSize="@dimen/text_l" />

                <TextView
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:ellipsize="end"
                    android:gravity="right"
                    android:paddingLeft="10dp"
                    android:singleLine="true"
                    android:textColor="@color/textGray"
                    android:textSize="@dimen/text_normal" />

                <com.zcw.togglebutton.ToggleButton
                    android:id="@+id/as_switchbutton_desktop"
                    android:layout_width="60dp"
                    android:layout_height="30dp"
                    android:layout_gravity="center"
                    android:layout_marginRight="20dp"
                    toggle:offColor="@color/white"
                    toggle:onColor="#65bd12"
                    toggle:spotColor="#fff" />
            </LinearLayout>

            <View
                android:layout_width="match_parent"
                android:layout_height="1dp"
                android:layout_marginLeft="18dp"
                android:layout_marginRight="18dp"
                android:background="@color/bg_line" />
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="40dp"
            android:gravity="center_vertical"
            android:orientation="horizontal" >

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:layout_weight="1"
                android:text="开机自启动"
                android:textColor="#626262"
                android:textSize="@dimen/text_l" />

            <TextView
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:ellipsize="end"
                android:gravity="right"
                android:paddingLeft="10dp"
                android:singleLine="true"
                android:textColor="@color/textGray"
                android:textSize="@dimen/text_normal" />

            <com.zcw.togglebutton.ToggleButton
                android:id="@+id/as_switchbutton_start"
                android:layout_width="60dp"
                android:layout_height="30dp"
                android:layout_gravity="center"
                android:layout_marginRight="20dp"
                toggle:offColor="@color/white"
                toggle:onColor="#65bd12"
                toggle:spotColor="#fff" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:layout_marginLeft="18dp"
            android:layout_marginRight="18dp"
            android:background="@color/bg_line" />
    </LinearLayout>

</LinearLayout>

redpajama_set_name: RedPajamaGithub


text:
package com.qatang.admin.dao.user;

import com.qatang.admin.entity.user.User;
import com.qatang.core.dao.IDao;

/**
 * @author qatang
 * @since 2014-12-19 14:46
 */
public interface UserDao extends IDao<User, Long> {
    public User findByUsername(String username);

    public User findByEmail(String email);
}


text:
import logging
import tqdm
from collections import Counter
from indra.statements.validate import assert_valid_statements
from indra.databases import hgnc_client, uniprot_client
from indra.statements import Agent, Phosphorylation, Autophosphorylation, \
    Evidence, BioContext, RefContext, get_valid_residue, \
    InvalidResidueError, MutCondition

logger = logging.getLogger(__name__)

class RlimspProcessor(object):
    """Convert RLIMS-P JSON into INDRA Statements."""

    def __init__(self, rlimsp_json, doc_id_type=None):
        self._json = rlimsp_json
        self.statements = []
        self.doc_id_type = doc_id_type
        self.processed_texts = []
        return

    def extract_statements(self):
        """Extract the statements from the json."""
        for p_info in tqdm.tqdm(self._json, desc='Processing RLIMS-P JSON'):
            para = RlimspParagraph(p_info, self.doc_id_type)
            if para._text not in self.processed_texts:
                self.processed_texts.append(para._text)
                stmts = para.get_statements()
                assert_valid_statements(stmts)
                self.statements.extend(stmts)
        return

class RlimspParagraph(object):
    """An object that represents a single RLIMS-P Paragraph."""
    def __init__(self, p_info, doc_id_type):
        self._text = p_info['text']
        self._sentences = []
        self._sentence_starts = []
        for s in p_info['sentence']:
            start = s['charStart']
            stop = s['charEnd']
            self._sentences.append(self._text[start:stop])
            self._sentence_starts.append(start)
        if 'pmid' in p_info and 'pmcid' in p_info:
            self._text_refs = {n.upper(): p_info[n] for n in ['pmid', 'pmcid']
                               if p_info[n]}
        elif doc_id_type:
            self._text_refs = {doc_id_type.upper(): p_info['docId']}
        else:
            logger.info('Could not establish text refs for paragraph.')
            self._text_refs = {}
        self._relations = p_info['relation']
        self._entity_dict = p_info['entity']
        return

    def _get_agent(self, entity_id):
        """Convert the entity dictionary into an INDRA Agent."""
        if entity_id is None:
            return None

        entity_info = self._entity_dict.get(entity_id)
        if entity_info is None:
            logger.warning("Entity key did not resolve to entity.")
            return None
        return get_agent_from_entity_info(entity_info)

    def _get_site(self, site_id):
        def get_aa_code(residue_str):
            try:
                res = get_valid_residue(residue_str)
                return res
            except InvalidResidueError as e:
                logger.info('%s' % e)
                return None

        if site_id is None:
            return None, None, None
        site_info = self._entity_dict[site_id]
        site_text = site_info['attribute'][0]['value']
        site_parts = site_text.split('-')
        position = None
        if len(site_parts) == 2:
            residue_str = site_parts[0]
            residue = get_aa_code(residue_str)
            position = site_parts[1]
        else:
            residue = get_aa_code(site_text)
        coords = (site_info['charStart'], site_info['charEnd'])
        return residue, position, coords

    def _get_evidence(self, trigger_info, args, agent_coords, site_coords):
        """Get the evidence using the info in the trigger entity."""
        # Get the sentence index from the trigger word.
        s_idx_set = {self._entity_dict[eid]['sentenceIndex']
                     for eid in args.values()
                     if 'sentenceIndex' in self._entity_dict[eid]}
        if s_idx_set:
            i_min = min(s_idx_set)
            i_max = max(s_idx_set)

            text = '. '.join(self._sentences[i_min:(i_max+1)]) + '.'

            s_start = self._sentence_starts[i_min]
            annotations = {
                'agents': {'coords': [_fix_coords(coords, s_start)
                                      for coords in agent_coords]},
                'trigger': {'coords': _fix_coords([trigger_info['charStart'],
                                                   trigger_info['charEnd']],
                                                  s_start),
                            'text': trigger_info['entityText']}
                }
        else:
            logger.info('Unable to get sentence index')
            annotations = {}
            text = None
        if site_coords:
            annotations['site'] = {'coords': _fix_coords(site_coords, s_start)}

        return Evidence(text_refs=self._text_refs.copy(), text=text,
                        source_api='rlimsp', pmid=self._text_refs.get('PMID'),
                        annotations=annotations)

    def get_statements(self):
        stmts = []
        for rel_key, rel_info in self._relations.items():
            # Turn the arguments into a dict.
            args = {e['role']: e['entity_duid'] for e in rel_info['argument']}
            entity_args = args.copy()

            # Remove some special cases.
            trigger_id = entity_args.pop('TRIGGER')
            trigger_info = self._entity_dict[trigger_id]
            site_id = entity_args.pop('SITE', None)

            # Get the entity ids.
            entities = {role: self._get_agent(eid)
                        for role, eid in entity_args.items()}

            rel_type = rel_info['relationType']
            if rel_type == 'PHOSPHORYLATION':

                # Get the agents.
                enz, enz_coords = entities.get('KINASE', (None, None))
                sub, sub_coords = entities.get('SUBSTRATE', (None, None))
                if sub is None:
                    continue

                trigger_text = trigger_info.get('entityText')
                if enz is not None and enz.name == sub.name and \
                        'auto' in trigger_text:
                    is_autophos = True
                else:
                    is_autophos = False

                # Get the site
                residue, position, site_coords = self._get_site(site_id)

                # Get the evidence
                ev = self._get_evidence(trigger_info, args,
                                        [enz_coords, sub_coords],
                                        site_coords)

                # Turn taxonomy into context, sub TAX takes precedence
                tax = None
                if enz and 'TAX' in enz.db_refs:
                    tax = enz.db_refs.pop('TAX')
                if sub and 'TAX' in sub.db_refs:
                    tax = sub.db_refs.pop('TAX')
                if tax is not None:
                    context = \
                        BioContext(species=RefContext(tax,
                                                      {'TAXONOMY': tax}))
                    ev.context = context

                if is_autophos:
                    stmt = Autophosphorylation(sub, residue=residue,
                                               position=position,
                                               evidence=[ev])
                else:
                    stmt = Phosphorylation(enz, sub, residue=residue,
                                           position=position,
                                           evidence=[ev])
                stmts.append(stmt)
            else:
                logger.warning("Unhandled statement type: %s" % rel_type)

        return stmts

def get_agent_from_entity_info(entity_info):
    """Return an INDRA Agent by processing an entity_info dict."""
    # This will be the default name. If we get a gene name, it will
    # override this rawtext name.
    raw_text = entity_info['entityText']
    name = raw_text

    # Get the db refs.
    refs = {'TEXT': raw_text}
    entries = entity_info['entityId']
    if entries is None or entries == {'$undefined': True}:
        entries = []
    ref_counts = Counter([entry['source'] for entry in entries])
    for source, count in ref_counts.items():
        if source in ('Entrez', 'UniProt') and count > 1:
            logger.info('%s has %d entries for %s, skipping'
                        % (raw_text, count, source))
            return None, None
    muts = []
    for id_dict in entries:
        if id_dict['source'] == 'Entrez':
            refs['EGID'] = id_dict['idString']
            hgnc_id = hgnc_client.get_hgnc_from_entrez(id_dict['idString'])
            if hgnc_id is not None:
                # Check against what we may have already inferred from
                # UniProt. If it disagrees with this, let it be. Inference
                # from Entrez isn't as reliable.
                if 'HGNC' in refs.keys():
                    if refs['HGNC'] != hgnc_id:
                        msg = ('HGNC:%s previously set does not'
                               ' match HGNC:%s from EGID:%s') % \
                               (refs['HGNC'], hgnc_id, refs['EGID'])
                        logger.info(msg)
                else:
                    refs['HGNC'] = hgnc_id
        elif id_dict['source'] == 'UniProt':
            refs['UP'] = id_dict['idString']
            hgnc_id = uniprot_client.get_hgnc_id(id_dict['idString'])
            if hgnc_id:
                # Check to see if we have a conflict with an HGNC id
                # found from the Entrez id. If so, overwrite with this
                # one, in which we have greater faith.
                if 'HGNC' in refs.keys() and refs['HGNC'] != hgnc_id:
                    msg = ('Inferred HGNC:%s from UP:%s does not'
                           ' match HGNC:%s from EGID:%s') % \
                          (refs['HGNC'], refs['UP'], hgnc_id,
                           refs['EGID'])
                    logger.info(msg)
                refs['HGNC'] = hgnc_id
                name = hgnc_client.get_hgnc_name(hgnc_id)
            else:
                gene_name = uniprot_client.get_gene_name(id_dict['idString'])
                if gene_name is not None:
                    name = gene_name
        elif id_dict['source'] in ('Tax', 'NCBI'):
            # Note that TAX is non-standard but it's popped out later in the
            # extraction process
            refs['TAX'] = id_dict['idString']
        elif id_dict['source'] == 'CHEBI':
            refs['CHEBI'] = 'CHEBI:%s' % id_dict['idString']
        # These we take as is
        elif id_dict['source'] in ('MESH', 'OMIM'):
            refs[id_dict['source']] = id_dict['idString']
        # CTD is sometimes used for MESH chemical IDs but can also be just '-'
        elif id_dict['source'] == 'CTD':
            if id_dict['idString'] != '-':
                refs['MESH'] = id_dict['idString']
        # Handle mutations
        elif id_dict['source'] == 'Unk' and \
                id_dict['entityType'] == 'ProteinMutation':
            # {'idString': 'p|SUB|Y|268|A', 'source': 'Unk',
            #  'tool': 'PubTator', 'entityType': 'ProteinMutation'}
            # Mpk1(Y268A)'
            if id_dict['idString'].startswith('p|SUB|'):
                try:
                    # Handle special cases like p|SUB|A|30|P;RS#:104893878
                    parts = id_dict['idString'].split(';')[0].split('|')
                    residue_from, pos, residue_to = parts[2:5]
                    mut = MutCondition(pos, residue_from, residue_to)
                    muts.append(mut)
                except Exception as e:
                    logger.info('Could not process mutation %s' %
                                id_dict['idString'])
            else:
                logger.info('Unhandled mutation: %s' % id_dict['idString'])
        else:
            logger.warning("Unhandled id type: {source}={idString}"
                           .format(**id_dict))

    raw_coords = (entity_info['charStart'], entity_info['charEnd'])
    return Agent(name, db_refs=refs, mutations=muts), raw_coords

def _fix_coords(coords, offset):
    """Adjust the entity coordinates to the beginning of the sentence."""
    if coords is None:
        return None
    return tuple([n - offset for n in coords])


text:
/*.wikiEditor-ui-controls, .wikiEditor-ui-tabs, .wikiEditor-ui-buttons {
	background: transparent!important;
}*/
.wikiEditor-ui{
    color: #333;
}
.wikiEditor-ui .mw-charinsert-buttons a{
    color: #428bca;
}
.skin-bootstrap-mediawiki form#edit-form,.skin-bootstrap-mediawiki .wikiEditor-ui,.skin-bootstrap-mediawiki .editOptions{
    font-size: 14px;
}
.wikiEditor-ui-toolbar,.wikiEditor-ui-toolbar .sections .section{
    background: #eee!important;
}
#msupload-dropzone{
    height: auto!important;
}
.wikiEditor-ui-toolbar .page-characters div span{
    height: auto!important;
}
.wikiEditor-preview-contents,#wpTextbox1{
    font-size: 16px;
}
/*@media screen*/
.editOptions {
    background-color: #F0F0F0;
    border: 1px solid silver;
    border-top: none;
    padding: 1em 1em 1.5em 1em;
    margin-bottom: 2em;
    color: #333;
}
.editOptions a {
    color: #09c;
}
.client-js .mw-edittools-section input[type="button"] {
    font-size: 0.9em;
    padding-left: 1px;
    padding-right: 1px;
    margin-left: 1px;
}
/*button, html input[type=button], input[type=reset], input[type=submit] {*/
    /*-webkit-appearance: push-button; */
    /*-moz-appearance: -moz-win-borderless-glass;*/
	/*-moz-appearance: -moz-mac-unified-toolbar;*/
/*}*/
p.mw-edittools-section {
	display:inline;
}
.mw-editTools {
/*	border-left: 1px solid silver;
	border-right: 1px solid silver;*/
	padding: 0px 10px;
}

#msupload-select {
	z-index: 0 !important;
}
#msupload-bottom{
    height: auto !important;
}
#msupload-container{
    display:none;
}
.skin-bootstrap-mediawiki .CodeMirror {
    font-family: inherit;
}
.skin-BootstrapMediawiki .CodeMirror {
   border: 1px solid #CCC;
   font-size: 16px;
   line-height: 1.5em;
}

.skin-BootstrapMediawiki .CodeMirrorIE {
   font-size: small;
}
.skin-BootstrapMediawiki .CodeMirror pre {
    z-index: 1;
}

/*// .CodeMirror .cm-mw-pagename { text-decoration: underline; }*/
 /**/
/*// .CodeMirror .cm-mw-matching {background-color: gold;}*/
 /**/
/*// .CodeMirror .cm-mw-skipformatting {    background-color: #adf; }*/
/*// .CodeMirror .cm-mw-list {color: #08f; font-weight: normal; background-color: #eee;}*/
/*// .CodeMirror .cm-mw-signature,*/
/*// .CodeMirror .cm-mw-hr { color: #08f; font-weight: normal; background-color: #eee; }*/
/*// .CodeMirror .cm-mw-indenting {color: #08f; font-weight: normal; background-color: #ddd;}*/
/*// .CodeMirror .cm-mw-mnemonic {color: #090;}*/
/*// .CodeMirror .cm-mw-comment {color: #aaa; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-apostrophes-bold, .cm-mw-apostrophes-italic {color: #08f;}*/
 /**/
/*// .CodeMirror pre.cm-mw-section-1 {font-size: 1.8em;}*/
/*// .CodeMirror pre.cm-mw-section-3 {font-weight: normal;}*/
/*// .CodeMirror pre.cm-mw-section-4 {font-weight: normal;}*/
/*// .CodeMirror pre.cm-mw-section-5 {font-weight: normal;}*/
/*// .CodeMirror pre.cm-mw-section-6 {font-weight: normal;}*/
/*// .CodeMirror .cm-mw-section-header {color: #08f; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-template {color: #a11; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-template-name {color: #a11; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-template-name-mnemonic {font-weight: normal;}*/
/*// .CodeMirror .cm-mw-template-argument-name {color: #a11; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-template-delimiter {color: #a11; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-template-bracket {color: #a11; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-templatevariable {color: #f50;  font-weight: normal;}*/
/*// .CodeMirror .cm-mw-templatevariable-name {color: #f50; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-templatevariable-bracket {color: #f50;  font-weight: normal;}*/
/*// .CodeMirror .cm-mw-templatevariable-delimiter {color: #f50; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-parserfunction {font-weight: normal;}*/
/*// .CodeMirror .cm-mw-parserfunction-name {color: #70a; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-parserfunction-bracket {color: #70a; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-parserfunction-delimiter {color: #70a; font-weight: normal;}*/
 /**/
/*// .CodeMirror pre.cm-mw-exttag {background-image: url(img/ext2.png);}*/
/*// .CodeMirror .cm-mw-exttag {background-image: url(img/ext4.png);}*/
/*// .CodeMirror .cm-mw-exttag-name {color: #70a; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-exttag-bracket {color: #70a; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-exttag-attribute {color: #70a; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-htmltag-name {color: #170; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-htmltag-bracket {color: #170; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-htmltag-attribute {color: #170; font-weight: normal;}*/
 /**/
/*// .CodeMirror pre.cm-mw-tag-pre, .cm-mw-tag-pre {background-image: url(img/black4.png);}*/
/*// .CodeMirror pre.cm-mw-tag-nowiki, .cm-mw-tag-nowiki {background-image: url(img/black4.png);}*/
 /**/
/*// .CodeMirror .cm-mw-link-pagename {color: #219; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-link-tosection {color: #08f; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-link-bracket {color: #219; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-link-text {}*/
/*// .CodeMirror .cm-mw-link-delimiter {color: #219; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-extlink, .cm-mw-free-extlink {color: #219; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-extlink-protocol, .cm-mw-free-extlink-protocol {color: #219; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-extlink-text {}*/
/*// .CodeMirror .cm-mw-extlink-bracket {color: #219; font-weight: normal;}*/
 /**/
/*// .CodeMirror .cm-mw-table-bracket {color: #e0e; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-table-delimiter {color: #e0e; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-table-definition {color: #e0e; font-weight: normal;}*/
/*// .CodeMirror .cm-mw-table-caption {font-weight: normal;}*/
.CodeMirror{
    font-family: inherit!important;
}
#msupload-div{
    background: #000!important;
}
#wikiEditor-section-advanced > div.group> .label{
    padding-top: 0!important;
}
#wikiEditor-section-characters{
    font-size: 12px;
}
.wikiEditor-toolbar-spritedButton{
    /* @embed */
    background: url("http://fs.huijiwiki.com/www/resources/assets/editor-icon.png");
}
#wikiEditor-section-main > div.group.group-format > a:nth-child(1){
    background-position:0 0px !important;
}
#wikiEditor-section-main > div.group.group-format > a:nth-child(2){
    background-position:0 -44px !important;
}
#wikiEditor-section-main > div.group.group-insert > a[rel="link"]{
    background-position:0 -88px !important;
}
#wikiEditor-section-main > div.group.group-insert > a[rel="file"]{
    background-position:0 -132px !important;
}
#wikiEditor-section-main > div.group.group-insert > a[rel="reference"]{
    background-position:0 -176px !important;
}
#wikiEditor-section-advanced > div.group.group-format > a:nth-child(2){
    background-position:0 -394px !important;
}
#wikiEditor-section-advanced > div.group.group-format > a:nth-child(3){
    background-position:0 -440px !important;
}
#wikiEditor-section-advanced > div.group.group-format > a:nth-child(4){
    background-position:0 -484px !important;
}
#wikiEditor-section-advanced > div.group.group-format > a:nth-child(5){
    background-position:0 -528px !important;
}
#wikiEditor-section-advanced > div.group.group-size > a:nth-child(1){
    background-position:0 -572px !important;
}
#wikiEditor-section-advanced > div.group.group-size > a:nth-child(2){
    background-position:0 -616px !important;
}
#wikiEditor-section-advanced > div.group.group-size > a:nth-child(3){
    background-position:0 -660px !important;
}
#wikiEditor-section-advanced > div.group.group-size > a:nth-child(4){
    background-position:0 -704px !important;
}
#wikiEditor-section-advanced > div.group.group-insert > a[rel="gallery"]{
    background-position:0 -748px !important;
}
#wikiEditor-section-advanced > div.group.group-insert > a[rel="redirect"]{
    background-position:0 -792px !important;
}
#wikiEditor-section-advanced > div.group.group-insert > a[rel="table"]{
    background-position:0 -836px !important;
}
#wikiEditor-section-advanced > div.group.group-search > a:nth-child(1){
    background-position:0 -924px !important;
}
.skin-BootstrapMediawiki .tool-button {
    background-position: 0px 0px !important;
}
.mw-editTools p {
    display:inline;
    line-height: 1;
}
.wikiEditor-ui-toolbar .section-main{
    height: 0 !important;
}
#mw-edittools-charinsert{
    position: relative;
    display: inline-block;
    vertical-align: middle;
}
#mw-edittools-charinsert a{
    width: 10%;
}
.mw-scribunto-console-fieldset{
    background:transparent;
}


text:
package com.kevinquan.cwa.tests;

import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.junit.Assert.assertThat;

import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Test;

import com.kevinquan.cwa.Blueprints;
import com.kevinquan.cwa.model.levels.Quest;
import com.kevinquan.java.utils.JSONUtils;
import com.kevinquan.tests.BaseJUnit4Test;

public class QuestsTestCase extends BaseJUnit4Test {

    @SuppressWarnings("unused")
    private static final String TAG = QuestsTestCase.class.getSimpleName();

    protected JSONArray mBlueprint;

    @Override
    public void setUp() {
        super.setUp();
        mBlueprint = readBlueprint(Blueprints.QUESTS);
    }

    @Test
    public void testQuestBlueprint() {
        assertThat("Incorrect blueprint count", mBlueprint.length(), is(mNameTranslater.getQuestCount()));
        for (int i = 0; i < mBlueprint.length(); i++) {
            JSONObject questCondition = JSONUtils.safeGetJSONObjectFromArray(mBlueprint, i);
            String questName = JSONUtils.safeGetString(questCondition, Blueprints.FIELD_ID);
            if (questName == null) {
                System.out.println("Could not retrieve quest name from "+questCondition);
                continue;
            }
            Quest quest = mNameTranslater.getQuestByName(questName);
            assertThat("Could not retrieve quest with name "+questName, quest, notNullValue());
        }
    }

}


text:
require 'rubygems'
require 'yaml'
require 'xml/libxml'
require 'net/http'
require "date"
require "uri"
require 'rexml/document'

@@locations_metafile = '.locations_metafile'

class Location

  def initialize(locationMode)
    @@locationMode = locationMode
    puts @@locationMode

    @@currentLocation = {'latitude' => 0, 'longitude' => 0}
    @@currentLocationUpdated = nil

    if @@locationMode == 'GPS'
      Thread.start{
        io = IO.popen("/usr/libexec/navicore-gpsd-helper >> .vrGPSTrace")

        #b = bb.readlines
        #puts b.join
      }

    end

  end

  def getLocation

    if @@currentLocation == nil or @@currentLocationUpdated == nil or (DateTime.now.min() - @@currentLocationUpdated.min()) > 2
      updateLocation
      @@currentLocationUpdated = DateTime.now
    end

    return @@currentLocation

  end

  # Updates current location of the device
  def updateLocation
    if @@locationMode == 'GPS'
      @@currentLocation = getLocationFromGPSfile
    elsif @@locationMode == 'noGPS1'
      @@currentLocation = getLocationFromService1
    else
      @@currentLocation = getLocationFromService2
    end

    # If updating from one service failed, tries updating from the other service
    if @@currentLocation['latitude'] == 0 or @@currentLocation['longitude'] == 0
      if @@locationMode == 'noGPS1'
        @@currentLocation = getLocationFromService2
      else
        @@currentLocation = getLocationFromService1
      end
    end
  end

  # Gets location based on the ip address from the service: http://api.hostip.info/
  def getLocationFromService1
    puts "service 1"
    location_longitude = 0
    location_latitude = 0
    location = {'latitude' => location_latitude, 'longitude' => location_longitude}
    begin

      uri = URI.parse('http://api.hostip.info/')
      Net::HTTP.start(uri.host, 80) { |http|

        response = http.get(uri.path.size > 0 ? uri.path : "/")
        case response
          when Net::HTTPSuccess
          xml = response.body

          if xml != nil
            puts "testx1"
            doc, posts = REXML::Document.new(xml), []
            doc.elements.each('HostipLookupResultSet/gml:featureMember/Hostip/ipLocation/gml:pointProperty/gml:Point/gml:coordinates') do |p|
              location_longitude, location_latitude = p.text.to_s.split(',')
              location = {'latitude' => location_latitude.to_f, 'longitude' => location_longitude.to_f}
            puts "testx2"
            end
          end

        else
          return errorLocation
        end
      }

    rescue => e
      puts "Couldn't update location: " + e.to_s
      return errorLocation
    end

    puts "Location from service1: " + location['latitude'].to_s + ", " + location['longitude'].to_s
    return location
  end

  # Gets location based on the ip address from service: ipaddressgeolocation.com
  def getLocationFromService2

    location_longitude = 0
    location_latitude = 0
    location = {'latitude' => location_latitude, 'longitude' => location_longitude}
    begin

      uri = URI.parse('http://www.ipaddressgeolocation.com')

      Net::HTTP.start(uri.host, 80) { |http|

        response = http.get(uri.path.size > 0 ? uri.path : "/")

        case response
          when Net::HTTPSuccess

            response.body.split(%r{<tr\s*>(.*?)</tr\s*>}mi).each do |tr|
              if tr['My IP address latitude:']
                location['latitude'] = (tr.split(%r{<td\s*>(.*?)°</td\s*>}mi)[1]).to_f
              elsif tr['My IP address longitude:']
                location['longitude'] = (tr.split(%r{<td\s*>(.*?)°</td\s*>}mi)[1]).to_f
              end
            end

          else

            return errorLocation
          end
      }
    rescue => e
      puts "Couldn't update location: " + e.to_s
      location = errorLocation
    end

    # Tällä voi antaa testiarvoja krs: 62.267423, 21.365082, koti: 61.454583, 23.842349
    # krs
    #location = {'latitude' => 62.267423, 'longitude' => 21.365082}
    # koti:
    # location = {'latitude' => 61.454583, 'longitude' => 23.842349}
    puts "Location from service2: " + location['latitude'].to_s + ", " + location['longitude'].to_s
    return location
  end

  def errorLocation
    location = Hash.new
    location['latitude'] = 0
    location['longitude'] = 0
    puts "Couldn't update location. Location: " + location['latitude'].to_s + ", " + location['longitude'].to_s
    return location
  end

  def getLocationFromGPSfile

    location = {'latitude' => 0, 'longitude' => 0}

    begin

      File.open(".vrGPSTrace", "r") do |infile|
        while (line = infile.gets)
          if line['$GPGLL'] != nil
            data = line.split(',', 5)

            lat = data[1].to_s
            lon = data[3].to_s

            if !lat.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) or !lon.to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/)
              next
            else

            lat = (data[1].to_f)/100
            lon = (data[3].to_f)/100

              #puts "lati: " + lat.to_s
              #puts "longi: " + lon.to_s
              puts line
              location = {'latitude' => 61.449820, 'longitude' => 23.857239 }
            end
          end
        end
      end

      if !location['latitude'].to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/) or !location['longitude'].to_s.match(/\A[+-]?\d+?(\.\d+)?\Z/)
        raise Exception.new("Can't get location.")
      end

      @@currentLocation = location

    rescue => e
      puts e
      @@currentLocation = {'latitude' => 0, 'longitude' => 0}
    end
  end

end


text:
"""Hamiltonian Monte Carlo, a gradient-based MCMC algorithm.
"""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

# go/tf-wildcard-import
from tensorflow.contrib.bayesflow.python.ops.hmc_impl import *  # pylint: disable=wildcard-import,unused-wildcard-import,g-importing-member
from tensorflow.python.util import all_util

_allowed_symbols = [
    'chain',
    'kernel',
    'leapfrog_integrator',
    'leapfrog_step',
    'ais_chain'
]

all_util.remove_undocumented(__name__, _allowed_symbols)


text:
using namespace foundation;
using namespace renderer;
using namespace std;

namespace appleseed {
namespace studio {

//
// DisneyMaterialCustomUI class implementation.
//

namespace
{
    int get_layer_number(const Dictionary& values)
    {
        return
            values.strings().exist("layer_number")
                ? values.get<int>("layer_number")
                : 0;
    }

    struct LayerDefinitionOrderPredicate
    {
        bool operator()(const Dictionary& lhs, const Dictionary& rhs) const
        {
            return get_layer_number(lhs) < get_layer_number(rhs);
        }
    };

    vector<Dictionary> collect_layer_definitions(const Dictionary& values)
    {
        vector<Dictionary> layer_definitions;

        for (const_each<DictionaryDictionary> i = values.dictionaries(); i; ++i)
            layer_definitions.push_back(i->value());

        sort(
            layer_definitions.begin(),
            layer_definitions.end(),
            LayerDefinitionOrderPredicate());

        return layer_definitions;
    }
}

DisneyMaterialCustomUI::DisneyMaterialCustomUI(
    const Project&      project,
    ParamArray&         settings)
  : m_project(project)
  , m_settings(settings)
  , m_parent(0)
  , m_layout(0)
{
}

void DisneyMaterialCustomUI::create_widgets(
    QVBoxLayout*        layout,
    const Dictionary&   values)
{
    m_parent = layout->parentWidget();
    m_layout = layout;

    // Add New Layer button.
    m_add_layer_button = new QPushButton("Add New Layer");
    m_layout->addWidget(m_add_layer_button);
    connect(m_add_layer_button, SIGNAL(clicked()), this, SLOT(slot_add_layer()));

    // Stretcher at the bottom.
    m_layout->addStretch(1);

    const vector<Dictionary> layer_definitions = collect_layer_definitions(values);

    if (layer_definitions.empty())
    {
        // Insert the initial layer.
        append_new_layer(make_new_layer_values());
    }
    else
    {
        for (const_each<vector<Dictionary> > i = layer_definitions; i; ++i)
            append_new_layer(*i);
    }
}

Dictionary DisneyMaterialCustomUI::get_values() const
{
    Dictionary values;

    for (size_t i = 0; i < m_layers.size(); ++i)
    {
        Dictionary layer_values = m_layers[i]->get_values();

        values.insert(
            layer_values.get<string>("layer_name"),
            layer_values.insert("layer_number", i));
    }

    return values;
}

void DisneyMaterialCustomUI::slot_add_layer()
{
    append_new_layer(make_new_layer_values());

    emit signal_apply();
}

void DisneyMaterialCustomUI::slot_move_layer_up(QWidget* layer_widget)
{
    const size_t layer_index = find_layer_index_by_widget(layer_widget);

    if (layer_index > 0)
    {
        swap(m_layers[layer_index], m_layers[layer_index - 1]);

        const int layer_widget_index = m_layout->indexOf(layer_widget);
        m_layout->takeAt(layer_widget_index);
        m_layout->insertWidget(layer_widget_index - 1, layer_widget);
    }

    emit signal_apply();
}

void DisneyMaterialCustomUI::slot_move_layer_down(QWidget* layer_widget)
{
    const size_t layer_index = find_layer_index_by_widget(layer_widget);

    if (layer_index < m_layers.size() - 1)
    {
        swap(m_layers[layer_index], m_layers[layer_index + 1]);

        const int layer_widget_index = m_layout->indexOf(layer_widget);
        m_layout->takeAt(layer_widget_index);
        m_layout->insertWidget(layer_widget_index + 1, layer_widget);
    }

    emit signal_apply();
}

void DisneyMaterialCustomUI::slot_delete_layer(QWidget* layer_widget)
{
    const size_t layer_index = find_layer_index_by_widget(layer_widget);

    m_layers.erase(m_layers.begin() + layer_index);

    m_layout->removeWidget(layer_widget);
    layer_widget->deleteLater();

    emit signal_apply();
}

size_t DisneyMaterialCustomUI::find_layer_index_by_widget(const QWidget* layer_widget) const
{
    for (size_t i = 0; i < m_layers.size(); ++i)
    {
        if (m_layers[i] == layer_widget)
            return i;
    }

    assert(!"Could not find layer widget.");
    return ~0;
}

vector<string> DisneyMaterialCustomUI::collect_layer_names() const
{
    vector<string> names;

    for (size_t i = 0; i < m_layers.size(); ++i)
        names.push_back(m_layers[i]->get_values().get<string>("layer_name"));

    return names;
}

Dictionary DisneyMaterialCustomUI::make_new_layer_values()
{
    return
        DisneyMaterialLayer::get_default_values()
            .insert("layer_name", make_unique_name("layer", collect_layer_names()));
}

void DisneyMaterialCustomUI::append_new_layer(const Dictionary& values)
{
    DisneyMaterialLayerUI* layer_widget =
        new DisneyMaterialLayerUI(m_parent, m_project, m_settings, values);

    connect(
        layer_widget, SIGNAL(signal_move_layer_up(QWidget*)),
        this, SLOT(slot_move_layer_up(QWidget*)));
    connect(
        layer_widget, SIGNAL(signal_move_layer_down(QWidget*)),
        this, SLOT(slot_move_layer_down(QWidget*)));
    connect(
        layer_widget, SIGNAL(signal_delete_layer(QWidget*)),
        this, SLOT(slot_delete_layer(QWidget*)));
    connect(
        layer_widget, SIGNAL(signal_apply()),
        this, SIGNAL(signal_apply()));

    m_layers.push_back(layer_widget);

    m_layout->insertWidget(m_layout->count() - 2, layer_widget);
}

}   // namespace studio
}   // namespace appleseed


text:
import os
import sys
from base import BaseBuild
from pony_barn import client as pony
from django.template import Template, Context
from django.conf import settings

class DjangoBuild(BaseBuild):
    """
    A build that sets up a django settings file for you
    """

    def __init__(self):
        super(DjangoBuild, self).__init__()
        self.directory = os.path.dirname(os.path.abspath(__file__))
        self.settings_file = os.path.join(self.directory, 'settings', 'base_settings.py')
        self.required = ['django']
        self.installed_apps = []

    def add_options(self):
        super(DjangoBuild, self).add_options()

        self.cmdline.add_option('-d', '--db',
                           choices=['sqlite', 'postgres', 'mysql'], default=None,
                           help='Which database backend to use.')
        self.cmdline.add_option('--name', default='pony_build_test',
                           help='Database name to use')

    def setup(self):
        #Setup Database
        name = self.options.name

        db = self.options.db
        if db is None:
            if hasattr(self, 'default_db'):
                print "Using Default DB"
                db = self.default_db
            else:
                db = 'sqlite'

        if db == 'sqlite':
            self.db_engine = 'sqlite3'
            self.db_name = name
            self.db_user = ''
            self.db_pass = ''
        elif db == 'postgres':
            self.db_engine = 'postgresql_psycopg2'
            self.db_name = name
            self.db_user = ''
            self.db_pass = ''
        elif db == 'mysql':
            self.db_engine = 'mysql'
            self.db_name = name
            self.db_user = ''
            self.db_pass = ''

        self.tags.append(db)

        # Create the settings file
        self.settings_path = "pony_barn_test_settings"
        dest_dir = os.path.join(self.context.tempdir, 'lib', self.py_name, 'site-packages')
        settings_dest = os.path.join(dest_dir, '%s.py' % self.settings_path)
        init_dest = os.path.join(dest_dir, '__init__.py')
        settings_template = open(self.settings_file).read()
        context = Context({
            'more_installed': self.installed_apps,
            'db_engine': self.db_engine,
            'db_name': self.db_name,
            'db_user': self.db_user,
            'db_pass': self.db_pass,
        })
        #Templates needs settings... :/
        if not settings.configured:
            settings.configure()
        rendered = Template(settings_template).render(context)
        open(settings_dest, 'w').write(rendered)
        open(init_dest, 'w').write('#OMG')
        sys.path.insert(0, dest_dir)

class DjangoVCSBuild(DjangoBuild):
    """
    A build that checkouts out from a repo and then runs manage.py test
    on your application
    """

    def define_commands(self):
        self.commands = [
            self.vcs_class(self.repo_url, egg=self.get_name()),
            pony.BuildCommand([self.context.python, 'setup.py', 'install'], name='Install'),
            pony.BuildCommand([self.context.djangoadmin, 'syncdb', '--noinput', '--settings', self.settings_path], name='Syncdb'),
            pony.TestCommand([self.context.djangoadmin, 'test', self.get_name(), '--settings', self.settings_path], name='run tests')
            ]

class DjangoGitBuild(DjangoVCSBuild):
    """
    A build that checkouts out from a git repo and then runs manage.py test
    on your application
    """
    vcs = 'git'

class DjangoHgBuild(DjangoVCSBuild):
    """
    A build that checkouts out from a hg repo and then runs manage.py test
    on your application
    """
    vcs = 'hg'

class DjangoSvnBuild(DjangoVCSBuild):
    """
    A build that checkouts out from a svn repo and then runs manage.py test
    on your application
    """
    vcs = 'svn'


text:
Shadowsocks client implement in Lua, based on my libuv binding.

Usage: luajit Shadowsocks.lua local.json

The json file is compatible with the official one.

# TODOs:

I will implement these functions one-by-one:

1. iptables-based transparent proxy on Linux
2. dynamic proxying without PAC files
3. Add a web UI to manage it
4. Shadowsocks server with Web UI authentication
5. Easy-to-deploy scripts

# Benchmarking

I wrote a server that prints how many client it has accepted after 10 seconds and sends 20000 SOCKS5 connect request to the Shadowsocks client. The Shadowsocks server is the official python server.py. Here are the results:

## This implement

luajit 59.9 MiB
server 110.2 MiB

Got 16669 connections.

## Python implement

local 58.8 MiB
server 66.7 MiB

Got 9056 connections.


text:
/**
 * Module dependencies.
 */

var express = require('express');
var MongoStore = require('connect-mongo')(express);
var flash = require('express-flash');
var less = require('less-middleware');
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var expressValidator = require('express-validator');
var argv = require('optimist').argv;
var timeago = require('timeago');

/**
 * Create Express server.
 */

var app = express();

/**
 * Load controllers.
 */

var homeController = require('./controllers/home');
var userController = require('./controllers/user');
var apiController = require('./controllers/api');
var contactController = require('./controllers/contact');
var newsController = require('./controllers/news');

/**
 * API keys + Passport configuration.
 */

var secrets = require('./config/secrets');
var passportConf = require('./config/passport');

/**
 * Mongoose configuration.
 */

mongoose.connect(secrets.db);
mongoose.connection.on('error', function() {
  console.log('✗ MongoDB Connection Error. Please make sure MongoDB is running.'.red);
});

/**
 * Express configuration.
 */

var hour = 3600000;
var day = (hour * 24);
var week = (day * 7);
var month = (day * 30);

app.locals.cacheBuster = Date.now();
app.set('port', process.env.PORT || argv.p || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.compress());
app.use(express.favicon(path.join(__dirname, 'public/img/favicon.ico')));
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(expressValidator());
app.use(express.methodOverride());
app.use(express.session({
  secret: 'your secret code',
  store: new MongoStore({
    db: mongoose.connection.db,
    auto_reconnect: true
  })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
  res.locals.user = req.user;

  res.setHeader("Content-Security-Policy", "script-src 'self' https://apis.google.com; frame-src 'none';");

  res.setHeader("X-Frame-Options", "DENY");

  next();
});
app.use(flash());
app.use(less({ src: __dirname + '/public', compress: true }));
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public'), { maxAge: week }));
app.use(function(req, res) {
  res.render('404', { status: 404 });
});
app.use(function(err, req, res, next){
  console.error("req: "+req +"\nerror:"+err.stack);
  res.statusCode = 500;
  res.render('error',{error:err});
});

app.locals.timeago = timeago;

/**
 * Application routes.
 */

/**
 * Sign in / out Routes
 */
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.get('/logout', userController.logout);

/**
 * Static Page Routes
 */

app.get('/about', homeController.about);
app.get('/bookmarklet', homeController.bookmarklet);
app.get('/signup', homeController.signup);

/**
 * Contact Routes
 */

app.get('/contact', contactController.getContact);
app.post('/contact', contactController.postContact);

/**
 * User Account Routes
 */

app.get('/', newsController.index);
app.get('/account', passportConf.isAuthenticated, userController.getAccount);
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);

/**
 * News Routes
 */

app.get('/news', newsController.index);
app.get('/news/submit', passportConf.isAuthenticated, newsController.submitNews);
app.post('/news/submit', passportConf.isAuthenticated, newsController.postNews);

app.get('/news/summarize', passportConf.isAuthenticated, newsController.summarize);

app.get('/news/source/:source', newsController.sourceNews);
app.get('/news/:id', newsController.comments);
app.post('/news/:id/comments', newsController.postComment);
app.post('/news/:id', newsController.vote);
app.get('/news/user/:id', newsController.userNews);

/**
 * API Routes
 */

app.get('/api', apiController.getApi);
app.get('/api/foursquare', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFoursquare);
app.get('/api/tumblr', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTumblr);
app.get('/api/facebook', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getFacebook);
app.get('/api/scraping', apiController.getScraping);
app.get('/api/github', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getGithub);
app.get('/api/lastfm', apiController.getLastfm);
app.get('/api/nyt', apiController.getNewYorkTimes);
app.get('/api/twitter', passportConf.isAuthenticated, passportConf.isAuthorized, apiController.getTwitter);
app.get('/api/aviary', apiController.getAviary);
app.get('/api/paypal', apiController.getPayPal);
app.get('/api/paypal/success', apiController.getPayPalSuccess);
app.get('/api/paypal/cancel', apiController.getPayPalCancel);

/**
 * OAuth routes for sign-in.
 */

app.get('/auth/facebook', passport.authenticate('facebook', { scope: 'email' }));
app.get('/auth/facebook/callback', passport.authenticate('facebook', { successRedirect: '/', failureRedirect: '/login' }));
app.get('/auth/github', passport.authenticate('github'));
app.get('/auth/github/callback', passport.authenticate('github', { successRedirect: '/', failureRedirect: '/login' }));
app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' }));
app.get('/auth/google/callback', passport.authenticate('google', { successRedirect: '/', failureRedirect: '/login' }));
app.get('/auth/twitter', passport.authenticate('twitter'));
app.get('/auth/twitter/callback', passport.authenticate('twitter', { successRedirect: '/', failureRedirect: '/login' }));

/**
 * OAuth routes for API examples that require authorization.
 */

app.get('/auth/foursquare', passport.authorize('foursquare'));
app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/foursquare');
});
app.get('/auth/tumblr', passport.authorize('tumblr'));
app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) {
  res.redirect('/api/tumblr');
});

app.listen(app.get('port'), function() {
  console.log("✔ Express server listening on port %d in %s mode", app.get('port'), app.settings.env);
});


text:
#ifndef _EPINFERENCEMETHOD_H_
#define _EPINFERENCEMETHOD_H_

#include <shogun/lib/config.h>

#include <shogun/machine/gp/Inference.h>
#include <shogun/mathematics/RandomMixin.h>

namespace shogun
{

/** @brief Class of the Expectation Propagation (EP) posterior approximation
 * inference method.
 *
 * For more details, see: Minka, T. P. (2001). A Family of Algorithms for
 * Approximate Bayesian Inference. PhD thesis, Massachusetts Institute of
 * Technology
 */
class CEPInferenceMethod : public RandomMixin<CInference>
{
public:
	/** default constructor */
	CEPInferenceMethod();

	/** constructor
	 *
	 * @param kernel covariance function
	 * @param features features to use in inference
	 * @param mean mean function
	 * @param labels labels of the features
	 * @param model likelihood model to use
	 */
	CEPInferenceMethod(CKernel* kernel, CFeatures* features, CMeanFunction* mean,
			CLabels* labels, CLikelihoodModel* model);

	virtual ~CEPInferenceMethod();

	/** return what type of inference we are
	 *
	 * @return inference type EP
	 */
	virtual EInferenceType get_inference_type() const { return INF_EP; }

	/** returns the name of the inference method
	 *
	 * @return name EP
	 */
	virtual const char* get_name() const { return "EPInferenceMethod"; }

	/** helper method used to specialize a base class instance
	 *
	 * @param inference inference method
	 * @return casted CEPInferenceMethod object
	 */
	static CEPInferenceMethod* obtain_from_generic(CInference* inference);

	/** returns the negative logarithm of the marginal likelihood function:
	 *
	 * \f[
	 * -log(p(y|X, \theta))
	 * \f]
	 *
	 * where \f$y\f$ are the labels, \f$X\f$ are the features, and \f$\theta\f$
	 * represent hyperparameters.
	 *
	 * @return negative log marginal likelihood
	 */
	virtual float64_t get_negative_log_marginal_likelihood();

	/** returns vector to compute posterior mean of Gaussian Process under EP
	 * approximation:
	 *
	 * \f[
	 * \mathbb{E}_q[f_*|X,y,x_*] = k^T_*\alpha
	 * \f]
	 *
	 * where \f$k^T_*\f$ - covariance between training points \f$X\f$ and test
	 * point \f$x_*\f$, and for EP approximation:
	 *
	 * \f[
	 * \alpha = (K + \tilde{S}^{-1})^{-1}\tilde{S}^{-1}\tilde{\nu} =
	 * (I-\tilde{S}^{\frac{1}{2}}B^{-1}\tilde{S}^{\frac{1}{2}}K)\tilde{\nu}
	 * \f]
	 *
	 * where \f$K\f$ is the prior covariance matrix,
	 * \f$\tilde{S}^{\frac{1}{2}}\f$ is the diagonal matrix (see description of
	 * get_diagonal_vector() method) and \f$\tilde{\nu}\f$ - natural parameter
	 * (\f$\tilde{\nu} = \tilde{S}\tilde{\mu}\f$).
	 *
	 * @return vector \f$\alpha\f$
	 */
	virtual SGVector<float64_t> get_alpha();

	/** returns upper triangular factor \f$L^T\f$ of the Cholesky decomposition
	 * (\f$LL^T\f$) of the matrix:
	 *
	 * \f[
	 * B = (\tilde{S}^{\frac{1}{2}}K\tilde{S}^{\frac{1}{2}}+I)
	 * \f]
	 *
	 * where \f$\tilde{S}^{\frac{1}{2}}\f$ is the diagonal matrix (see
	 * description of get_diagonal_vector() method) and \f$K\f$ is the prior
	 * covariance matrix.

	 * @return upper triangular factor of the Cholesky decomposition of the
	 * matrix \f$B\f$
	 */
	virtual SGMatrix<float64_t> get_cholesky();

	/** returns diagonal vector of the diagonal matrix:
	 *
	 * \f[
	 * \tilde{S}^{\frac{1}{2}} = \sqrt{\tilde{S}}
	 * \f]
	 *
	 * where \f$\tilde{S} = \text{diag}(\tilde{\tau})\f$, and \f$\tilde{\tau}\f$
	 * - natural parameter (\f$\tilde{\tau}_i = \tilde{\sigma}_i^{-2}\f$).
	 *
	 * @return diagonal vector of the matrix \f$\tilde{S}^{\frac{1}{2}}\f$
	 */
	virtual SGVector<float64_t> get_diagonal_vector();

	/** returns mean vector \f$\mu\f$ of the Gaussian distribution
	 * \f$\mathcal{N}(\mu,\Sigma)\f$, which is an approximation to the
	 * posterior:
	 *
	 * \f[
	 * p(f|X,y) \approx q(f|X,y) = \mathcal{N}(f|\mu,\Sigma)
	 * \f]
	 *
	 * Mean vector \f$\mu\f$ is evaluated like:
	 *
	 * \f[
	 * \mu = \Sigma\tilde{\nu}
	 * \f]
	 *
	 * where \f$\Sigma\f$ - covariance matrix of the posterior approximation and
	 * \f$\tilde{\nu}\f$ - natural parameter (\f$\tilde{\nu} =
	 * \tilde{S}\tilde{\mu}\f$).
	 *
	 * @return mean vector \f$\mu\f$
	 */
	virtual SGVector<float64_t> get_posterior_mean();

	/** returns covariance matrix \f$\Sigma=(K^{-1}+\tilde{S})^{-1}\f$ of the
	 * Gaussian distribution \f$\mathcal{N}(\mu,\Sigma)\f$, which is an
	 * approximation to the posterior:
	 *
	 * \f[
	 * p(f|X,y) \approx q(f|X,y) = \mathcal{N}(f|\mu,\Sigma)
	 * \f]
	 *
	 * Covariance matrix \f$\Sigma\f$ is evaluated using matrix inversion lemma:
	 *
	 * \f[
	 * \Sigma = (K^{-1}+\tilde{S})^{-1} = K -
	 * K\tilde{S}^{\frac{1}{2}}B^{-1}\tilde{S}^{\frac{1}{2}}K
	 * \f]
	 *
	 * where \f$B=(\tilde{S}^{\frac{1}{2}}K\tilde{S}^{\frac{1}{2}}+I)\f$.
	 *
	 * @return covariance matrix \f$\Sigma\f$
	 */
	virtual SGMatrix<float64_t> get_posterior_covariance();

	/** returns tolerance of the EP approximation
	 *
	 * @return tolerance
	 */
	virtual float64_t get_tolerance() const { return m_tol; }

	/** sets tolerance of the EP approximation
	 *
	 * @param tol tolerance to set
	 */
	virtual void set_tolerance(const float64_t tol) { m_tol=tol; }

	/** returns minimum number of sweeps over all variables
	 *
	 * @return minimum number of sweeps
	 */
	virtual uint32_t get_min_sweep() const { return m_min_sweep; }

	/** sets minimum number of sweeps over all variables
	 *
	 * @param min_sweep minimum number of sweeps to set
	 */
	virtual void set_min_sweep(const uint32_t min_sweep) { m_min_sweep=min_sweep; }

	/** returns maximum number of sweeps over all variables
	 *
	 * @return maximum number of sweeps
	 */
	virtual uint32_t get_max_sweep() const { return m_max_sweep; }

	/** sets maximum number of sweeps over all variables
	 *
	 * @param max_sweep maximum number of sweeps to set
	 */
	virtual void set_max_sweep(const uint32_t max_sweep) { m_max_sweep=max_sweep; }

	/**
	 * @return whether combination of Laplace approximation inference method and
	 * given likelihood function supports binary classification
	 */
	virtual bool supports_binary() const
	{
		check_members();
		return m_model->supports_binary();
	}

	/** update all matrices Expect gradients*/
	virtual void update();

	/** Set a minimizer
	 *
	 * @param minimizer minimizer used in inference method
	 */
	virtual void register_minimizer(Minimizer* minimizer);

	/** Specify behavious when EP does not converge: failure or warning
	 * @param fail_on_non_convergence If True, throws error, otherwise prints warning
	 */
	void set_fail_on_non_convergence(bool fail_on_non_convergence)
	{
		m_fail_on_non_convergence = fail_on_non_convergence;
	}

protected:
	/** update gradients */
	virtual void compute_gradient();

	/** update alpha matrix */
	virtual void update_alpha();

	/** update Cholesky matrix */
	virtual void update_chol();

	/** update covariance matrix of the approximation to the posterior */
	virtual void update_approx_cov();

	/** update mean vector of the approximation to the posterior */
	virtual void update_approx_mean();

	/** update negative marginal likelihood */
	virtual void update_negative_ml();

	/** update matrices which are required to compute negative log marginal
	 * likelihood derivatives wrt hyperparameter
	 */
	virtual void update_deriv();

	/** returns derivative of negative log marginal likelihood wrt parameter of
	 * CInference class
	 *
	 * @param param parameter of CInference class
	 *
	 * @return derivative of negative log marginal likelihood
	 */
	virtual SGVector<float64_t> get_derivative_wrt_inference_method(
			const TParameter* param);

	/** returns derivative of negative log marginal likelihood wrt parameter of
	 * likelihood model
	 *
	 * @param param parameter of given likelihood model
	 *
	 * @return derivative of negative log marginal likelihood
	 */
	virtual SGVector<float64_t> get_derivative_wrt_likelihood_model(
			const TParameter* param);

	/** returns derivative of negative log marginal likelihood wrt kernel's
	 * parameter
	 *
	 * @param param parameter of given kernel
	 *
	 * @return derivative of negative log marginal likelihood
	 */
	virtual SGVector<float64_t> get_derivative_wrt_kernel(
			const TParameter* param);

	/** returns derivative of negative log marginal likelihood wrt mean
	 * function's parameter
	 *
	 * @param param parameter of given mean function
	 *
	 * @return derivative of negative log marginal likelihood
	 */
	virtual SGVector<float64_t> get_derivative_wrt_mean(
			const TParameter* param);

private:
	void init();

private:
	/** mean vector of the approximation to the posterior */
	SGVector<float64_t> m_mu;

	/** covariance matrix of the approximation to the posterior */
	SGMatrix<float64_t> m_Sigma;

	/** negative marginal likelihood */
	float64_t m_nlZ;

	/** vector of natural parameters \f$\tilde{\nu} = \tilde{S}\tilde{\mu}\f$,
	 * where \f$\tilde{S} = \text{diag}(\tilde{\tau})\f$
	 */
	SGVector<float64_t> m_tnu;

	/** vector of natural parameters \f$\tilde{\tau}_i =
	 * \tilde{\sigma}_i^{-2}\f$
	 */
	SGVector<float64_t> m_ttau;

	/** square root of the \f$\tilde{\tau}\f$ vector */
	SGVector<float64_t> m_sttau;

	/** tolerance of the EP approximation */
	float64_t m_tol;

	/** minimum number of sweeps over all variables */
	uint32_t m_min_sweep;

	/** maximum number of sweeps over all variables */
	uint32_t m_max_sweep;

	/** flag whether to show error or warning when not-converging */
	bool m_fail_on_non_convergence;

	SGMatrix<float64_t> m_F;
};
}
#endif /* _EPINFERENCEMETHOD_H_ */


text:
#include "mumble_pch.hpp"
#include "Global.h"
#include "MainWindow.h"

char *os_url = NULL;
char *os_lang = NULL;
static FILE *fConsole = NULL;

#ifdef __x86_64__
#define SCREWAPPLE  void *
#else
#define SCREWAPPLE  long
#endif

#define PATH_MAX 1024
static char crashhandler_fn[PATH_MAX];

static void crashhandler_signals_restore();
static void crashhandler_handle_crash();

static OSErr urlCallback(const AppleEvent *ae, AppleEvent *, SCREWAPPLE) {
	OSErr err;
	DescType type;
	Size dataSize, size;
	static char url[1024];

	err = AESizeOfParam(ae, keyDirectObject, &type, &dataSize);
	if (err != noErr)
		return err;

	memset(url, 0, 1024);
	if (dataSize > 1023)
		dataSize = 1023;

	err = AEGetParamPtr(ae, keyDirectObject, typeChar, &type, url, dataSize, &size);
	if (err != noErr)
		return err;

	/*
	 * Determine whether a mumble:// URL invoked a Mumble launch
	 * of if we were already running beforehand.
	 */
	if (g.mw)
		g.mw->openUrl(QUrl::fromEncoded(QByteArray(url)));
	else
		os_url = url;

	return noErr;
}

static void mumbleMessageOutput(QtMsgType type, const char *msg) {
	char c;

	switch (type) {
		case QtDebugMsg:
			c='D';
			break;
		case QtWarningMsg:
			c='W';
			break;
		case QtFatalMsg:
			c='F';
			break;
		default:
			c='X';
	}

#define LOG(f, msg) fprintf(f, "<%c>%s %s\n", c, \
		qPrintable(QDateTime::currentDateTime().toString(QLatin1String("yyyy-MM-dd hh:mm:ss.zzz"))), msg)

	LOG(stderr, msg);
	LOG(fConsole, msg);
	fflush(fConsole);

	if (type == QtFatalMsg) {
		CFStringRef csMsg = CFStringCreateWithFormat(kCFAllocatorDefault, NULL, CFSTR("%s\n\nThe error has been logged. Please submit your log file to the Mumble project if the problem persists."), msg);
		CFUserNotificationDisplayAlert(0, 0, NULL,  NULL, NULL, CFSTR("Mumble has encountered a fatal error"), csMsg, CFSTR("OK"), NULL, NULL, NULL);
		CFRelease(csMsg);
		exit(0);
	}
}

void query_language() {
	CFPropertyListRef cfaLangs;
	CFStringRef cfsLang;
	static char lang[16];

	cfaLangs = CFPreferencesCopyAppValue(CFSTR("AppleLanguages"), kCFPreferencesCurrentApplication);
	cfsLang = (CFStringRef) CFArrayGetValueAtIndex((CFArrayRef)cfaLangs, 0);

	if (! CFStringGetCString(cfsLang, lang, 16, kCFStringEncodingUTF8))
		return;

	os_lang = lang;
}

static void crashhandler_signal_handler(int signal) {
	switch (signal) {
		case SIGQUIT:
		case SIGILL:
		case SIGTRAP:
		case SIGABRT:
		case SIGEMT:
		case SIGFPE:
		case SIGBUS:
		case SIGSEGV:
		case SIGSYS:
			crashhandler_signals_restore();
			crashhandler_handle_crash();
			break;
		default:
			break;
	}
}

/* These are the signals that according to signal(3) produce a coredump by default. */
int sigs[] = { SIGQUIT, SIGILL, SIGTRAP, SIGABRT, SIGEMT, SIGFPE, SIGBUS, SIGSEGV, SIGSYS };
#define NSIGS sizeof(sigs)/sizeof(sigs[0])

static void crashhandler_signals_setup() {
	for (int i = 0; i < NSIGS; i++) {
		signal(sigs[i], crashhandler_signal_handler);
	}
}

static void crashhandler_signals_restore() {
	for (int i = 0; i < NSIGS; i++) {
		signal(sigs[i], NULL);
	}
}

static void crashhandler_init() {
#ifdef COMPAT_CLIENT
	QString dump = QDir::homePath() + QLatin1String("/Library/Preferences/Mumble/mumble11x.dmp");
#else
	QString dump = g.qdBasePath.filePath(QLatin1String("mumble.dmp"));
#endif
	if (strncpy(crashhandler_fn, dump.toUtf8().data(), PATH_MAX)) {
		crashhandler_signals_setup();
		/* todo: Change the behavior of the Apple crash dialog? Maybe? */
	}
}

static void crashhandler_handle_crash() {
	/* Abuse mtime for figuring out which crashdump we should send. */
	FILE *f = fopen(crashhandler_fn, "w");
	fflush(f);
	fclose(f);
}

void os_init() {
	crashhandler_init();

	const char *home = getenv("HOME");
#ifdef COMPAT_CLIENT
	const char *logpath = "/Library/Logs/Mumble11x.log";
#else
	const char *logpath = "/Library/Logs/Mumble.log";
#endif

	if (home) {
		size_t len = strlen(home) + strlen(logpath) + 1;
		STACKVAR(char, buff, len);
		memset(buff, 0, len);
		strcat(buff, home);
		strcat(buff, logpath);
		fConsole = fopen(buff, "a+");
		if (fConsole)
			qInstallMsgHandler(mumbleMessageOutput);
	}

	/* Query for language setting. OS X's LANG environment variable is determined from the region selected
	 * in SystemPrefs -> International -> Formats -> Region instead of the system language. We override this
	 * by always using the system langauge, to get rid of all sorts of nasty langauge inconsistencies. */
	query_language();

	/* Install Apple Event handler for GURL events. This intercepts any URLs set in Mumble's Info.plist. */
	AEInstallEventHandler(kInternetEventClass, kAEGetURL, NewAEEventHandlerUPP(urlCallback), 0, false);
}


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.camunda.bpm.cockpit.plugin.dashboards.resources;

import javax.ws.rs.Path;
import javax.ws.rs.PathParam;

import org.camunda.bpm.cockpit.plugin.dashboards.DashboardsPlugin;
import org.camunda.bpm.cockpit.plugin.resource.AbstractCockpitPluginRootResource;

@Path("plugin/" + DashboardsPlugin.ID)
public class DashboardsRootResource extends AbstractCockpitPluginRootResource {

  public DashboardsRootResource() {
    super(DashboardsPlugin.ID);
  }

  @Path("{engineName}"+SearchResource.PATH)
  public SearchResource search(@PathParam("engineName") String engineName) {
    return subResource(new SearchResource(engineName), engineName);
  }

  @Path("{engineName}"+ProcessInstanceHistogramResource.PATH)
  public ProcessInstanceHistogramResource dateHistogram(@PathParam("engineName") String engineName) {
    return subResource(new ProcessInstanceHistogramResource(engineName), engineName);
  }
}


text:
set :css_dir, 'stylesheets'

set :js_dir, 'javascripts'

set :images_dir, 'images'

# Build-specific configuration
configure :build do
  # For example, change the Compass output style for deployment
  # activate :minify_css

  # Minify Javascript on build
  # activate :minify_javascript

  # Enable cache buster
  # activate :asset_hash

  activate :relative_assets
  set :relative_links, true

  # Or use a different image path
  # set :http_prefix, "/Content/images/"
end


text:
#ifndef OVR_Lockless_h
#define OVR_Lockless_h

#include <cstring>
using std::memcpy;

#include "OVR_Atomic.h"

// Define this to compile-in Lockless test logic
//#define OVR_LOCKLESS_TEST

namespace OVR {

// ***** LocklessUpdater

// For single producer cases where you only care about the most recent update, not
// necessarily getting every one that happens (vsync timing, SensorFusion updates).
//
// This is multiple consumer safe, but is currently only used with a single consumer.
//
// The SlotType can be the same as T, but should probably be a larger fixed size.
// This allows for forward compatibility when the updater is shared between processes.

template <class T, class SlotType = T>
class LocklessUpdater {
 public:
  LocklessUpdater() {
    OVR_COMPILER_ASSERT(sizeof(T) <= sizeof(SlotType));
  }

  T GetState() const {
    // Copy the state out, then retry with the alternate slot
    // if we determine that our copy may have been partially
    // stepped on by a new update.
    T state;
    int begin, end, final;

    for (;;) {
      // We are adding 0, only using these as atomic memory barriers, so it
      // is ok to cast off the const, allowing GetState() to remain const.
      end = UpdateEnd.load(std::memory_order_acquire);
      state = Slots[end & 1];
      begin = UpdateBegin.load(std::memory_order_acquire);
      if (begin == end) {
        break;
      }

      // The producer is potentially blocked while only having partially
      // written the update, so copy out the other slot.
      state = Slots[(begin & 1) ^ 1];
      final = UpdateBegin.load(std::memory_order_acquire);
      if (final == begin) {
        break;
      }

      // The producer completed the last update and started a new one before
      // we got it copied out, so try fetching the current buffer again.
    }
    return state;
  }

  void SetState(const T& state) {
    const int slot = UpdateBegin.fetch_add(1) & 1;
    // Write to (slot ^ 1) because ExchangeAdd returns 'previous' value before add.
    Slots[slot ^ 1] = state;
    UpdateEnd.fetch_add(1);
  }

  std::atomic<int> UpdateBegin = {0};
  std::atomic<int> UpdateEnd = {0};
  SlotType Slots[2];
};

#pragma pack(push, 8)

// Padded out version stored in the updater slots
// Designed to be a larger fixed size to allow the data to grow in the future
// without breaking older compiled code.
OVR_DISABLE_MSVC_WARNING(4351)
template <class Payload, int PaddingSize>
struct LocklessPadding {
  uint8_t buffer[PaddingSize];

  LocklessPadding() : buffer() {}

  LocklessPadding& operator=(const Payload& rhs) {
    // if this fires off, then increase PaddingSize
    // IMPORTANT: this WILL break backwards compatibility
    static_assert(sizeof(buffer) >= sizeof(Payload), "PaddingSize is too small");

    memcpy(buffer, &rhs, sizeof(Payload));
    return *this;
  }

  operator Payload() const {
    Payload result;
    memcpy(&result, buffer, sizeof(Payload));
    return result;
  }
};
OVR_RESTORE_MSVC_WARNING()

#pragma pack(pop)

} // namespace OVR

#endif // OVR_Lockless_h


text:
var path       = require("path"),
    fs         = require("fs"),
    nomnom     = require("nomnom"),
    yawp       = require("./yawp"),
    configPath = "./.yawpfile",
    config     = {};

// Configuration file
nomnom.option("config", {
    abbr      : "c",
    help      : "Yawp run configuration file",
    default   : "./.yawpfile",
    transform : function(loc) {
        if(!loc) return;
        configPath = loc; //JSON.parse(fs.readFileSync(path.resolve(loc), "utf8"));
        return loc;
    }
});

// Json source file
nomnom.option("source", {
    abbr      : "s",
    help      : "Path to JSON source file"
});

// Directory to putput to
nomnom.option("output", {
    abbr      : "o",
    help      : "Path to output file"
});

// Name of initial template
nomnom.option("template", {
    abbr      : "t",
    help      : "Name of main template"
});

// Path to template directory
nomnom.option("template-dir", {
    abbr      : "td",
    help      : "Path to templates directory"
});

function checkConfig(opts) {
    var valid = ["source", "output", "template-dir"];

    valid = valid.every(function(name) {
        var loc;

        if(loc = opts[name]) {
            config[name] = path.resolve(loc);
        } else if(loc = config[name]) {
            config[name] = path.resolve(loc);
        }

        return !!loc;
    });

    return valid;
}

config = JSON.parse(fs.readFileSync(path.resolve(configPath), "utf8"));

if(checkConfig(nomnom.parse())) {
    yawp.run(config);
}


text:
#ifndef CAFFE_OPTIMIZATION_SOLVER_HPP_
#define CAFFE_OPTIMIZATION_SOLVER_HPP_

#include <string>
#include <vector>

#include "caffe/net.hpp"

namespace caffe {

/**
 * @brief An interface for classes that perform optimization on Net%s.
 *
 * Requires implementation of ApplyUpdate to compute a parameter update
 * given the current state of the Net parameters.
 */
template <typename Dtype>
class Solver {
 public:
  explicit Solver(const SolverParameter& param,
      const Solver* root_solver = NULL);
  explicit Solver(const string& param_file, const Solver* root_solver = NULL);
  void Init(const SolverParameter& param);
  void InitTrainNet();
  void InitTestNets();
  // The main entry of the solver function. In default, iter will be zero. Pass
  // in a non-zero iter number to resume training for a pre-trained net.
  virtual void Solve(const char* resume_file = NULL);
  inline void Solve(const string resume_file) { Solve(resume_file.c_str()); }
  void Step(int iters);
  // The Restore method simply dispatches to one of the
  // RestoreSolverStateFrom___ protected methods. You should implement these
  // methods to restore the state from the appropriate snapshot type.
  void Restore(const char* resume_file);
  virtual ~Solver() {}
  inline const SolverParameter& param() const { return param_; }
  inline shared_ptr<Net<Dtype> > net() { return net_; }
  inline const vector<shared_ptr<Net<Dtype> > >& test_nets() {
    return test_nets_;
  }
  int iter() { return iter_; }

  // Invoked at specific points during an iteration
  class Callback {
   protected:
    virtual void on_start() = 0;
    virtual void on_gradients_ready() = 0;

    template <typename T>
    friend class Solver;
  };
  const vector<Callback*>& callbacks() const { return callbacks_; }
  void add_callback(Callback* value) {
    callbacks_.push_back(value);
  }

 protected:
  // Make and apply the update value for the current iteration.
  virtual void ApplyUpdate() = 0;
  // The Solver::Snapshot function implements the basic snapshotting utility
  // that stores the learned net. You should implement the SnapshotSolverState()
  // function that produces a SolverState protocol buffer that needs to be
  // written to disk together with the learned net.
  void Snapshot();
  string SnapshotFilename(const string extension);
  string SnapshotToBinaryProto();
  string SnapshotToHDF5();
  // The test routine
  void TestAll();
  void Test(const int test_net_id = 0);
  virtual void SnapshotSolverState(const string& model_filename) = 0;
  virtual void RestoreSolverStateFromHDF5(const string& state_file) = 0;
  virtual void RestoreSolverStateFromBinaryProto(const string& state_file) = 0;
  void DisplayOutputBlobs(const int net_id);

  SolverParameter param_;
  int iter_;
  int current_step_;
  shared_ptr<Net<Dtype> > net_;
  vector<shared_ptr<Net<Dtype> > > test_nets_;
  vector<Callback*> callbacks_;

  // The root solver that holds root nets (actually containing shared layers)
  // in data parallelism
  const Solver* const root_solver_;

  DISABLE_COPY_AND_ASSIGN(Solver);
};

/**
 * @brief Solver that only computes gradients, used as worker
 *        for multi-GPU training.
 */
template <typename Dtype>
class WorkerSolver : public Solver<Dtype> {
 public:
  explicit WorkerSolver(const SolverParameter& param,
      const Solver<Dtype>* root_solver = NULL)
      : Solver<Dtype>(param, root_solver) {}

 protected:
  void ApplyUpdate() {}
  void SnapshotSolverState(const string& model_filename) {
    LOG(FATAL) << "Should not be called on worker solver.";
  }
  void RestoreSolverStateFromBinaryProto(const string& state_file) {
    LOG(FATAL) << "Should not be called on worker solver.";
  }
  void RestoreSolverStateFromHDF5(const string& state_file) {
    LOG(FATAL) << "Should not be called on worker solver.";
  }
};

/**
 * @brief Optimizes the parameters of a Net using
 *        stochastic gradient descent (SGD) with momentum.
 */
template <typename Dtype>
class SGDSolver : public Solver<Dtype> {
 public:
  explicit SGDSolver(const SolverParameter& param)
      : Solver<Dtype>(param) { PreSolve(); }
  explicit SGDSolver(const string& param_file)
      : Solver<Dtype>(param_file) { PreSolve(); }

  const vector<shared_ptr<Blob<Dtype> > >& history() { return history_; }

 protected:
  void PreSolve();
  Dtype GetLearningRate();
  virtual void ApplyUpdate();
  virtual void Normalize(int param_id);
  virtual void Regularize(int param_id);
  virtual void ComputeUpdateValue(int param_id, Dtype rate);
  virtual void ClipGradients();
  virtual void SnapshotSolverState(const string& model_filename);
  virtual void SnapshotSolverStateToBinaryProto(const string& model_filename);
  virtual void SnapshotSolverStateToHDF5(const string& model_filename);
  virtual void RestoreSolverStateFromHDF5(const string& state_file);
  virtual void RestoreSolverStateFromBinaryProto(const string& state_file);
  // history maintains the historical momentum data.
  // update maintains update related data and is not needed in snapshots.
  // temp maintains other information that might be needed in computation
  //   of gradients/updates and is not needed in snapshots
  vector<shared_ptr<Blob<Dtype> > > history_, update_, temp_;

  DISABLE_COPY_AND_ASSIGN(SGDSolver);
};

template <typename Dtype>
class NesterovSolver : public SGDSolver<Dtype> {
 public:
  explicit NesterovSolver(const SolverParameter& param)
      : SGDSolver<Dtype>(param) {}
  explicit NesterovSolver(const string& param_file)
      : SGDSolver<Dtype>(param_file) {}

 protected:
  virtual void ComputeUpdateValue(int param_id, Dtype rate);

  DISABLE_COPY_AND_ASSIGN(NesterovSolver);
};

template <typename Dtype>
class AdaGradSolver : public SGDSolver<Dtype> {
 public:
  explicit AdaGradSolver(const SolverParameter& param)
      : SGDSolver<Dtype>(param) { constructor_sanity_check(); }
  explicit AdaGradSolver(const string& param_file)
      : SGDSolver<Dtype>(param_file) { constructor_sanity_check(); }

 protected:
  virtual void ComputeUpdateValue(int param_id, Dtype rate);
  void constructor_sanity_check() {
    CHECK_EQ(0, this->param_.momentum())
        << "Momentum cannot be used with AdaGrad.";
  }

  DISABLE_COPY_AND_ASSIGN(AdaGradSolver);
};

template <typename Dtype>
class RMSPropSolver : public SGDSolver<Dtype> {
 public:
  explicit RMSPropSolver(const SolverParameter& param)
      : SGDSolver<Dtype>(param) { constructor_sanity_check(); }
  explicit RMSPropSolver(const string& param_file)
      : SGDSolver<Dtype>(param_file) { constructor_sanity_check(); }

 protected:
  virtual void ComputeUpdateValue(int param_id, Dtype rate);
  void constructor_sanity_check() {
    CHECK_EQ(0, this->param_.momentum())
        << "Momentum cannot be used with RMSProp.";
    CHECK_GE(this->param_.rms_decay(), 0)
        << "rms_decay should lie between 0 and 1.";
    CHECK_LT(this->param_.rms_decay(), 1)
        << "rms_decay should lie between 0 and 1.";
  }

  DISABLE_COPY_AND_ASSIGN(RMSPropSolver);
};

template <typename Dtype>
class AdaDeltaSolver : public SGDSolver<Dtype> {
 public:
  explicit AdaDeltaSolver(const SolverParameter& param)
      : SGDSolver<Dtype>(param) { AdaDeltaPreSolve(); }
  explicit AdaDeltaSolver(const string& param_file)
      : SGDSolver<Dtype>(param_file) { AdaDeltaPreSolve(); }

 protected:
  void AdaDeltaPreSolve();
  virtual void ComputeUpdateValue(int param_id, Dtype rate);

  DISABLE_COPY_AND_ASSIGN(AdaDeltaSolver);
};

template <typename Dtype>
Solver<Dtype>* GetSolver(const SolverParameter& param) {
  SolverParameter_SolverType type = param.solver_type();

  switch (type) {
  case SolverParameter_SolverType_SGD:
      return new SGDSolver<Dtype>(param);
  case SolverParameter_SolverType_NESTEROV:
      return new NesterovSolver<Dtype>(param);
  case SolverParameter_SolverType_ADAGRAD:
      return new AdaGradSolver<Dtype>(param);
  case SolverParameter_SolverType_RMSPROP:
      return new RMSPropSolver<Dtype>(param);
  case SolverParameter_SolverType_ADADELTA:
      return new AdaDeltaSolver<Dtype>(param);
  default:
      LOG(FATAL) << "Unknown SolverType: " << type;
  }
  return (Solver<Dtype>*) NULL;
}

}  // namespace caffe

#endif  // CAFFE_OPTIMIZATION_SOLVER_HPP_


text:
package com.vmware.fdmsecprotomgmt;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ResultTablePrinter
{
    List<List<String>> lines = new ArrayList<>();
    List<Integer> maxLengths = new ArrayList<>();
    int numColumns = -1;

    public ResultTablePrinter addLine(String... line) {

        if (numColumns == -1){
            numColumns = line.length;
            for(int i = 0; i < numColumns; i++) {
                maxLengths.add(0);
            }
        }

        if (numColumns != line.length) {
            throw new IllegalArgumentException();
        }

        for(int i = 0; i < numColumns; i++) {
            maxLengths.set(  i, Math.max( maxLengths.get(i), line[i].length() )  );
        }

        lines.add( Arrays.asList(line) );

        return this;
    }

    public void print(){
        System.out.println( toString() );
    }

    @Override
    public String toString(){
        String result = "";
        for(List<String> line : lines) {
            for(int i = 0; i < numColumns; i++) {
                result += pad( line.get(i), maxLengths.get(i) + 1 );
            }
            result += System.lineSeparator();
        }
        return result;
    }

    private String pad(String word, int newLength){
        while (word.length() < newLength) {
            word += " ";
        }
        return word;
    }
}


text:
template <unsigned rank>
class Tensor
{
};

template <unsigned rank>
class Tensor<2> : Tensor<rank> { // { dg-error "" } template parameters not used
};


text:
package org.codehaus.groovy.vmplugin.v7;

import java.lang.invoke.MethodType;
import java.math.BigDecimal;
import java.math.BigInteger;

/**
 * This class contains helper methods for converting and comparing types.
 * WARNING: This class is for internal use only. do not use it outside of its
 * package and not outside groovy-core.
 * @author Jochen "blackdrag" Theodorou
 */
public class TypeHelper {
    /**
     * Get wrapper class for a given class.
     * If the class is for a primitive number type, then the wrapper class
     * will be returned. If it is no primitive number type, we return the
     * class itself.
     */
    protected static Class getWrapperClass(Class c) {
        if (c == Integer.TYPE) {
            c = Integer.class;
        } else if (c == Byte.TYPE) {
            c = Byte.class;
        } else if (c == Long.TYPE) {
            c = Long.class;
        } else if (c == Double.TYPE) {
            c = Double.class;
        } else if (c == Float.TYPE) {
            c = Float.class;
        } else if (c == Boolean.TYPE) {
            c = Boolean.class;
        } else if (c == Character.TYPE) {
            c = Character.class;
        } else if (c == Short.TYPE) {
            c = Short.class;
        }
        return c;
    }

    /**
     * Realizes an unsharp equal for the class.
     * In general we return true if the provided arguments are the same. But
     * we will also return true if our argument class is a wrapper for
     * the parameter class. For example the parameter is an int and the
     * argument class is a wrapper.
     */
    protected static boolean argumentClassIsParameterClass(Class argumentClass, Class parameterClass) {
        if (argumentClass == parameterClass) return true;
        if (getWrapperClass(parameterClass) == argumentClass) return true;
        return false;
    }

    /**
     * Replaces the types in the callSiteType parameter if more specific types
     * given through the arguments. This is in general the case, unless
     * the argument is null.
     */
    protected static MethodType replaceWithMoreSpecificType(Object[] args, MethodType callSiteType) {
        for (int i=0; i<args.length; i++) {
            // if argument null, take the static type
            if (args[i]==null) continue;
            if (callSiteType.parameterType(i).isPrimitive()) continue;
            Class argClass = args[i].getClass();
            callSiteType = callSiteType.changeParameterType(i, argClass);
        }
        return callSiteType;
    }

    protected static boolean isIntCategory(Class x) {
        return x==Integer.class    ||  x==int.class    ||
                x==Byte.class       ||  x==byte.class   ||
                x==Short.class      ||  x==short.class;
    }

    protected static boolean isLongCategory(Class x) {
        return  x==Long.class       ||  x==long.class   ||
                isIntCategory(x);
    }

    private static boolean isBigIntCategory(Class x) {
        return  x==BigInteger.class || isLongCategory(x);
    }

    protected static boolean isBigDecCategory(Class x) {
        return  x==BigDecimal.class || isBigIntCategory(x);
    }

    protected static boolean isDoubleCategory(Class x) {
        return  x==Float.class      ||  x==float.class  ||
                x==Double.class     ||  x==double.class ||
                isBigDecCategory(x);
    }
}


text:
package filodb.cli

import akka.actor.{ActorRef, ActorSystem}
import akka.pattern.ask
import akka.util.Timeout
import com.opencsv.{CSVReader, CSVWriter}
import org.velvia.filo.{ArrayStringRowReader, RowReader}
import scala.concurrent.{Await, Future, ExecutionContext}
import scala.concurrent.duration._
import scala.language.postfixOps

import filodb.core.metadata.MetaStore
import filodb.core.reprojector.{MemTable, Scheduler}
import filodb.coordinator.CoordinatorActor
import filodb.coordinator.sources.CsvSourceActor
import filodb.core._

// Turn off style rules for CLI classes
//scalastyle:off
trait CsvImportExport {
  val system: ActorSystem
  val metaStore: MetaStore
  val memTable: MemTable
  val scheduler: Scheduler
  val coordinatorActor: ActorRef
  var exitCode = 0

  implicit val ec: ExecutionContext
  import scala.collection.JavaConversions._

  protected def parseResponse[B](cmd: => Future[Response])(handler: PartialFunction[Response, B]): B = {
    Await.result(cmd, 15 seconds) match {
      case e: ErrorResponse =>
        println("ERROR: " + e)
        exitCode = 1
        null.asInstanceOf[B]
      case r: Response => handler(r)
    }
  }

  protected def parse[T, B](cmd: => Future[T], awaitTimeout: FiniteDuration = 5 seconds)(func: T => B): B = {
    func(Await.result(cmd, awaitTimeout))
  }

  protected def actorAsk[B](actor: ActorRef, msg: Any,
                            askTimeout: FiniteDuration = 5 seconds)(f: PartialFunction[Any, B]): B = {
    implicit val timeout = Timeout(askTimeout)
    parse(actor ? msg, askTimeout)(f)
  }

  protected def awaitSuccess(cmd: => Future[Response]) {
    parseResponse(cmd) {
      case Success =>   println("Succeeded.")
    }
  }

  def ingestCSV(dataset: String, version: Int, csvPath: String) {
    val fileReader = new java.io.FileReader(csvPath)

    val reader = new CSVReader(fileReader, ',')
    val columns = reader.readNext.toSeq
    println(s"Ingesting CSV at $csvPath with columns $columns...")

    val ingestCmd = CoordinatorActor.SetupIngestion(dataset, columns, version: Int)
    actorAsk(coordinatorActor, ingestCmd, 10 seconds) {
      case CoordinatorActor.IngestionReady =>
      case CoordinatorActor.UnknownDataset =>
        println(s"Dataset $dataset is not known, you need to --create it first!")
        exitCode = 2
        return
      case CoordinatorActor.UndefinedColumns(undefCols) =>
        println(s"Some columns $undefCols are not defined, please define them with --create first!")
        exitCode = 2
        return
      case CoordinatorActor.BadSchema(msg) =>
        println(s"BadSchema - $msg")
        exitCode = 2
        return
    }

    var linesIngested = 0
    reader.iterator.grouped(100).foreach { lines =>
      val mappedLines = lines.toSeq.map(ArrayStringRowReader)
      var resp: MemTable.IngestionResponse = MemTable.PleaseWait
      do {
        resp = memTable.ingestRows(dataset, version, mappedLines)
        if (resp == MemTable.PleaseWait) {
          do {
            println("Waiting for MemTable to be able to ingest again...")
            Thread sleep 10000
          } while (!memTable.canIngest(dataset, version))
        }
      } while (resp != MemTable.Ingested)
      linesIngested += mappedLines.length
      if (linesIngested % 10000 == 0) println(s"Ingested $linesIngested lines!")
    }
    // val csvActor = system.actorOf(CsvSourceActor.props(fileReader, dataset, version, coordinatorActor))
    // actorAsk(csvActor, RowSource.Start, 61 minutes) {
    //   case RowSource.SetupError(err) =>
    //     println(s"ERROR: $err")
    //     exitCode = 2
    //   case RowSource.AllDone =>
        coordinatorActor ! CoordinatorActor.Flush(dataset, version)
        println("Waiting for scheduler/memTable to finish flushing everything")
        Thread sleep 5000
        while (memTable.flushingDatasets.nonEmpty) {
          print(".")
          Thread sleep 1000
        }
        println("ingestCSV finished!")
        exitCode = 0
    // }
  }

  def exportCSV(dataset: String, version: Int,
                columnNames: Seq[String], limit: Int,
                outFile: Option[String]) {
    val columns = parse(metaStore.getSchema(dataset, version)) { schema =>
      columnNames.map(schema)
    }

    val outStream = outFile.map(new java.io.FileOutputStream(_)).getOrElse(System.out)
    val writer = new CSVWriter(new java.io.OutputStreamWriter(outStream))
    writer.writeNext(columnNames.toArray, false)

    println("Sorry, exportCSV functionality is temporarily unavailable")

    // val extractor = new ReadRowExtractor(datastore, partObj, version, columns, ArrayStringRowSetter)(system)
    // val row = Array.fill(columns.length)("")
    // var rowNo = 0
    // while (rowNo < limit && extractor.hasNext) {
    //   extractor.next(row)
    //   writer.writeNext(row, false)
    //   rowNo += 1
    // }
    // writer.flush()
  }
}