text:
%   Class for Hi-D matching with merging of data subsets using
%       QF match or F-measure or both
%
%
%   QF Algorithm is described in
%   https://www.ncbi.nlm.nih.gov/pmc/articles/PMC6586874/
%   and
%   https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5818510/
%
%   Bioinformatics lead: Darya Orlova <dyorlova@gmail.com>
%   Software Developer: Stephen Meehan <swmeehan@stanford.edu>
%
%   Provided by the Herzenberg Lab at Stanford University
%   License: BSD 3 clause
%
classdef QfTable < handle
    properties(SetAccess=private)
        fig;
        data;
        unmatched;
        sortTable;
        tb;
        qf;
        tClrs;
        priorFig;
        fHistFig;
        qHistFig;
        R;
    end

    properties(Constant)
        PROP_OUTER_POS2='OuterPosition2_V2';
    end

    methods
        function this=QfTable(qf, tClrs, props, priorFig, visible)
            if nargin<5
                visible=true;
                if nargin<4
                    priorFig=gcf;
                    if nargin<3
                        props=[];
                    end
                end
            end
            app=BasicMap.Global;
            if isempty(props)
                props=app;
            end
            this.tClrs=tClrs;
            this.qf=qf;
            PROP_COL_W='mdsColumnWidthsV1.33';
            PROP_COL_ORD='mdsColumnOrder_v2';
            PROP_SORT='mdsRowOrder_v2';
            path=BasicMap.Path;
            if visible
                pu=PopUp('Preparing QF dissimilarity table', 'north west+', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
            else
                pu=[];
            end
            this.priorFig=priorFig;
            [this.fig, tb_]=Gui.Figure;
            this.tb=tb_;
            figName=['QF dissimilarity between ' ...
                num2str(length(qf.tIds)) ' and ' num2str(length(qf.sIds))...
                ' subsets'];
            set(this.fig, 'CloseRequestFcn', @(h, e)hush(h), ...
                'Name', figName);
            [this.data, labels, fmts, tips,  this.unmatched, groupIdx, ...
                freqIdx, rankIdx, symIdx]=QfTable.Contents(qf, tClrs, pu);
            [this.R, C]=size(this.data);
            J=edu.stanford.facs.swing.Basics;
            [sData, widths]=SortTable.Convert(this.data, fmts);
            this.sortTable=SortTable(this.fig, sData, ...
                labels, [], @(h,e)select(h,e), tips);
            st=this.sortTable;
            jt=st.jtable;
            N=length(widths);
            for i=1:N
                if app.highDef
                    factor=app.toolBarFactor;
                else
                    factor=1;
                end
                st.setColumnWidth(i, widths(i)*factor)
                st.setColumnWidth(i, widths(i)*factor)
            end
            preSorted=SortTable.SetRowOrder(jt, ...
                BasicMap.GetNumbers(props, PROP_SORT));
            if ~preSorted
                jt.sortColumn(rankIdx-1, true, true);
                jt.sortColumn(groupIdx-1, false, true);
                jt.sortColumn(freqIdx-1, false, false);
            end
            startingRowOrder=SortTable.GetRowOrder(jt);
            if ~isempty(qf.matrixHtml)
                ToolBarMethods.addButton(tb_, ...
                    fullfile(path, 'world_16.png'), 'See table in default browser', ...
                    @(h,e)browse(h));
            end
            bb=ToolBarMethods.addButton(tb_,fullfile(path, 'table.gif'), ...
                'Restore default row and column order', ...
                @(h,e)defaultOrder());
            ToolBarMethods.addButton(tb_,fullfile(path, 'leftArrowNarrow.png'), ...
                'Shift sorted columns to the left', ...
                @(h,e)shiftSortLeft());

            ToolBarMethods.addButton(tb_, fullfile(path, 'histQF.png'), ...
                'Open histogram of QF scores', ...
                @(h,e)doHistQF(this));

            ToolBarMethods.addButton(tb_, fullfile(path, 'histF.png'), ...
                'Open histogram of F-measure scores', ...
                @(h,e)doHistF(this));
            savedOrder=BasicMap.GetNumbers(props, PROP_COL_ORD);
            if ~isempty(savedOrder)
                try
                    SortTable.SetColumnOrder(jt, savedOrder,...
                        BasicMap.GetNumbers(props, PROP_COL_W));
                catch
                end
            else
                defaultColumnOrder;
            end
            op=BasicMap.GetNumbers(props, QfTable.PROP_OUTER_POS2);
            if length(op)==4
                newFigPos=Gui.RepositionOnSameScreenIfRequired(op);
                set(this.fig, 'OuterPosition', newFigPos);
                Gui.FitFigToScreen(this.fig);
            else
                Gui.SetToRight(this.priorFig, this.fig, false, 80);
            end
            if visible
                pu.close;
                Gui.SetFigVisible(this.fig);
            end
            if preSorted
                jt.unsort;
                SortTable.SetRowOrder(jt, ...
                    BasicMap.GetNumbers(props, PROP_SORT))
            elseif isempty(savedOrder)
                bb.doClick;
            end
            MatBasics.DoLater(@(h,e)heighten(), .31);

            function heighten
                drawnow;
                height=jt.getRowHeight;
                jt.setRowHeight(floor(height*1.33));
                try
                    if props.multiProps.is('mds_figHistQF', false)
                        this.doHistQF(visible);
                    end
                    if props.multiProps.is('mds_figHistF', false)
                        this.doHistF;
                    end
                catch ex
                    disp('Using QF table outside of CytoGenie''s AutoGate')
                    %ex.getReport
                end
            end

            function shiftSortLeft(h)
                if ~SortTable.MoveSortColumnsLeft(jt)
                    if ismac
                        key='command';
                    else
                        key='control';
                    end
                    msg(Html.Wrap(['There is no sort order currently.'...
                        '
To sort the table you
'...
                        '
Click on a column to sort it'...
                        '
Click again for descending order'...
                        '
Hold ' key ' key for multi column
']), ...
                        8, 'north', 'No sort order...');
                else
                    r=jt.getSelectedRow;
                    if r<0
                        r=0;
                    end
                    rect=jt.getCellRect(r,0, true);
                    jt.scrollRectToVisible(rect);
                end
            end

            function defaultOrder()
                defaultRowOrder;
                defaultColumnOrder;
            end

            function defaultRowOrder
                SortTable.SetRowOrder(jt, [(rankIdx-1) true 0; ...
                    (groupIdx-1) false 0; (freqIdx-1) false 1]);
            end

            function defaultColumnOrder()
                idxs=1:jt.getColumnCount;
                idxs(rankIdx)=[];
                idxs(symIdx)=[];
                idxs=[rankIdx symIdx idxs]-1;
                SortTable.SetColumnOrder(jt, idxs, [], true);
            end

            function browse(h)
                Html.Browse(Html.Wrap([SortTable.ToHtml(jt) '
' ...
                    Html.remove(qf.matrixHtml)]));
            end

            function hush(h)
                if ishandle(this.priorFig)
                    [columnOrder, widths]=SortTable.GetColumnOrder(jt);
                    props.set(PROP_COL_ORD, num2str(columnOrder));
                    props.set(PROP_COL_W, num2str(widths));
                    rowOrder=SortTable.GetRowOrder(jt);
                    if ~isequal(rowOrder, startingRowOrder)
                        props.set(PROP_SORT, MatBasics.Encode(...
                            rowOrder));
                    end
                    props.set(QfTable.PROP_OUTER_POS2, ...
                        num2str(get(h, 'OuterPosition')));
                    figure(this.priorFig);
                end
                delete(h);
            end

            function showSelected()
                selectedIdxs=SortTable.SelectedRows(jt);
                try
                    N_=length(selectedIdxs);
                    for ii=1:N_

                    end
                catch ex
                    ex.getReport
                end
            end
            function select(h, e)
                if ~isempty(e.Indices)
                    rowIdx=e.Indices(1,1)-1;
                    if rowIdx>=0
                        try
                            colIdx=jt.convertColumnIndexToModel(...
                                e.Indices(1,2)-1);
                            st.showTip(colIdx+1);
                            rowIdx=jt.getActualRowAt(...
                                jt.convertRowIndexToModel(rowIdx))+1;

                            showSelected;
                        catch ex
                            ex.getReport
                        end
                        return;
                    end
                end
                st.showTip(0);
            end
        end

        function doHistQF(this, visible)
            if nargin<2
                visible=true;
            end
            if ishandle(this.qHistFig)
                figure(this.qHistFig);
            else
                fig_=Gui.NewFigure;
                if ~visible
                    set(fig_, 'visible', 'off');
                end
                this.qHistFig=fig_;
                Gui.Resize(fig_, .66);
                Gui.Locate(fig_, this.fig, 'south west+')
                ax=gca;
                qfData=cell2mat(this.data(:,4))*100;
                qfData=qfData(~isnan(qfData));
                avgMdn=median(qfData);
                avgMn=mean(qfData);
                histogram(ax, qfData, length(unique(qfData)));
                set(ax, 'units', 'normalized', 'Position', ...
                    [.1 .16 .8 .7]);
                Gui.StretchUpper(ax, @ylim, .1);
                Gui.StretchUpper(ax, @xlim, .1);
                xlabel(ax, '% dissimilarity', 'FontName', 'Arial')
                xlim(ax, [-5 100]);
                ylabel(ax, '# of subset matches', 'FontName', 'Arial')
                figName=['QF dissimilarity between ' ...
                    num2str(length(this.qf.tIds)) ' and ' ...
                    num2str(length(this.qf.sIds)) ' subsets'];
                this.addTitleToHist(fig_, ax, ...
                    figName, avgMdn, avgMn);
                disp(num2str(get(fig_, 'OuterPosition')));
                set(fig_, 'CloseRequestFcn', @(h, e)hush(h));
            end

            function hush(h)
                if ishandle(this.fig)
                    figure(this.fig);
                end
                delete(h);
            end
        end

        function addTitleToHist(this, fig, ax, score, avgMdn, avgMn)
            ttl=[score ', median/mean=\color{blue}' ...
                String.encodeRounded(avgMdn, 1) ...
                '\color{black}/\color{blue}'...
                String.encodeRounded(avgMn, 1) '\color{black}% '];
            set(fig, 'name', String.RemoveTex(score), 'NumberTitle', 'off');
            if this.unmatched>0
                title(ax, {ttl, [ ...
                    num2str(this.R-this.unmatched) ' subsets matched, ' ...
                    '\color{red}' num2str(this.unmatched) ...
                    ' \color{black}NOT matched ']},'FontName', 'Arial');
            else
                title(ax, {ttl, [ ...
                    num2str(this.R) ' matches']}, ...
                    'FontName', 'Arial');
            end
        end

        function doHistF(this, visible)
            if nargin<2
                visible=true;
            end
            if ishandle(this.fHistFig)
                figure(this.fHistFig);
            else
                fig_=Gui.NewFigure;
                if ~visible
                    set(fig_, 'visible', 'off');
                end
                this.fHistFig=fig_;
                Gui.Resize(fig_, .66);
                Gui.Locate(fig_, this.fig, 'south east+')
                ax=gca;
                fData=cell2mat(this.data(:,5))*100;
                fData=fData(~isnan(fData));
                avgMdn=median(fData);
                avgMn=mean(fData);

                histogram(ax, fData, length(unique(fData)));
                set(ax, 'units', 'normalized', 'Position', ...
                    [.1 .16 .8 .7]);
                Gui.StretchUpper(ax, @ylim, .1);

                xlabel(ax, '% overlap', 'FontName', 'Arial')
                xlim(ax, [-5 100]);
                ylabel(ax, '# of subset matches', 'FontName', 'Arial')
                set(ax, 'xlim', [0 100]);
                this.addTitleToHist(fig_, ax, ...
                    '%  Overlap ^{(F-measure)}', avgMdn, avgMn);
                set(fig_, 'CloseRequestFcn', @(h, e)hush(h));
            end

            function hush(h)
                if ishandle(this.fig)
                    figure(this.fig);
                end
                delete(h);
            end
        end

        function QF=save(this, qf, file)
            QF.tIds=qf.tIds;
            QF.sIds=qf.sIds;
            %QF.matches=qf.matches;
            %QF.getStudNames=qf.getStudNames();
            QF.tNames=qf.tNames;
            QF.tSizes=qf.tSizes;
            QF.sSizes=qf.sSizes;
            QF.matrixHtml=qf.matrixHtml;
            QF.qfTableData=this.data;
            QF.unmatched=this.unmatched;
            QF.tClrs=this.tClrs;
            if nargin>2 && ~isempty(file)
                save(file, 'QF');
            end
        end

    end

    methods(Static)

        function QF=Load(file)
            load(file, 'QF');
        end

        function [data, names, widths, tips, unmatched, plotIdx, freqIdx,...
                rankIdx, symIdx]=Contents(qf, clrs, pu)
            unmatched=0;
            plotIdx=6;
            freqIdx=7;
            widths=[3 0; 17 nan; 5 0; 3 -2; 3 -2; ...
                    6 nan; 3 -1;  10 0; 5 nan; 8 0];
            names={'#', ...
                'Name', ...
                Html.WrapSm('Mat-
ches '), ...
                Html.WrapSm('QF dis-
similaritry'), ...
                Html.WrapSm('Overlap
F-measure'),...
                Html.WrapSm('
Trainer'), ...
                Html.WrapSm('
Freq.'), ...
                Html.WrapSm('# of
events'), ...
                '', ...
                Html.WrapSm('QF
Rank')};
            rankIdx=length(names);
            symIdx=rankIdx-1;
            tips={...
                'The subset''s item # ',...
                'The name of the subset including match name if applicable`',...
                'The number of subsets in this match set',...
                'The lower the % the more similar the match',...
                'The higher the % the more overlap (similarity) of cells (or bins)',...
                'yes for training set, no for test set ',...
                'The frequency of the subset within this selection of cells/events',...
                'The # of cells/events for the subset ',...
                'The subset''s frequency-sized symbol',...
                'The ranking of the match set'};
            try
                [data, unmatched]=qf.getTableData(clrs);
            catch ex
                data=qf.qfTableData;
                unmatched=qf.unmatched;
            end
            if exist('pu', 'var') && ~isempty(pu)
                if ~isempty(pu.pb)
                    pu.pb.setValue(N);
                end
            end
        end

        function qft=RunWithGt(supervisors, gt, gid, fcs, fcsIdxs, ...
                data, file, embedding, visible, pu)
            qft=[];
            pFig=gcf;
            if exist(file, 'file')
                qf=QfTable.Load(file);
                qft=QfTable(qf, qf.tClrs, [], pFig, visible);
                qft.doHistQF(visible);
                return;
            end
            if isempty(fcsIdxs)
                return;
            end
            newPu=nargin<10||isempty(pu);
            if newPu
                path=BasicMap.Path;
                pu=PopUp('Generating QF dissimilarity table', 'north', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
                pu.setTimeSpentTic(tic);
            else
                pu.setText2('Generating QF dissimilarity table');
            end
            [gtData, ~, ~, gtIds]=QfHiDM.GetRequiredData2(fcs, fcsIdxs, ...
                gt, gid, pu, visible);
            if isempty(gtData)
                return;
            end
            matchStrategy=1;
            gids=MatBasics.GetUniqueIdsAndCntIfGt0(gtIds);
            hghl=gt.highlighter;
            N=length(gids);
            names=cell(1,N);
            for i=1:N
                id=num2str(gids(i));
                names{i}=gt.tp.getDescription(id);
            end
            [tNames, tLbls, clrs]=supervisors.getQfTrained(embedding);
            qf=run_HiD_match(data, tLbls, gtData, gtIds, ...
                'trainingNames', tNames, ...
                'testNames', names, ...
                'matchStrategy', matchStrategy, 'log10', true, 'pu', pu);
            if ~isempty(qf)
                qft=QfTable(qf, clrs, [], pFig, visible);
                qft.doHistQF(visible);
                if ~isempty(file) && ~exist(file, 'file')
                    qft.save(qf, file);
                end
            end
            if newPu
                pu.close;
            end
        end

        function qft=Run(fcs, fcsIdxs, gt, gid1, gid2, file, visible, pu)
            pFig=gcf;
            qft=[];
            if exist(file, 'file')
                qf=QfTable.Load(file);
                qft=QfTable(qf, qf.tClrs, [], pFig, visible);
                qft.doHistQF(visible);
                return;
            end
            if isempty(fcsIdxs)
                return;
            end
            newPu=nargin<8|| isempty(pu);
            if newPu
                path=BasicMap.Path;
                pu=PopUp('Generating QF dissimilarity table', 'north', ...
                    'Note...', false, true, fullfile(path, 'genieSearch.png'));
                pu.setTimeSpentTic(tic);
            else
                pu.setText2('Generating QF dissimilarity table');
            end
            [data1, ids1, names1, clrs1]=go(gid1);
            if isempty(data1)
                return;
            end
            [data2, ids2, names2, clrs2]=go(gid2);
            if isempty(data2)
                return;
            end
            matchStrategy=1;
            qf=run_HiD_match(data1, ids1, data2, ids2, ...
                'trainingNames', names1, 'testNames', names2, ...
                'matchStrategy', matchStrategy, 'log10', true, ...
                'pu', pu);
            if ~isempty(qf)
                qft=QfTable(qf, clrs1, [], pFig, visible);
                qft.doHistQF(visible);
                if ~isempty(file) && ~exist(file, 'file')
                    qft.save(qf, file);
                end
            end
            if newPu
                pu.close;
            end

            function [gtData, gtIds, names, clrs]=go(gid)
                [gtData, ~, ~, gtIds]=QfHiDM.GetRequiredData2(fcs, ...
                    fcsIdxs, gt, gid, pu, visible);
                if isempty(gtData)
                    return;
                end
                gids=MatBasics.GetUniqueIdsAndCntIfGt0(gtIds);
                hghl=gt.highlighter;
                N=length(gids);
                clrs=zeros(N, 3);
                names=cell(1,N);
                for i=1:N
                    id=num2str(gids(i));
                    names{i}=gt.tp.getDescription(id);
                    clrs(i,:)=hghl.getColor(id, Gui.HslColor(i, N));
                end
            end
        end
    end
end


text:
const config = require("./config");
const app = require("./app");

app.listen(config.port, () => {
  console.log(`App listening on port ${config.port}!`);
});

redpajama_set_name: RedPajamaGithub


text:
namespace Aspose.Tasks.Examples.CSharp
{
    using System;
    using System.Diagnostics.CodeAnalysis;

    using NUnit.Framework;
    using Saving;

    [TestFixture]
    [SuppressMessage("ReSharper", "StyleCop.SA1108", Justification = "Reviewed. Suppression is OK here.")]
    public class ExTasksLoggedException : ApiExampleBase
    {
        [Test]
        public void PrintTaskWritingException()
        {
            // ExStart:PrintTaskWritingException
            // ExFor: TasksWritingException
            // ExFor: TasksWritingException.#ctor(SerializationInfo,StreamingContext)
            // ExFor: TasksLoggedException
            // ExFor: TasksLoggedException.#ctor(SerializationInfo,StreamingContext)
            // ExFor: TasksLoggedException.LogText
            // ExFor: TasksLoggedException.Operation
            // ExSummary: Shows how to read log text and type of exception to check problems with MPP export.
            try
            {
                var project = new Project(DataDir + "PrintTaskWritingException.mpp");

                // export the project as an MPP file
                project.Save(OutDir + "PrintTaskWritingException_out.MPP", SaveFileFormat.Mpp);
            }
            catch (TasksWritingException ex)
            {
                Console.WriteLine("Exception Operation: " + ex.Operation);
                Console.WriteLine("Exception Log Text: ");
                Console.WriteLine(ex.LogText);
            }

            // ExEnd:PrintTaskWritingException
            catch (NotSupportedException ex)
            {
                Console.WriteLine(
                    ex.Message
                    + "\nThis example will only work if you apply a valid Aspose License. You can purchase full license or get 30 day temporary license from http://www.aspose.com/purchase/default.aspx.");
            }
        }
    }
}


text:
package org.wildfly.swarm.plugin.maven;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.inject.Inject;

import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Dependency;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.impl.ArtifactResolver;
import org.wildfly.swarm.fractions.PropertiesUtil;
import org.wildfly.swarm.tools.ArtifactSpec;
import org.wildfly.swarm.tools.BuildTool;
import org.wildfly.swarm.tools.DeclaredDependencies;

/**
 * @author Bob McWhirter
 */
public abstract class AbstractSwarmMojo extends AbstractMojo {

    protected static final String EXCLUDE_PREFIX = "!";

    protected static final String JAR = "jar";

    protected static final String WAR = "war";

    protected static final String DOT = ".";

    protected static final String JAR_FILE_EXTENSION = DOT + JAR;

    protected static final String WAR_FILE_EXTENSION = DOT + WAR;

    @Parameter(defaultValue = "${project}", readonly = true)
    protected MavenProject project;

    @Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
    protected DefaultRepositorySystemSession repositorySystemSession;

    @Parameter(alias = "remoteRepositories", defaultValue = "${project.remoteArtifactRepositories}", readonly = true)
    protected List<ArtifactRepository> remoteRepositories;

    @Parameter(defaultValue = "${project.build.directory}")
    protected String projectBuildDir;

    @Parameter(defaultValue = "${session}", readonly = true)
    protected MavenSession mavenSession;

    @Deprecated
    @Parameter(alias = "mainClass", property = "swarm.mainClass")
    protected String mainClass;

    /**
     * Flag to skip all executions
     */
    @Parameter(alias = "skipAll", defaultValue = "false", property = "swarm.skipAll")
    protected boolean skipAll;

    @Parameter(alias = "properties")
    protected Properties properties;

    @Parameter(alias = "propertiesFile", property = "swarm.propertiesFile")
    protected String propertiesFile;

    @Parameter(alias = "environment")
    protected Properties environment;

    @Parameter(alias = "environmentFile", property = "swarm.environmentFile")
    protected String environmentFile;

    @Parameter(alias = "modules")
    protected List<String> additionalModules = new ArrayList<>();

    @Parameter(alias = "fractions")
    protected List<String> fractions = new ArrayList<>();

    @Parameter(defaultValue = "when_missing", property = "swarm.detect.mode")
    protected BuildTool.FractionDetectionMode fractionDetectMode;

    @Inject
    protected ArtifactResolver resolver;

    @Component
    protected RepositorySystem repositorySystem;

    AbstractSwarmMojo() {
        if (this.additionalModules.isEmpty()) {
            this.additionalModules.add("modules");
        }
    }

    @Override
    public final void execute() throws MojoExecutionException, MojoFailureException {
        deprecationWarnings();
        if (this.skipAll) {
            getLog().info("Skipping wildfly-swarm-plugin execution");
            return;
        }
        executeSpecific();
    }

    public abstract void executeSpecific() throws MojoExecutionException, MojoFailureException;

    protected void deprecationWarnings() {
        if (mainClass != null && !mainClass.equals("")) {
            getLog().warn(
                    "\n------\n" +
                    "Custom main() usage is intended to be deprecated in a future release and is no longer supported, \n" +
                            "please refer to http://docs.wildfly-swarm.io for YAML configuration that replaces it." +
                    "\n------"
            );
        }
    }

    protected void initProperties(final boolean withMaven) {
        if (this.properties == null) {
            this.properties = new Properties();
        }

        if (this.propertiesFile != null) {
            try {
                this.properties.putAll(PropertiesUtil.loadProperties(this.propertiesFile));
            } catch (IOException e) {
                getLog().error("Failed to load properties from " + this.propertiesFile, e);
            }
        }

        this.properties.putAll(PropertiesUtil.filteredSystemProperties(this.properties, withMaven));
    }

    protected void initEnvironment() throws MojoFailureException {
        if (this.environment == null) {
            this.environment = new Properties();
        }
        if (this.environmentFile != null) {
            try {
                this.environment.putAll(PropertiesUtil.loadProperties(this.environmentFile));
            } catch (IOException e) {
                getLog().error("Failed to load environment from " + this.environmentFile, e);
            }
        }
    }

    protected MavenArtifactResolvingHelper mavenArtifactResolvingHelper() {
        MavenArtifactResolvingHelper resolvingHelper =
                new MavenArtifactResolvingHelper(this.resolver,
                                                 this.repositorySystem,
                                                 this.repositorySystemSession,
                                                 this.project.getDependencyManagement());
        this.remoteRepositories.forEach(resolvingHelper::remoteRepository);

        return resolvingHelper;
    }

    protected ArtifactSpec artifactToArtifactSpec(Artifact dep) {
        return new ArtifactSpec(dep.getScope(),
                                dep.getGroupId(),
                                dep.getArtifactId(),
                                dep.getBaseVersion(),
                                dep.getType(),
                                dep.getClassifier(),
                                dep.getFile());
    }

    protected Map<ArtifactSpec, Set<ArtifactSpec>> createBuckets(Set<Artifact> transientDeps, List<Dependency> directDeps) {
        Map<ArtifactSpec, Set<ArtifactSpec>> buckets = new HashMap<>();
        for (Artifact dep : transientDeps) {
            if (dep.getDependencyTrail().isEmpty()) {
                throw new RuntimeException("Empty trail " + asBucketKey(dep));
            } else if (dep.getDependencyTrail().size() == 2) {
                ArtifactSpec key = asBucketKey(dep);
                //System.out.println("Appears to be top level: "+ key);
                if (!buckets.containsKey(key)) {
                    buckets.put(key, new HashSet<>());
                }
            } else {

                String owner = dep.getDependencyTrail().get(1);
                String ownerScope = null;
                String[] tokens = owner.split(":");
                for (Dependency d : directDeps) {
                    if (d.getGroupId().equals(tokens[0])
                            && d.getArtifactId().equals(tokens[1])) {
                        ownerScope = d.getScope();
                        break;
                    }
                }

                assert ownerScope != null : "Failed to resolve owner scope";

                ArtifactSpec parent = DeclaredDependencies.createSpec(owner, ownerScope);
                if (!buckets.containsKey(parent)) {
                    buckets.put(parent, new HashSet<>());
                }
                buckets.get(parent).add(asBucketKey(dep));
            }
        }
        return buckets;
    }

    private static ArtifactSpec asBucketKey(Artifact artifact) {

        return new ArtifactSpec(
                artifact.getScope(),
                artifact.getGroupId(),
                artifact.getArtifactId(),
                artifact.getBaseVersion(),
                artifact.getType(),
                artifact.getClassifier(),
                artifact.getFile()
        );
    }

}


text:
package generics.solution.ex01;
import java.lang.reflect.Proxy;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationHandler;

interface Shape {
  void draw();
  void show();
}
class Circle implements Shape {
  public void draw() {
    System.out.println("draw");
  }
  public void show() {
    System.out.println("show");
  }
  void runCircle() {
    System.out.println("run circle");
  }
}
class DynamicProxyCircle implements InvocationHandler {
  private static Object proxied;
  DynamicProxyCircle(Object proxied) {
    this.proxied = proxied;
  }
  @Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Exception{
    return method.invoke(proxied,args);
  }
}
public class DynamicProxyTest {
  public static void main(String[] args){
    Object proxy = Proxy.newProxyInstance(
    	Shape.class.getClassLoader(),
      	new Class[]{ Shape.class},
      	new DynamicProxyCircle(new Circle())
    	);
    Shape s = (Shape)proxy;
    s.draw();
    s.show();
    //s.runCircle();
  }
}


text:
<form id="addform" encType="multipart/form-data" class="form-horizontal form-label-left" novalidate>

        产品名称*

            <input id="form_name" class="form-control col-md-7 col-xs-12 " name="name"  required="required" type="text">

        产品年份:

            <input id="year" class="form-control col-md-7 col-xs-12" name="year" data-validate-minmax="00,99" data-validate-length="2"    required="required" type="number">

        产品编号:

            <input id="number" class="form-control col-md-7 col-xs-12" name="number" data-validate-minmax="000000,999999"  required="required" type="number">

        产品保质期:

            <input id="operation" class="form-control col-md-7 col-xs-12" name="expirationdate" data-validate-minmax="0,12"  required="required" type="number">

        产品大小:

            <input id="menuNO" class="form-control col-md-7 col-xs-12" name="size"  required="required" type="number">

        存储条件:

            <input id="meno" class="form-control col-md-7 col-xs-12" name="storage"  required="required" type="text">

        产品等级:

            <input id="grade" class="form-control col-md-7 col-xs-12" name="grade"  required="required" type="text">

        产品信息:

            <input id="information" class="form-control col-md-7 col-xs-12" name="information"  required="required" type="text">

        文件:

            添加图片

</form>


text:
"""Tests for the music_service module."""

from __future__ import unicode_literals

import mock
import pytest

import soco.soap
from soco.exceptions import MusicServiceException
from soco.music_services.accounts import Account
from soco.music_services.music_service import (
    MusicService, MusicServiceSoapClient, desc_from_uri
)

# Typical account data from http://{Sonos-ip}:1400/status/accounts
ACCOUNT_DATA = """<?xml version="1.0" ?>
<ZPSupportInfo type="User">
    <Accounts
    LastUpdateDevice="RINCON_000XXXXXXXX400" Version="8" NextSerialNum="5">
    <Account Type="2311" SerialNum="1">
        <UN>12345678</UN>
        <MD>1</MD>
        <NN>mysonos</NN>
        <OADevID>12345</OADevID>
        <Key></Key>
    </Account>
    <Account Type="41735" SerialNum="3">
        <UN></UN>
        <MD>1</MD>
        <NN></NN>
        <OADevID></OADevID>
        <Key></Key>
    </Account>
    <Account Type="519" SerialNum="4" Deleted="1">
        <UN>email@example.com</UN>
        <MD>1</MD>
        <NN>myservice</NN>
        <OADevID></OADevID>
        <Key></Key>
    </Account>
    <Account Type="41479" SerialNum="2">
    <UN></UN>
    <MD>1</MD>
    <NN></NN>
    <OADevID></OADevID>
    <Key></Key></Account></Accounts>
</ZPSupportInfo>"""

# Typical service descriptor list
# available_services = device.musicServices.ListAvailableServices()
# descriptor_list_xml = available_services['AvailableServiceDescriptorList']
# The list has been edited to include services represented in ACCOUNT_DATA
SERVICES_DESCRIPTOR_LIST = """<?xml version="1.0"?>
<Services
    SchemaVersion="1">
    <Service
        Id="163"
        Name="Spreaker"
        Version="1.1"
        Uri="http://sonos.spreaker.com/sonos/service/v1"
        SecureUri="https://sonos.spreaker.com/sonos/service/v1"
        ContainerType="MService"
        Capabilities="513"
        MaxMessagingChars="0">
        <Policy
            Auth="Anonymous"
            PollInterval="30" />
        <Presentation>
            <Strings
                Version="1"
                Uri="https://www.spreaker.com/sonos/string_table.xml" />
            <PresentationMap
                Version="2"
                Uri="https://www.spreaker.com/sonos/presentation_map.xml" />
        </Presentation>
    </Service>
    <Service
        Id="162"
        Name="radioPup"
        Version="1.1"
        Uri="http://sonos.townsquaremedia.com/index.php"
        SecureUri="https://sonos.townsquaremedia.com/index.php"
        ContainerType="MService"
        Capabilities="513"
        MaxMessagingChars="0">
        <Policy
            Auth="Anonymous"
            PollInterval="3600" />
        <Presentation>
            <Strings
                Version="1"
                Uri="http://sonos.townsquaremedia.com/strings.xml" />
            <PresentationMap
                Version="1"
                Uri="http://sonos.townsquaremedia.com/pmap.xml" />
        </Presentation>
    </Service>
    <Service
        Id="9"
        Name="Spotify"
        Version="1.1"
        Uri="https://spotify.ws.sonos.com/smapi"
        SecureUri="https://spotify.ws.sonos.com/smapi"
        ContainerType="MService"
        Capabilities="2563"
        MaxMessagingChars="0">
        <Policy
            Auth="DeviceLink"
            PollInterval="30" />
        <Presentation>
            <Strings
                Version="11"
                Uri="http://spotify-static-resources.s3.amazonaws.com/strings.xml" />
            <PresentationMap
                Version="8"
                Uri="http://sonos-pmap.ws.sonos.com/spotify_pmap.8.xml" />
        </Presentation>
    </Service>
    <Service
        Id="2"
        Name="Deezer"
        Version="1.1"
        Uri="http://deezer.ws.sonos.com/services/smapi"
        SecureUri="https://deezer.ws.sonos.com/services/smapi"
        ContainerType="MService"
        Capabilities="563"
        MaxMessagingChars="0">
        <Policy
            Auth="UserId"
            PollInterval="300" />
        <Presentation>
            <Strings
                Version="5"
                Uri="http://static.deezer.sonos-ws-us.com/strings.xml" />
            <PresentationMap
                Version="4"
                Uri="http://sonos-pmap.ws.sonos.com/deezer_pmap.4.xml" />
        </Presentation>
    </Service>
    <Service
        Id="254"
        Name="TuneIn" Version="1.1"
        Uri="http://legato.radiotime.com/Radio.asmx"
        SecureUri="http://legato.radiotime.com/Radio.asmx"
        ContainerType="MService"
        Capabilities="0"
        MaxMessagingChars="0">
        <Policy
            Auth="Anonymous"
            PollInterval="0"/>
        <Presentation>
        </Presentation>
    </Service>
    <Service
        Id="160"
        Name="SoundCloud"
        Version="1.1"
        Uri="https://soundcloud.ws.sonos.com/smapi"
        SecureUri="https://soundcloud.ws.sonos.com/smapi"
        ContainerType="MService"
        Capabilities="515"
        MaxMessagingChars="0">
        <Policy
            Auth="DeviceLink"
            PollInterval="30"/>
        <Presentation>
            <Strings Version="11" Uri="http://soundcloud-static.ws.sonos.com/strings.xml"/>
            <PresentationMap Version="11" Uri="http://soundcloud-static.ws.sonos.com/pmap.xml"/>
        </Presentation>
    </Service>
</Services>
"""

@pytest.fixture(autouse=True)
def patch_music_services(monkeypatch):
    """Patch MusicService, Account and SoapMessage to avoid network requests
    and use dummy data."""
    monkeypatch.setattr(
        MusicService, '_get_music_services_data_xml',
        mock.Mock(return_value=SERVICES_DESCRIPTOR_LIST))
    monkeypatch.setattr(
        soco.soap, 'SoapMessage',
        mock.Mock())
    monkeypatch.setattr(
        soco.music_services.music_service, 'MusicServiceSoapClient',
        mock.Mock()
    )
    monkeypatch.setattr(
        Account, '_get_account_xml',
        mock.Mock(return_value=ACCOUNT_DATA))

def test_initialise_account():
    assert len(Account._all_accounts) == 0
    accounts = Account.get_accounts()
    assert len(accounts) == 4  # TuneIn account is added automatically
    assert accounts['0'].service_type == '65031'  # TuneIn
    assert accounts['1'].username == '12345678'
    assert accounts['1'].service_type == '2311'
    assert accounts['1'].deleted is False
    assert accounts['1'].nickname == 'mysonos'
    assert accounts.get('4') is None

def test_get_all_accounts():
    a = Account.get_accounts()
    assert len(a) == 4  # Including TuneIn

def test_get_accounts_for_service():
    a = Account.get_accounts_for_service('2311')
    assert len(a) == 1
    assert a[0].username == "12345678"

def test_initialise_services():
    assert MusicService._music_services_data is None
    data = MusicService._get_music_services_data()
    assert len(data) == 6
    deezer = data['519']
    assert deezer['Name'] == "Deezer"
    assert deezer['Capabilities'] == '563'
    assert deezer['Auth'] == 'UserId'
    assert deezer['Version'] == '1.1'
    assert deezer['ContainerType'] == 'MService'
    assert deezer['Id'] == '2'
    assert deezer['PresentationMapUri'] == \
        'http://sonos-pmap.ws.sonos.com/deezer_pmap.4.xml'
    assert deezer['ServiceType'] == '519'

def test_get_data_for_name():
    s = MusicService.get_data_for_name('Spotify')
    assert s['Name'] == "Spotify"
    assert s['Capabilities'] == '2563'

def test_get_names():
    names = MusicService.get_all_music_services_names()
    assert len(names) == 6
    assert "Spotify" in names
    assert "Deezer" in names

def test_get_subscribed_names():
    names = MusicService.get_subscribed_services_names()
    assert len(names) == 4
    assert set(names) == {'TuneIn', 'Spotify', 'Spreaker', 'radioPup'}

def test_create_music_service():
    ms = MusicService('Spotify')
    assert ms.account.username == '12345678'
    with pytest.raises(MusicServiceException) as excinfo:
        unknown = MusicService('Unknown Music Service')
    assert 'Unknown music service' in str(excinfo.value)
    with pytest.raises(MusicServiceException) as excinfo:
        soundcloud = MusicService('SoundCloud')
    assert 'No account found' in str(excinfo.value)

def test_tunein():
    """TuneIn is handles specially by MusicServices."""
    tunein = MusicService('TuneIn')
    assert tunein
    assert tunein.service_id == '254'
    assert tunein.service_type == '65031'
    assert tunein.account.serial_number == '0'

def test_search():
    spotify = MusicService('Spotify')
    # Set up dummy search categories
    spotify._get_search_prefix_map = lambda: {
        'stations': 'search:station',
        'shows': 'search:show',
        'hosts': 'search:host',
    }
    categories = spotify.available_search_categories
    assert len(categories) == 3
    assert set(categories) == {'stations', 'shows', 'hosts'}
    with pytest.raises(MusicServiceException) as excinfo:
        spotify.search('badcategory')
    assert "support the 'badcategory' search category" in str(excinfo.value)

def test_sonos_uri_from_id():
    spotify = MusicService('Spotify')
    track = 'spotify:track:2qs5ZcLByNTctJKbhAZ9JE'
    assert spotify.sonos_uri_from_id(track) == \
        'soco://spotify%3Atrack%3A2qs5ZcLByNTctJKbhAZ9JE?sid=9&sn=1'
    # Check for escaping with a few difficult characters
    track = 'spotify: track\2qc%ünicøde?'
    assert spotify.sonos_uri_from_id(track) == \
        'soco://spotify%3A%20track%02qc%25%C3%BCnic%C3%B8de%3F?sid=9&sn=1'
    # and a different service
    spreaker = MusicService('Spreaker')
    track = 'spreaker12345678'
    assert spreaker.sonos_uri_from_id(track) == \
        'soco://spreaker12345678?sid=163&sn=3'

def test_desc():
    spotify = MusicService('Spotify')
    assert spotify.desc == 'SA_RINCON2311_12345678'
    spreaker = MusicService('Spreaker')
    assert spreaker.desc == 'SA_RINCON41735_'

def test_desc_from_uri():
    URI = 'x-sonos-http:track%3a3402413.mp3?sid=2&flags=32&sn=1'
    assert desc_from_uri(URI) == 'SA_RINCON2311_12345678'
    SID_ONLY = 'x-sonos-http:track%3a3402413.mp3?sid=9&flags=32'
    assert desc_from_uri(SID_ONLY) == 'SA_RINCON2311_12345678'
    TUNEIN_URI = 'x-sonosapi-stream:s49815?sid=254&flags=8224&sn=0'
    assert desc_from_uri(TUNEIN_URI) == 'SA_RINCON65031_'
    UNKNOWN_AC_WITH_SID = \
        'x-sonos-http:track%3a3402413.mp3?sid=9&flags=32&sn=400'
    assert desc_from_uri(UNKNOWN_AC_WITH_SID) == 'SA_RINCON2311_12345678'
    NO_DATA = 'x-sonos-http:track%3a3402413.mp3?flags=32'
    assert desc_from_uri(NO_DATA) == 'RINCON_AssociatedZPUDN'
    HTTP = "http://archive.org/download/TenD/TenD2005-07-16t10Wonderboy_64kb.mp3"
    assert desc_from_uri(HTTP) == 'RINCON_AssociatedZPUDN'


text:
require "vagrant"

module VagrantPlugins
  module Joyent
    module Errors
      class VagrantJoyentError < Vagrant::Errors::VagrantError
        error_namespace("vagrant_joyent.errors")
      end

      class FogError < VagrantJoyentError
        error_key(:fog_error)
      end

      class RsyncError < VagrantJoyentError
        error_key(:rsync_error)
      end
    end
  end
end


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Uses of Package org.codehaus.jackson.mrbean (Jackson JSON Processor)</title>
<meta name="date" content="2013-07-14">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Package
org.codehaus.jackson.mrbean

Packages that use org.codehaus.jackson.mrbean

Package
Description

org.codehaus.jackson.mrbean

Package that implements "interface materializer" functionality, whereby
 abstract classes and interfaces can be used as-is, and framework constructs
 implementations as needed.

Classes in org.codehaus.jackson.mrbean used by org.codehaus.jackson.mrbean

Class and Description

AbstractTypeMaterializer

Nifty class for pulling implementations of classes out of thin air.

AbstractTypeMaterializer.Feature

Enumeration that defines togglable features that guide
 the serialization feature.

BeanBuilder

Heavy lifter of mr Bean package: class that keeps track of logical POJO properties,
 and figures out how to create an implementation class.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ZSchema = new Schema({
  surname: String,
  forename: String,
  weight: Number,
  dateOfBirth: Date,
  termsAccepted: Boolean
});

var Z;
try {
  Z = mongoose.model('Z');
} catch (e) {
  Z = mongoose.model('Z', ZSchema);
}

module.exports = Z;


text:
package org.gridsphere.layout.view;

import org.gridsphere.layout.PortletComponent;
import org.gridsphere.portletcontainer.GridSphereEvent;

public class BaseRender implements Render {

    protected static StringBuffer BLANK = new StringBuffer();

    public StringBuffer doStart(GridSphereEvent event, PortletComponent comp) {
        return BLANK;
    }

    public StringBuffer doStartBorder(GridSphereEvent event, PortletComponent comp) {
        return BLANK;
    }

    public StringBuffer doEndBorder(GridSphereEvent event, PortletComponent comp) {
        return BLANK;
    }

    public StringBuffer doEnd(GridSphereEvent event, PortletComponent comp) {
        return BLANK;
    }

}


text:
![Build Status](https://travis-ci.org/gooscht/start.svg?branch=master "gooscht/start")

[![Build Status](https://travis-ci.org/gooscht/start.svg?branch=master)](https://travis-ci.org/gooscht/start)


text:
/**
 * Converts a JS boolean to a C boolean.
 * @param {boolean} bool - a JS boolean.
 * @return {number} C boolean.
 * @author Vitor Cortez <vitoracortez+github@gmail.com>
 */
var convertJSBooleanToCBoolean = function(bool) {
  if (bool === false && bool !== true) {
    return 0;
  } else if (bool === true && bool !== false) {
    return 1;
  } else {
    return Infinity;
  }
};

anything.prototype.convertJSBooleanToCBoolean = convertJSBooleanToCBoolean;


text:
package cloud::aws::billing::plugin;

use strict;
use warnings;
use base qw(centreon::plugins::script_custom);

sub new {
    my ( $class, %options ) = @_;
    my $self = $class->SUPER::new( package => __PACKAGE__, %options );
    bless $self, $class;

    $self->{version} = '0.1';
    %{ $self->{modes} } = (
        'estimated-charges'     => 'cloud::aws::billing::mode::estimatedcharges',
        'list-services'         => 'cloud::aws::billing::mode::listservices',
    );

    $self->{custom_modes}{paws} = 'cloud::aws::custom::paws';
    $self->{custom_modes}{awscli} = 'cloud::aws::custom::awscli';
    return $self;
}

1;

__END__

=head1 PLUGIN DESCRIPTION

Check Amazon Billing.

Works for 'us-east-1' region only.

=cut


text:
const assert = require('assert')
const process = require('process')
const TwitchApi = require('../src/index.js')

describe('TwitchApi', () => {
  const scopes = ['user_read', 'channel_read', 'chat_login', 'channel_feed_edit', 'channel_subscriptions', 'channel_editor'];
  const clientId = process.env.TWITCH_CLIENT_ID
  const clientSecret = process.env.TWITCH_CLIENT_SECRET
  const redirectUri = 'https://example.com'
  const accessToken = process.env.ACCESS_TOKEN;

  const twitch = new TwitchApi({
    clientId,
    clientSecret,
    redirectUri,
    scopes
  });
  const oldTwitch = new TwitchApi({
    clientId,
    clientSecret,
    redirectUri,
    scopes,
    version: 3
  })

  describe('getGames()', () => {
    it('get games', () => {
      oldTwitch.getGames()
        .then(games => {
          assert.equal(typeof games._total, 'number');
          assert.equal(Array.isArray(games.top), true);
        });
    })
  });

  describe('getAuthorizationUrl()', () => {
    it('match url', () => {
      const url = twitch.getAuthorizationUrl()
      const expected = `https://id.twitch.tv/oauth2/authorize?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scopes.join('+')}`
      return assert.strictEqual(url, expected)
    })
  })

  describe('getUser()', () => {
    it('fetch single user: 139658194 (jake_loo)', () => {
      const expected = {
        display_name: "jake_loo",
        _id: "139658194",
        name: "jake_loo",
        type: "user"
      }

      return twitch.getUser("139658194")
      .then((b) => {
        const user = b;
        const expectUser = expected;

        // we only care about couple field is correct
        assert.strictEqual(user.display_name, expectUser.display_name)
        assert.strictEqual(user._id, expectUser._id)
        assert.strictEqual(user.name, expectUser.name)
        assert.strictEqual(user.type, expectUser.type)
        return true
      })
    })

    it('fetch two user: jake_loo, jake_loo_dev, jake_loo_prod', () => {
      return twitch.getUsersLogin(['jake_loo', 'jake_loo_dev', 'jake_loo_prod'])
      .then((b) => {
        // we only care about couple field is correct
        assert.strictEqual(b._total, 3)
        assert.strictEqual(b.users.length, 3)
        return true
      })
    })

    it('fetch an invalid user', () => {
      // Twitch doesn't allow query with invalid character nor 1 character login name, so test it with UUID
      return twitch.getUsersLogin(['e331a9f237fc480d968c87af6c6ed552'])
        .then((b) => assert.strictEqual(b._total, 0))
    })

    it('fetch an invalid and a valid user', () => {
      // Twitch doesn't allow query with invalid character nor 1 character login name, so test it with UUID
      return twitch.getUsersLogin(['e331a9f237fc480d968c87af6c6ed552', 'jake_loo'])
      .then((b) => {
        assert.strictEqual(b._total, 1)
        assert.strictEqual(b.users.length, 1)
      })
    })
  })

  describe('getChannel()', () => {
    it('fetch channel: theonlyjohnny_jd_', () => {
      let social_id = '';
      return twitch.getUsersLogin(['theonlyjohnny_jd_'])
      .then(({users})=> {
        const user = users[0];
        social_id = user._id;
        return twitch.getChannel(social_id);
      })
      .then(chan => {
        assert.equal(chan.display_name, 'theonlyjohnny_jd_');
        assert.equal(typeof chan.status, 'string');
        assert.equal(typeof chan.game, 'string');
        assert.equal(chan._id, social_id);
      })
    })
  });

  describe('updateChannel()', () => {
    let channel = {};
    it('fetch channel: theonlyjohnny_jd_', () => {
      let social_id = '';
      return twitch.getUsersLogin(['theonlyjohnny_jd_'])
      .then(({users})=> {
        const user = users[0];
        social_id = user._id;
        return twitch.getChannel(social_id);
      })
      .then(chan => {
        assert.equal(chan.display_name, 'theonlyjohnny_jd_');
        assert.equal(typeof chan.status, 'string');
        assert.equal(typeof chan.game, 'string');
        assert.equal(chan._id, social_id);
        channel = chan;
      })
    })

    it('update channel: theonlyjohnny_jd_', () => {
      const update = { status: `twitch-api test @${Date.now()}` }
      return twitch.updateChannel(channel._id, update, accessToken)
        .then(res => {
          assert.equal(update.status, res.status);
        });
    })
  })

  describe('getChannelSubscriptions', () => {
    it('fetch subscriptions list: theonlyjohnny_jd_', () => {
      return oldTwitch.getChannelSubscriptions('theonlyjohnny_jd_', accessToken, { limit: 50 });
       /* idk what asserts to do here tbh lol  */
    });
  });

  describe('getUsersLogin()', () => {
    it('fetch single user: jake_loo', () => {
      const expected = {
        _total: 1,
        users:[
          {
            display_name: "jake_loo",
            _id: "139658194",
            name: "jake_loo",
            type: "user"
          }
        ]
      }

      return twitch.getUsersLogin(['jake_loo'])
      .then((b) => {
        // we only care about couple field is correct
        assert.strictEqual(b._total, expected._total)
        assert.strictEqual(b.users.length, expected.users.length)

        const user = b.users[0];
        const expectUser = expected.users[0];

        assert.strictEqual(user.display_name, expectUser.display_name)
        assert.strictEqual(user._id, expectUser._id)
        assert.strictEqual(user.name, expectUser.name)
        assert.strictEqual(user.type, expectUser.type)
        return true
      })
    })

    it('fetch two user: jake_loo, jake_loo_dev, jake_loo_prod', () => {
      return twitch.getUsersLogin(['jake_loo', 'jake_loo_dev', 'jake_loo_prod'])
      .then((b) => {
        // we only care about couple field is correct
        assert.strictEqual(b._total, 3)
        assert.strictEqual(b.users.length, 3)
        return true
      })
    })

    it('fetch an invalid user', () => {
      // Twitch doesn't allow query with invalid character nor 1 character login name, so test it with UUID
      return twitch.getUsersLogin(['e331a9f237fc480d968c87af6c6ed552'])
        .then((b) => assert.strictEqual(b._total, 0))
    })

    it('fetch an invalid and a valid user', () => {
      // Twitch doesn't allow query with invalid character nor 1 character login name, so test it with UUID
      return twitch.getUsersLogin(['e331a9f237fc480d968c87af6c6ed552', 'jake_loo'])
      .then((b) => {
        assert.strictEqual(b._total, 1)
        assert.strictEqual(b.users.length, 1)
      })
    })
  })

  describe('checkAuthStatus', () => {
    it('fetches', () => twitch.checkAuthStatus(accessToken));
    it('is well formed', () => twitch.checkAuthStatus(accessToken)
      .then(response => {
        assert.equal(Boolean(response && response.token), true);
      })
    );

    it('is valid auth', () => twitch.checkAuthStatus(accessToken)
      .then(response => response.token)
      .then(token => assert.strictEqual(token.valid, true))
    );
  });

})


text:
require 'rails_helper'

RSpec.describe Instance::Announcement do
  let!(:instance) { create(:instance) }
  with_tenant(:instance) do
    subject { Ability.new(user) }
    let(:course) { create(:course) }
    let!(:not_started_announcement) { create(:instance_announcement, :not_started) }
    let!(:ended_announcement) { create(:instance_announcement, :ended) }
    let!(:valid_announcement) { create(:instance_announcement) }

    context 'when the user is a Instance User' do
      let(:user) { create(:instance_user).user }

      it { is_expected.to be_able_to(:show, valid_announcement) }
      it { is_expected.to be_able_to(:show, ended_announcement) }
      it { is_expected.not_to be_able_to(:show, not_started_announcement) }
      it { is_expected.not_to be_able_to(:manage, valid_announcement) }

      it 'sees the started announcements' do
        expect(instance.announcements.accessible_by(subject)).
          to contain_exactly(valid_announcement, ended_announcement)
      end
    end

    context 'when the user is a Instance Administrator' do
      let(:user) { create(:instance_administrator).user }

      it { is_expected.to be_able_to(:manage, valid_announcement) }
      it { is_expected.to be_able_to(:manage, ended_announcement) }
      it { is_expected.to be_able_to(:manage, not_started_announcement) }

      it 'sees all announcements' do
        expect(instance.announcements.accessible_by(subject)).
          to contain_exactly(not_started_announcement, valid_announcement, ended_announcement)
      end
    end
  end
end


text:
using UnityEngine;

public class Infringeable : MonoBehaviour
{
    public GameObject Player;

    private PlayerManager _playerManager;

	// Use this for initialization
	void Start()
    {
        if (this.Player == null) this.Player = GameObject.Find("Player");

        _playerManager = this.Player.GetComponent<PlayerManager>();
	}

	// Update is called once per frame
	void Update()
    {

	}

    void OnCollisionEnter(Collision collision)
    {
        Debug.Log(collision);

        Debug.Log(collision.gameObject);

        if (collision.gameObject == this.Player) _playerManager.InfringeACopyright();

        Destroy(gameObject);
    }
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.pd.test</groupId>
    <artifactId>restVersioning</artifactId>
    <packaging>war</packaging>
    <version>1.0.0-SNAPSHOT</version>

    <repositories>
        <repository>
            <id>central</id>
            <name>Maven Repository Switchboard</name>
            <layout>default</layout>
            <url>http://repo1.maven.org/maven2</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>central</id>
            <name>Maven Plugin Repository</name>
            <url>http://repo1.maven.org/maven2</url>
            <layout>default</layout>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
        </pluginRepository>
    </pluginRepositories>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>4.1.1.RELEASE</spring.version>
        <slf4j.version>1.7.7</slf4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.jayway.jsonpath</groupId>
            <artifactId>json-path</artifactId>
            <version>0.9.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.3.0</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>log4j-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.1.2</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.5</version>
        </dependency>

    </dependencies>

    <build>

        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.1</version>
                <configuration>
                    <path>/</path>
                    <contextReloadable>false</contextReloadable>
                    <useTestClasspath>false</useTestClasspath>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace Nest
{
	[JsonConverter(typeof(StringEnumConverter))]
	public enum GeoOptimizeBBox
	{
		[EnumMember(Value = "memory")]
		Memory,
		[EnumMember(Value = "indexed")]
		Indexed,
		[EnumMember(Value = "none")]
		None
	}

	[JsonConverter(typeof(StringEnumConverter))]
	public enum GeoValidationMethod
	{
		[EnumMember(Value = "coerce")]
		Coerce,
		[EnumMember(Value = "ignore_malformed")]
		IgnoreMalformed,
		[EnumMember(Value = "strict")]
		Strict
	}
}


text:
package se.microcode.cogwork;

import java.util.List;

public class Team
{
    public String classType;
    public List<String> names;
    public List<String> clubs;
    public String state;

    public String getClassType()
    {
        return classType;
    }

    public List<String> getNames()
    {
        return names;
    }

    public int getNameCount()
    {
        return names.size();
    }

    public List<String> getClubs()
    {
        return clubs;
    }

    public int getClubCount()
    {
        return clubs.size();
    }

    public String getState()
    {
        return state;
    }
}


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class DeleteTables extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        //
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('choice');
        Schema::drop('question');
        Schema::drop('type');
        Schema::drop('category');
        Schema::drop('survey');
        Schema::drop('examen');
        Schema::drop('users');
        Schema::drop('coordinates');
        Schema::drop('group');
        Schema::drop('roles');
        Schema::drop('password_resets');
    }
}


text:
[#escape x as (x)!?html]
<!DOCTYPE html>

<meta charset="utf-8" />
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="author" content="atarm" />
<title>长沙银行OA办公系统 -- Powerd by Jspxcms</title>
<meta name="description" content="长沙银行OA办公系统 " />
<meta name="keywords" content="长沙银行OA办公系统 " />

<link
	href="${CTX}/static/vendor/metronic/assets/global/plugins/bootstrap/css/bootstrap.min.css"
	rel="stylesheet">

<link href="${CTX}/static/vendor/metronic/assets/global/css/components.css"
	rel="stylesheet">
<link href="${CTX}/static/vendor/metronic/assets/frontend/layout/css/style.css"
	rel="stylesheet">
<link
	href="${CTX}/static/vendor/metronic/assets/frontend/layout/css/style-responsive.css"
	rel="stylesheet">
<link href="${CTX}/static/vendor/metronic/assets/admin/layout/css/layout.css"
	rel="stylesheet">
<link href="${CTX}/static/css/oa.css" rel="stylesheet">

	[#include "../common/a_header.ftl"/]

					<button type="button" class="btn default">提交</button>
					<button type="button" class="btn default">返回</button>
					<button type="button" class="btn default">打印</button>
					<button type="button" class="btn default">过程跟踪</button>

								零售业务审批

 流程信息

 附件

 审批提交

								[#include "../flow_view.ftl"/]

										当前审批环节:业务处理人处理

													选择活动 <select class="form-control">
														<option>返回给申请人</option>
														<option>信息技术部经理审批</option>
														<option>业务处理人处理</option>
													</select>

												<input type="text" class="form-control form-filter"
													id="approver" name="approver" disabled>
												<button type="button" onclick="Tree.openModal()"
													class="btn default">选择执行人</button>

												审批意见
												<textarea class="form-control" placeholder="请在此填写审批意见"
													rows="4"></textarea>

	[#include "../common/select_approver_modal.ftl"/]

[/#escape]


text:
package org.mifos.platform.rest.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * This is a dummy rest controller which is used to make sure if the rest services are available
 *
 * /mifos/status.json
 *
 */
@Controller
public class StatusRESTController {

    @RequestMapping(value="status", method = RequestMethod.GET)
    public @ResponseBody
    StatusJSON status() {
        StatusJSON json = new StatusJSON();
        json.setStatus("Success");
        return json;
    }

    @RequestMapping(value="accessDenied", method = RequestMethod.GET)
    public @ResponseBody
    StatusJSON accessDenied() {
        StatusJSON json = new StatusJSON();
        json.setStatus("session expired");
        return json;
    }

    @RequestMapping(value="restLogin", method = RequestMethod.GET)
    public String restLoginForm() {
        return "restLogin";
    }

}

class StatusJSON {

    private String status;

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}


text:
from __future__ import division, print_function, absolute_import, unicode_literals

import numpy as np

from .parse_dm3 import *

structarray_to_np_map = {
    ('d', 'd'): np.complex128,
    ('f', 'f'): np.complex64}

np_to_structarray_map = {v: k for k, v in structarray_to_np_map.items()}

# we want to amp any image type to a single np array type
# but a sinlge np array type could map to more than one dm type.
# For the moment, we won't be strict about, eg, discriminating
# int8 from bool, or even unit32 from RGB. In the future we could
# convert np bool type eg to DM bool and treat y,x,3 int8 images
# as RGB.

# note uint8 here returns the same data type as int8 - could be that the
# only way they're differentiated is via this type, not the raw type
# in the tag file? Might be same for PackedComplex images too
# And 8 is missing!
dm_image_dtypes = {
    1: ("int16", np.int16),
    2: ("float32", np.float32),
    3: ("Complex64", np.complex64),
    6: ("uint8", np.int8),
    7: ("int32", np.int32),
    9: ("int8", np.int8),
    10: ("uint16", np.uint16),
    11: ("uint32", np.uint32),
    12: ("float64", np.float64),
    13: ("Complex128", np.complex128),
    14: ("Bool", np.int8),
    23: ("RGB", np.int32),
    27: ("PackedComplex64", np.float32),
    28: ("PackedComplex128", np.float64)
}

def imagedatadict_to_ndarray(imdict):
    """
    Converts the ImageData dictionary, imdict, to an nd image.
    """
    arr = imdict['Data']
    im = None
    if isinstance(arr, array.array):
        im = np.asarray(arr, dtype=arr.typecode)
    elif isinstance(arr, structarray):
        t = tuple(arr.typecodes)
        im = np.frombuffer(
            arr.raw_data,
            dtype=structarray_to_np_map[t])
    # print "Image has dmimagetype", imdict["DataType"], "numpy type is", im.dtype
    assert dm_image_dtypes[imdict["DataType"]][1] == im.dtype
    assert imdict['PixelDepth'] == im.dtype.itemsize
    return im.reshape(imdict['Dimensions'][::-1])

def ndarray_to_imagedatadict(nparr):
    """
    Convert the numpy array nparr into a suitable ImageList entry dictionary.
    Returns a dictionary with the appropriate Data, DataType, PixelDepth
    to be inserted into a dm3 tag dictionary and written to a file.
    """
    ret = {}
    dm_type = (k for k, v in dm_image_dtypes.items() if v[1] == nparr.dtype.type).next()
    ret["DataType"] = dm_type
    ret["PixelDepth"] = nparr.dtype.itemsize
    ret["Dimensions"] = list(nparr.shape[::-1])
    if nparr.dtype.type in np_to_structarray_map:
        types = np_to_structarray_map[nparr.dtype.type]
        ret["Data"] = structarray(types)
        ret["Data"].raw_data = str(nparr.data)
    else:
        ret["Data"] = array.array(nparr.dtype.char, nparr.flatten())
    return ret

def load_image(file):
    """
    Loads the image from the file-like object or string file.
    If file is a string, the file is opened and then read.
    Returns a numpy ndarray of our best guess for the most important image
    in the file.
    """
    if isinstance(file, str):
        with open(file, "rb") as f:
            return load_image(f)
    dmtag = parse_dm_header(file)
    img_index = -1
    return imagedatadict_to_ndarray(dmtag['ImageList'][img_index]['ImageData'])

def save_image(image, file):
    """
    Saves the nparray image to the file-like object (or string) file.
    If file is a string the file is created and written to
    """
    if isinstance(file, str):
        with open(file, "wb") as f:
            return save_image(image, f)
    # we need to create a basic DM tree suitable for an imge
    # we'll try the minimum: just an image list
    # doesn't work. Do we need a ImageSourceList too?
    # and a DocumentObjectList?
    image = ndarray_to_imagedatadict(image)
    ret = {}
    ret["ImageList"] = [{"ImageData": image}]
    # I think ImageSource list creates a mapping between ImageSourceIds and Images
    ret["ImageSourceList"] = [{"ClassName": "ImageSource:Simple", "Id": [0], "ImageRef": 0}]
    # I think this lists the sources for the DocumentObjectlist. The source number is not
    # the indxe in the imagelist but is either the index in the ImageSourceList or the Id
    # from that list. We also need to set the annotation type to identify it as an image
    ret["DocumentObjectList"] = [{"ImageSource": 0, "AnnotationType": 20}]
    # finally some display options
    ret["Image Behavior"] = {"ViewDisplayID": 8}
    ret["InImageMode"] = 1
    parse_dm_header(file, ret)


text:
class CreateElements < ActiveRecord::Migration
  def change
    create_table :elements do |t|
      t.integer :folio_id
      t.string :title
      t.string :description
      t.string :citation
      t.string :element_link
      t.string :font
      t.string :color
      t.string :width

      t.timestamps null: false
    end
  end
end


text:
class CDateTimePage : public CPropertyPage
{
	DECLARE_DYNCREATE(CDateTimePage)

// Construction
public:
	void OnDTNotify(NMHDR *pHdr, LRESULT *pRes);
	CListBox m_lbNotifyList;
	UINT m_nPrevStyle;
	void SetCheck(UINT idBtn);
	CDateTimeCtrl m_DateTime;
	CDateTimePage();
	~CDateTimePage();

// Dialog Data
	//{{AFX_DATA(CDateTimePage)
	enum { IDD = IDD_DATETIME };
	BOOL    m_bAppCanParse;
	BOOL    m_bShowNone;
	BOOL    m_bUpDown;
	//}}AFX_DATA

// Overrides
	// ClassWizard generate virtual function overrides
	//{{AFX_VIRTUAL(CDateTimePage)
	public:
	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV support
	//}}AFX_VIRTUAL

// Implementation
protected:
	// Generated message map functions
	//{{AFX_MSG(CDateTimePage)
	virtual BOOL OnInitDialog();
	afx_msg void OnCkupdown();
	afx_msg void OnCktimeformat();
	afx_msg void OnCkshortdateformat();
	afx_msg void OnCkshownone();
	afx_msg void OnCklongdateformat();
	afx_msg void OnCkappcanparse();
	//}}AFX_MSG
	DECLARE_MESSAGE_MAP()

};

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.

#endif // !defined(AFX_DATETIME_H__39010224_ECB6_11D0_8FEA_00A0C9034892__INCLUDED_)


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicsDataExplorer.Bean
{
    /// <summary>
    /// カラム設定を保存するためのBean
    /// </summary>
    [Serializable]
    public class ColumnSettingBean
    {
        public string DataPropertyName { get; set; }
        public string Name { get; set; }
        public string HeaderText { get; set; }
        public Object ListItem { get; set; }
    }
}


text:
[ ${#} -eq 0 ] && sh ${0} help && exit
[ ${#} -eq 1 ] && [ ${1} = "first" ] && sh ${0} create start install install_node install_emscripten install_android_sdk_ndk put && exit
[ ${#} -eq 1 ] && [ ${1} = "last" ] && sh ${0} stop clear && exit

DOCKER_CONTAINER_NAME_01=docker-fuhaha-builder
DOCKER_LINUX=ubuntu:16.04
EMSCRIPTEN_VERSION=sdk-fastcomp-1.37.27-64bit
ANDROID_SDK_VERSION=r24.4.1
ANDROID_NDK_VERSION=r10e
PROJECT=${PWD##*/}

# makeコマンド このコマンドだけはオプションをつけることができる
[ ${#} -ge 1 ] && [ ${1} = "make" ] && {
	# 最初にファイル転送
	sh ${0} put
	echo -------- make start --------
	# makeコマンド作成と実行
	MAKE_COMMAND="cd /root/${PROJECT}"
	MAKE_COMMAND+=" && export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64"
	MAKE_COMMAND+=" && export ANDROID_HOME=/opt/android-sdk-${ANDROID_SDK_VERSION}"
	MAKE_COMMAND+=" && export ANDROID_NDK_HOME=/opt/android-ndk-${ANDROID_NDK_VERSION}"
	MAKE_COMMAND+=" && . /opt/emsdk/emsdk_env.sh"
	MAKE_COMMAND+=" && make ${@:$((1 + 1))}"
	docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c "${MAKE_COMMAND}"
	echo -------- make exit --------
	echo -------- get start --------
	# 最後にファイル転送
	SYNC_TARGET_01=src_client/platform_web/bin
	SYNC_TARGET_02=src_client/platform_android/build/outputs/apk
	mkdir -p ./${SYNC_TARGET_01}
	mkdir -p ./${SYNC_TARGET_02}
	rsync --blocking-io -e 'docker exec -i' -rltDv ${DOCKER_CONTAINER_NAME_01}:/root/${PROJECT}/${SYNC_TARGET_01}/ ./${SYNC_TARGET_01}/
	rsync --blocking-io -e 'docker exec -i' -rltDv ${DOCKER_CONTAINER_NAME_01}:/root/${PROJECT}/${SYNC_TARGET_02}/ ./${SYNC_TARGET_02}/
	echo -------- get exit --------
	# スクリプトを抜ける
	exit
}

for ARG in "${@}" ; do
	echo -------- ${ARG} start --------
	# 引数解釈
	case ${ARG} in
		status)
			docker network ls && echo '--------' && docker images && echo '--------' && docker ps -a
			;;
		create)
			docker create --name ${DOCKER_CONTAINER_NAME_01} --publish 8080:8080 --interactive --tty ${DOCKER_LINUX} /bin/bash --login
			[ ${?} -gt 0 ] && exit
			;;
		start)
			docker start ${DOCKER_CONTAINER_NAME_01}
			;;
		bash)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash
			;;
		stop)
			docker stop ${DOCKER_CONTAINER_NAME_01}
			;;
		clear)
			docker rm ${DOCKER_CONTAINER_NAME_01}
			;;
		install)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'apt-get update'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y rsync'
			;;
		install_node)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y wget'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y npm'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'npm cache clean'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'npm install n -g'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'n v9.3.0'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'ln -s /usr/local/bin/node /usr/bin/node'
			;;
		install_emscripten)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y wget'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y cmake'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y python'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y python2.7'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y nodejs'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y default-jre'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y git-core'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && git clone https://github.com/emscripten-core/emsdk.git'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt/emsdk && ./emsdk update-tags'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt/emsdk && ./emsdk install '${EMSCRIPTEN_VERSION}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt/emsdk && ./emsdk activate '${EMSCRIPTEN_VERSION}
			;;
		install_android_sdk_ndk)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y wget'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y expect'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y openjdk-8-jdk'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y lib32stdc++6'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'DEBIAN_FRONTEND=noninteractive apt-get install -y lib32z1'
			ANDROID_SDK_FILE="android-sdk_${ANDROID_SDK_VERSION}-linux.tgz"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && wget https://dl-ssl.google.com/android/'${ANDROID_SDK_FILE}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && tar -zxvf '${ANDROID_SDK_FILE}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'mv /opt/android-sdk-linux /opt/android-sdk-'${ANDROID_SDK_VERSION}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c '/opt/android-sdk-'${ANDROID_SDK_VERSION}'/tools/android list sdk --all --extended'
			ANDROID_EXPECT_COMMAND_01='set timeout -1 ; spawn /opt/android-sdk-'${ANDROID_SDK_VERSION}'/tools/android update sdk --no-ui --all --filter'
			ANDROID_EXPECT_COMMAND_02='; expect "Do you accept the license" { send "y\n" ; exp_continue } Downloading { exp_continue } Installing { exp_continue }'
			docker exec -it ${DOCKER_CONTAINER_NAME_01} expect -c "${ANDROID_EXPECT_COMMAND_01} android-23 ${ANDROID_EXPECT_COMMAND_02}"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} expect -c "${ANDROID_EXPECT_COMMAND_01} build-tools-23.0.2 ${ANDROID_EXPECT_COMMAND_02}"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} expect -c "${ANDROID_EXPECT_COMMAND_01} extra-google-m2repository ${ANDROID_EXPECT_COMMAND_02}"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} expect -c "${ANDROID_EXPECT_COMMAND_01} extra-android-m2repository ${ANDROID_EXPECT_COMMAND_02}"
			ANDROID_NDK_FILE="android-ndk-${ANDROID_NDK_VERSION}-linux-x86_64.bin"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && wget https://dl-ssl.google.com/android/ndk/'${ANDROID_NDK_FILE}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && chmod +x '${ANDROID_NDK_FILE}
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'cd /opt && ./'${ANDROID_NDK_FILE}
			;;
		sync_put|put)
			RSYNC_SRC=./
			RSYNC_DST=${DOCKER_CONTAINER_NAME_01}:/root/${PROJECT}/
			RSYNC_COMMAND="rsync --blocking-io -e 'docker exec -i' --exclude='.git' --filter=':- .gitignore' -rltDv"
			eval ${RSYNC_COMMAND} ${RSYNC_SRC} ${RSYNC_DST}
			;;
		sync_get|get)
			RSYNC_SRC=${DOCKER_CONTAINER_NAME_01}:/root/${PROJECT}/
			RSYNC_DST=./
			RSYNC_COMMAND="rsync --blocking-io -e 'docker exec -i' --exclude='.git' --filter=':- .gitignore' -rltDv"
			eval ${RSYNC_COMMAND} ${RSYNC_SRC} ${RSYNC_DST}
			;;
		restore)
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'rm -rf /root/'${PROJECT}/src_client/fuhahaEngine
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c 'rm -rf /root/'${PROJECT}/src_client/main
			;;
		serve)
			COMMAND="cd /root/${PROJECT}"
			COMMAND+=" && node src_server/node/main.js"
			docker exec -it ${DOCKER_CONTAINER_NAME_01} /bin/bash -c "${COMMAND}"
			;;
		browse)
			DOCKER_IP=$(docker inspect -f '{{.NetworkSettings.IPAddress}}' ${DOCKER_CONTAINER_NAME_01})
			DOCKER_HOSTIP=$(docker inspect -f '{{(index (index .NetworkSettings.Ports "8080/tcp") 0).HostIp}}' ${DOCKER_CONTAINER_NAME_01})
			DOCKER_HOSTPORT=$(docker inspect -f '{{(index (index .NetworkSettings.Ports "8080/tcp") 0).HostPort}}' ${DOCKER_CONTAINER_NAME_01})
			open http://${DOCKER_HOSTIP}:${DOCKER_HOSTPORT}
			;;
		help)
			echo create or status or start or install or put or get or restore or make or serve or browse or bash or stop or clear
			;;
		*)
			echo nothing to do
	esac
	echo -------- ${ARG} exit --------
done


text:
from django.conf.urls import url, include

from django.contrib.auth.views import login as django_login
from django.contrib.auth.views import logout as django_logout

from . import views

urlpatterns = [
    url(r'^$', views.index, name="index"),
    url(r'^u/(?P<label>[\w-]{,50})$', views.underground_comptoir),
    url(r'^agora$', views.underground_comptoir, name="agora"),

    # Django authentication views
    url(r'^login$', django_login, name="login"),
    url(r'^logout$', django_logout, name="logout"),
    # Custom register view
    url(r'^register$', views.register, name="register"),
]


text:
import unittest
import mock

from botocore import xform_name
import botocore.session

from touchdown.core import serializers

from touchdown.aws import common
from touchdown.aws.elasticache import CacheCluster

class TestGenericAction(unittest.TestCase):

    def test_basic_call(self):
        api = mock.Mock()
        plan = mock.Mock()

        plan.resource = CacheCluster(None, name='freddy')

        g = common.GenericAction(plan, "I am an action", api, serializer=serializers.Resource())
        self.assertEqual(tuple(g.description), ("I am an action", ))
        g.run()

        api.assert_called_with(
            NumCacheNodes=1,
            CacheClusterId='freddy',
        )

class TestSimpleDescribeImplementations(unittest.TestCase):

    ignore = (
        common.SimpleApply,
        common.SimpleDestroy,
    )

    def test_valid(self):
        session = botocore.session.get_session()
        for impl in common.SimpleDescribe.__subclasses__():
            if issubclass(impl, self.ignore):
                continue

            if impl.describe_action is None:
                continue

            service = session.get_service_model(impl.service_name)
            methods = {xform_name(s): s for s in service.operation_names}
            operation = service.operation_model(methods[impl.describe_action])

            if "." not in impl.describe_envelope and ":" not in impl.describe_envelope:
                self.assertEqual(
                    impl.describe_envelope in operation.output_shape.members,
                    True
                )


text:
<form action="form_result.php" method="post" enctype="multipart/form-data">

XLS (Specialist Project) to EOL format

        XLS File URL: <input type="text" name="url" size="100" style="font-size : x-small; font-family : Arial;">

        e.g. http://mydomain.org/my_spreadsheet.xls

        Download the spreadsheet template here for specialist projects.

        XLS File Upload: <input type="file" name="file_upload" id="file_upload" size="100"
        style="font-size : x-small; font-family : Arial;">

        <input type="submit" value="Convert to EOL-compliant XML">
        <input type='reset' value='Reset'>
        <input type="checkbox" name="validate">Validate

Content Partner >>

</form>


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('google_auth', '0001_initial'),
    ]

    operations = [
        migrations.AlterField(
            model_name='googleauthuser',
            name='access_token',
            field=models.CharField(max_length=254, null=True),
        ),
        migrations.AlterField(
            model_name='googleauthuser',
            name='refresh_token',
            field=models.CharField(max_length=254, null=True),
        ),
        migrations.AlterField(
            model_name='googleauthuser',
            name='token_expiry',
            field=models.DateTimeField(null=True),
        ),
    ]


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.Core;

namespace UserDefinedToolbarAddin
{
  public class SearchPathDoozer : IDoozer
  {
    public bool HandleConditions
    {
      get { return false; }
    }

    public object BuildItem(BuildItemArgs args)
    {
      Codon codon = args.Codon;
      return new SearchPathDescriptor(codon.Properties["path"], codon.Properties["category"]);
    }
  }
}


text:
/**
 * ResponseBuilder interfaces for HAL responses
 */
/**
 * @author patrickvk
 *
 */
package net.eusashead.hateoas.hal.response;

/*
 * #[license]
 * spring-halbuilder
 * %%
 * Copyright (C) 2013 Eusa's Head
 * %%
 * 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.
 * %[license]
 */


text:
#include <aws/healthlake/model/InputDataConfig.h>
#include <aws/core/utils/json/JsonSerializer.h>

#include <utility>

using namespace Aws::Utils::Json;
using namespace Aws::Utils;

namespace Aws
{
namespace HealthLake
{
namespace Model
{

InputDataConfig::InputDataConfig() :
    m_s3UriHasBeenSet(false)
{
}

InputDataConfig::InputDataConfig(JsonView jsonValue) :
    m_s3UriHasBeenSet(false)
{
  *this = jsonValue;
}

InputDataConfig& InputDataConfig::operator =(JsonView jsonValue)
{
  if(jsonValue.ValueExists("S3Uri"))
  {
    m_s3Uri = jsonValue.GetString("S3Uri");

    m_s3UriHasBeenSet = true;
  }

  return *this;
}

JsonValue InputDataConfig::Jsonize() const
{
  JsonValue payload;

  if(m_s3UriHasBeenSet)
  {
   payload.WithString("S3Uri", m_s3Uri);

  }

  return payload;
}

} // namespace Model
} // namespace HealthLake
} // namespace Aws


text:
"""
Trigger the conda-forge.github.io Travis job to restart.
"""

import argparse
import os

import requests
import six

import conda_smithy.ci_register

def rebuild_travis(repo_slug):
    headers = conda_smithy.ci_register.travis_headers()

    # If we don't specify the API version, we get a 404.
    # Also fix the accepted content type.
    headers["Accept"] = "application/json"
    headers["Travis-API-Version"] = "3"

    # Trigger a build on `master`.
    encoded_slug = six.moves.urllib.parse.quote(repo_slug, safe='')
    url = 'https://api.travis-ci.org/repo/{}/requests'.format(encoded_slug)
    response = requests.post(
        url,
        json={
            "request": {
                "branch": "master",
                "message": "Triggering build from staged-recipes",
            }
        },
        headers=headers
    )
    if response.status_code != 201:
        print(response.content)
        response.raise_for_status()

def main(argv):
    parser = argparse.ArgumentParser(description="Trigger Travis CI build.")
    parser.add_argument("slug", type=str, help="repo to trigger build for")

    args = parser.parse_args(argv[1:])

    rebuild_travis(args.slug)

    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main(sys.argv))


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>io.joshworks.snappy</groupId>
        <artifactId>plugin</artifactId>
        <version>0.6.0</version>
    </parent>
    <artifactId>snappy-maven-plugin</artifactId>
    <packaging>maven-plugin</packaging>

    <distributionManagement>
        <snapshotRepository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
        </snapshotRepository>
        <repository>
            <id>ossrh</id>
            <url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url>
        </repository>
    </distributionManagement>

    <dependencies>
        <dependency>
            <groupId>io.joshworks.snappy</groupId>
            <artifactId>snappy-loader</artifactId>
            <version>${project.parent.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-archiver</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-settings</artifactId>
            <version>3.1.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.shared</groupId>
            <artifactId>maven-common-artifact-filters</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-archiver</artifactId>
            <version>2.8.1</version>
            <exclusions>
                <exclusion>
                    <groupId>org.codehaus.plexus</groupId>
                    <artifactId>plexus-container-default</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.codehaus.plexus</groupId>
                    <artifactId>plexus-component-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-utils</artifactId>
            <version>3.0.20</version>
        </dependency>
        <!-- Optional -->
        <dependency>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.2</version>
            <optional>true</optional>
        </dependency>
        <!-- Provided -->
        <dependency>
            <groupId>org.apache.maven.plugin-tools</groupId>
            <artifactId>maven-plugin-annotations</artifactId>
            <version>3.2</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.2.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.21</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.1</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>2.7.13</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-library</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-plugin-plugin</artifactId>
                <version>3.3</version>
                <dependencies>
                    <dependency>
                        <groupId>org.ow2.asm</groupId>
                        <artifactId>asm</artifactId>
                        <version>6.2.1</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <goalPrefix>snappy</goalPrefix>
                    <skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
                </configuration>
                <executions>
                    <execution>
                        <id>generate-descriptor</id>
                        <goals>
                            <goal>descriptor</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>generated-helpmojo</id>
                        <goals>
                            <goal>helpmojo</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <!-- COPIES THE LOADER INSIDE META-INF SO IT CAN BE USED LATER INSIDE THE CODE TO COPY ITS CLASSES TO THE FINAL JAR-->

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.10</version>
                <executions>
                    <execution>
                        <id>include-layout-jar</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>io.joshworks.snappy</groupId>
                                    <artifactId>snappy-loader</artifactId>
                                    <version>${project.parent.version}</version>
                                    <destFileName>snappy-loader.jar</destFileName>
                                </artifactItem>
                            </artifactItems>
                            <outputDirectory>${basedir}/target/generated-resources/loader/META-INF/loader
                            </outputDirectory>
                            <overWriteReleases>false</overWriteReleases>
                            <overWriteSnapshots>true</overWriteSnapshots>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>build-helper-maven-plugin</artifactId>
                <version>1.10</version>
                <executions>
                    <execution>
                        <id>add-resources</id>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>add-resource</goal>
                        </goals>
                        <configuration>
                            <resources>
                                <resource>
                                    <directory>${basedir}/target/generated-resources/loader</directory>
                                </resource>
                            </resources>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <version>3.0.2</version>
                <configuration>
                    <archive>
                        <manifest>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                            <addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>


text:
@interface DFSTextAnnotationView : MKAnnotationView
@end