text:
function RunClusteringVirilis(wav_file, prevtempfile, whichsignal, ipiptl, segopts, doplots, remnoise)
    %To do: Save pulse train parameters together so cutoff can be adjusted
    %To do: Load previously assigned data if available
    %To do: Save output files in a different folder.
    %Alternative: Move files after creating them (in bash wrapper).
    %To do: Make saving male and female separately optional.
    %New: allow specification of minimum # pulses (minpulse) in segopts
    %New: allow specification of start and end song time (song_range) in segopts
    %Now uses addpath rather than changing directories.
    %If any issues, check if multiple paths have same script names).
    %Added option: ipiptl can be 'IPI','PTL', or 'both'
    %PTL/PPB analysis now ONLY run with 5-pulse minimum (not all trains)
    %Parameters now saved separately for male and female (using 'femalecut'
    %for IPI threshold)
    %Template filename taken out of final filename (too long)
    %Adding option to remove noise peaks from empty channel.
    if nargin < 7
        remnoise = 'FALSE';
        if nargin < 6
            doplots = 'TRUE';
        end
    end
    clearvars -except wav_file prevtempfile whichsignal ipiptl segopts doplots remnoise;
    relvars = {'fs','diffThreshold','template_pca_dimension'};
    femalecut = 0.025; %test this... potentially add to opts
    numpulsemax = 100;
    pulsetrainmax = 1.5; %in seconds
    if exist(segopts,'file') == 2
        load(segopts); %This is a structure with the following variables saved:
        %analyzerdir, plotanalyzerdir, segmenterdir, butterdir (paths),
        %fs, diffThreshold, template_pca_dimension (FlySongSegmenter options),
        %isshort, filtcut (filtering and clustering options)
        wmoptions = load(segopts,relvars{:});
    else
        %Modify the following to the location of your versions of these programs.
        %Alternatively, save these locations and load as segopts.
        analyzerdir = '../FlySongClusterSegment/';
        plotanalyzerdir = '../fly_song_analyzer_032412/';
        segmenterdir = '../FlySongSegmenter/';
        chronuxdir = '../FlySongSegmenter/chronux/';
        butterdir = pwd;
        fs = 6000; %read from file?
        diffThreshold = 20;
        template_pca_dimension = 10;
        wmoptions = struct('fs',6000,'diffThreshold',20,'template_pca_dimension',10);
        filtcut=200;
        isshort='n';
        domalefemale='FALSE';
    end

    addpath(segmenterdir,plotanalyzerdir,butterdir,chronuxdir);
    currentFolder = pwd;

    %Estimate runtime:
    tic;
    if exist('song_range','var')==0
        song_range = [];
        outname = strcat(wav_file,'_data');
    else
        outname = strcat(wav_file,num2str(song_range(1)),'-',num2str(song_range(2)),'_data');
    end
    [~,wavbase,ext] = fileparts(wav_file);
    splittempname = strsplit(prevtempfile,'/');
    newtempoutname = splittempname{length(splittempname)};
    %Make maxIPI a part of opts file?
    maxIPI = 0.2; %maximum IPI before a new bout is formed (in s)

    %First, check whether data already exists:
    %If d exists but dfilt does not, just filter d.
    %If data does not exist, grab the wav file.
    %If the wav file does not exist, error out.
    if exist(strcat(outname,'.mat'),'file') == 2
        d = load(strcat(outname,'.mat'));
        if isfield(d,'dfilt') == 0
            fprintf('Grabbing song from wav file to filter and resave: %s.\n', wav_file);
            if exist(wav_file) == 2
                if ~isempty(song_range)
                   song = audioread(wav_file,song_range);
                else
                    song = audioread(wav_file);
                end
                %Save this file
                d=song;
                %cd(butterdir);
                dfilt = tybutter(d,filtcut,fs,'high');
                save(strcat(outname,'.mat'),'d','dfilt');
            else
                error('Wav file does not exist: %s.\n', wav_file);
            end
        else
            dfilt=d.dfilt;
        end
    else
        %Generate a data file from the .wav file
        fprintf('Grabbing song from wav file %s.\n', wav_file);
        if ~isempty(song_range)
            song = audioread(wav_file,song_range);
        else
            song = audioread(wav_file);
        end
        %Save this file
        d=song;
        %cd(butterdir);
        dfilt = tybutter(d,filtcut,fs,'high');
        save(strcat(outname,'.mat'),'d','dfilt');
    end

    %Load in previously computed templates.
    fprintf('Loading previous templates: %s.\n', prevtempfile);
    load(prevtempfile);
    if length(whichsignal) > length(newtemplates)
        fprintf('Keeping all signals: %s.\n', num2str(length(newtemplates)));
        try
            whichsignal = whichsignal{1:length(newtemplates)};
        catch MEtemp
            disp(whichsignal)
            disp(length(newtemplates))
            rethrow(MEtemp)
        end
    end

    %Assign data to templates if not already done.
    %dataoutname = strcat(outname,newtempoutname,'signal',s %dataoutname = strcat(outname,newtempoutname,'signal',sprintf('%d',whichsignal), ...
    dataoutname = strcat(outname,'signal',sprintf('%d',whichsignal), ...
        'maxIPI',num2str(maxIPI),'assigned.mat');
    if exist('dataoutname','file') ~= 2
        fprintf('Assigning data to templates from %s.\n', prevtempfile);
        try
            [groupings,peakIdxGroup,likes,allPeakIdx,allNormalizedPeaks,...
            coeffs,projStds] = assignDataToTemplates(dfilt,newtemplates,wmoptions);
        catch MEadtt
            display(path)
            rethrow(MEadtt)
        end
        %Save these variables... including which templates were called signals.
        save(dataoutname,'groupings','peakIdxGroup','likes','allPeakIdx', ...
            'allNormalizedPeaks','coeffs','projStds','whichsignal');
    else
        load(dataoutname)
    end

    %Plot all templates and just signal templates.
    if strcmp(doplots,'TRUE')
        makePeakPlot(dfilt, peakIdxGroup, [1:length(newtemplates)]);
        %savefig(strcat(outname,newtempoutname,'dt',num2str(diffThreshold),'AllColored.fig'));
        savefig(strcat(outname,'dT',num2str(diffThreshold),'AllColored.fig')),
        makePeakPlot(dfilt, peakIdxGroup, whichsignal);
        %savefig(strcat(outname,newtempoutname,'dt',num2str(diffThreshold),'SignalColored.fig'));
        savefig(strcat(outname,'dT',num2str(diffThreshold),'SignalColored.fig'));
    end
    %Compute and plot IPI.

    %Get peakIdx for all signal peaks.
    signalPeakIdx = {};
    for i = 1:length(whichsignal)
        if isa(signalPeakIdx,'cell')
            signalPeakIdx = cell2mat(signalPeakIdx);
        end
        signalPeakIdx = horzcat(signalPeakIdx,peakIdxGroup{whichsignal(i)});
    end
    signalPeakIdx = sort(signalPeakIdx);

    %Remove noise peaks if requested.
    if strcmp(remnoise,'TRUE')
        %Determine filename for noise file.
        try
            noisefile = findNoiseFile(wavbase,whichsignal);
        catch ME
            error('remnoise improperly set: %s\n',remnoise)
        end
        if length(noisefile) > 0
            %Load noise file.
            noise = load(noisefile);
            %Remove peaks in signalPeakIdx that are also in the noise file.
            innoise = intersect(signalPeakIdx, noise.signalPeakIdx);
            signalPeakIdx = setdiff(signalPeakIdx, noise.signalPeakIdx);
            %Change outname to indicate that noise peaks have been removed.
            outname = strcat(outname,'remnoise');
            %Print number of peaks removed.
            fprintf('%d noise peaks removed from %s, leaving %d signal peaks.\n',length(innoise),wavbase,length(signalPeakIdx))
        end
    end

    %Get IPI.
    wall = diff(signalPeakIdx)./wmoptions.fs;
    w = wall(wall <= maxIPI);
    fprintf('Number of IPI measurements less than %s s %s\n', maxIPI, length(w));
    ts = signalPeakIdx./wmoptions.fs;

    %%% New code here:
    %Filter to include only pulses in trains of at least 5 pulses:
    %New: also split into male and female based on mean IPI.
    isConnected = wall <= maxIPI;
    CC = bwconncomp(isConnected);
    tokeep = [];
    tokeepmale = [];
    tokeepfemale = [];
    %Track pulses per burst and pulse train length.
    numPulses = zeros(CC.NumObjects,1);
    numPulses5pm = [];
    numpulsesfemale = [];
    numpulsesmale = [];
    %trainLengths = zeros(CC.NumObjects,1);
    trainLengths = [];
    trainlengthsfemale = [];
    trainlengthsmale = [];

    if exist('minpulse','var')==0
        minpulse = 5;
    else
        outname = strcat(outname,'mp',num2str(minpulse));
    end

    for i=1:CC.NumObjects
        numPulses(i) = length(CC.PixelIdxList{i});
        %trainLengths(i) = ts(CC.PixelIdxList{i}(end)+1) - ts(CC.PixelIdxList{i}(1));
        if numPulses(i) > (minpulse - 1)
            trainLengths = [trainLengths ts(CC.PixelIdxList{i}(end)+1) - ts(CC.PixelIdxList{i}(1))];
            pulsestoadd = [signalPeakIdx(CC.PixelIdxList{i}) signalPeakIdx(CC.PixelIdxList{i}(end)+1)];
            tokeep = [tokeep pulsestoadd];
            numPulses5pm = [numPulses5pm numPulses(i)];
            if strcmp(domalefemale,'TRUE')
                medianipi = median(diff(pulsestoadd)./wmoptions.fs);
                if medianipi > femalecut
                    tokeepfemale = [tokeepfemale pulsestoadd];
                    numpulsesfemale = [numpulsesfemale numPulses(i)];
                    trainlengthsfemale = [trainlengthsfemale trainLengths(end)];
                else
                    tokeepmale = [tokeepmale pulsestoadd];
                    numpulsesmale = [numpulsesmale numPulses(i)];
                    trainlengthsmale = [trainlengthsmale trainLengths(end)];
                end
            end
        end
    end
    ipdone = 0;
    if strcmp(ipiptl, 'IPI') == 1 || strcmp(ipiptl, 'both') == 1
        %wout = strcat(outname,newtempoutname,'dt',num2str(diffThreshold), ...
        wout = strcat(outname,'dT',num2str(diffThreshold), ...
            'signal',sprintf('%d',whichsignal),'maxIPI',num2str(maxIPI),'IPIdist');
        %Save IPI distribution.
        %Also save to text file for R manipulation.
        %save(strcat(wout,'.mat'),'w','wall');
        %save(strcat(wout,'.txt'),'w','-ascii');
        dlmwrite(strcat(wout,'.txt'),w,'delimiter','\n');
        %New function for sorting and saving pulse trains
        %No longer saves 'w' in output file, just 'w5' (excluding pulse trains shorter than 5)
        [tokeep, w5] = sortAndSavePulseTrains(tokeep, wmoptions.fs, ...
            maxIPI, 'all', wout, minpulse);
        if strcmp(domalefemale,'TRUE')
            [tokeepmale, w5male] = sortAndSavePulseTrains(tokeepmale, wmoptions.fs, ...
                maxIPI, 'male', wout, minpulse);
            [tokeepfemale, w5female] = sortAndSavePulseTrains(tokeepfemale, wmoptions.fs, ...
                maxIPI, 'female', wout, minpulse);
        end
        if strcmp(doplots, 'TRUE')
            %New code for plotting histograms
            plotParameterHist(w, 100, 'IPI', wavbase, 'Inter-pulse interval (IPI), in ms', ...
                strcat(outname,'FiltdT',num2str(diffThreshold), ...
                'SignalTemplatesIPIHist.jpg'));

            %also plot just 5-pulse IPIs
            plotParameterHist(w5, 100, '5-pulse minimum IPI', wavbase, ...
                'Inter-pulse interval (IPI), in ms', strcat(outname, ...
                'FiltdT',num2str(diffThreshold), ...
                'SignalTemplatesIPIHist5pm.jpg'));

            if strcmp(domalefemale,'TRUE')
                %Plot female and male IPIs separately.
                plotParameterHist(w5female, 100, '5-pulse minimum IPI female', wavbase, ...
                    'Inter-pulse interval (IPI), in ms', strcat(outname, ...
                    'FiltdT',num2str(diffThreshold), ...
                    'SignalTemplatesFemaleIPIHist5pm.jpg'));
                plotParameterHist(w5male, 100, '5-pulse minimum IPI male', wavbase, ...
                    'Inter-pulse interval (IPI), in ms', strcat(outname, ...
                    'FiltdT',num2str(diffThreshold), ...
                    'SignalTemplatesMaleIPIHist5pm.jpg'));
            end
        end
        ipdone = 1;
    end
    if strcmp(ipiptl,'PTL') == 1 || strcmp(ipiptl,'both') == 1
        %ipiptl now only influences what to save.
        %from IPI: wout = strcat(outname,newtempoutname,'dt',num2str(diffThreshold), ...
          %  'signal',sprintf('%d',whichsignal),'maxIPI',num2str(maxIPI),'IPIdist');
        %ptlout = strcat(outname,newtempoutname,'dT',num2str(diffThreshold), ...
        ptlout = strcat(outname,'dT',num2str(diffThreshold), ...
            'signal', sprintf('%d',whichsignal),'maxIPI',num2str(maxIPI));
        %save(strcat(ptlout,'allPTL.txt'),'trainLengths','-ascii');
        dlmwrite(strcat(ptlout,'allPTL.txt'),trainLengths,'delimiter','\n');
        %save(strcat(ptlout,'allPPB.txt'),'numPulses','-ascii');
        dlmwrite(strcat(ptlout,'allPPB.txt'),numPulses,'delimiter','\n');
        dlmwrite(strcat(ptlout,'allPPB5pm.txt'),numPulses5pm,'delimiter','\n');
        if strcmp(domalefemale,'TRUE')
            save(strcat(ptlout,'allPTL_PPBdata.mat'),'CC','numPulses','numPulses5pm','trainLengths', ...
                'numpulsesfemale', 'numpulsesmale', 'trainlengthsfemale', 'trainlengthsmale');
            %Also save all 5-pulse min values to text files
            dlmwrite(strcat(ptlout,'femalePTL.txt'),trainlengthsfemale,'delimiter','\n');
            dlmwrite(strcat(ptlout,'malePTL.txt'),trainlengthsmale,'delimiter','\n');
            dlmwrite(strcat(ptlout,'femalePPB.txt'),numpulsesfemale,'delimiter','\n');
            dlmwrite(strcat(ptlout,'malePPB.txt'),numpulsesmale,'delimiter','\n');
        else
            save(strcat(ptlout,'allPTL_PPBdata.mat'),'CC','numPulses','numPulses5pm','trainLengths');
        end
        if strcmp(doplots,'TRUE')
            %intnumPulses = numPulses(numPulses < numpulsemax);
            intnumPulses = numPulses5pm(numPulses5pm < numpulsemax);
            plotParameterHist(intnumPulses/1000, 50, 'PPB', wavbase, 'Pulses per burst (PPB)', ...
                strcat(outname,'FiltdT',num2str(diffThreshold), ...
                'SignalTemplatesPPBHist5pm.jpg'));

            inttrainLengths = trainLengths(trainLengths < pulsetrainmax);
            plotParameterHist(inttrainLengths, 50, 'PTL', wavbase, ...
                'Pulse Train Length (PTL), in ms', strcat(outname, ...
                'FiltdT',num2str(diffThreshold),'SignalTemplatesPTLHist5pm.jpg'));

            if strcmp(domalefemale,'TRUE')
                %Plot male and female separately.
                intnumpulsesfemale = numpulsesfemale(numpulsesfemale < numpulsemax);
                plotParameterHist(intnumpulsesfemale/1000, 50, 'PPB', wavbase, 'Pulses per burst (PPB) female', ...
                    strcat(outname,'FiltdT',num2str(diffThreshold), ...
                    'SignalTemplatesFemalePPBHist5pm.jpg'));

                inttrainlengthsfemale = trainlengthsfemale(trainlengthsfemale < pulsetrainmax);
                plotParameterHist(inttrainlengthsfemale, 50, 'PTL', wavbase, ...
                    'Pulse Train Length (PTL) female, in ms', strcat(outname, ...
                    'FiltdT',num2str(diffThreshold),'SignalTemplatesFemalePTLHist5pm.jpg'));

                intnumpulsesmale = numpulsesmale(numpulsesmale < numpulsemax);
                plotParameterHist(intnumpulsesmale/1000, 50, 'PPB', wavbase, 'Pulses per burst (PPB) male', ...
                    strcat(outname,'FiltdT',num2str(diffThreshold), ...
                    'SignalTemplatesMalePPBHist5pm.jpg'));

                inttrainlengthsmale = trainlengthsmale(trainlengthsmale < pulsetrainmax);
                plotParameterHist(inttrainlengthsmale, 50, 'PTL', wavbase, ...
                    'Pulse Train Length (PTL) male, in ms', strcat(outname, ...
                    'FiltdT',num2str(diffThreshold),'SignalTemplatesMalePTLHist5pm.jpg'));
            end
        end
        ipdone = 1;
    end
    if ipdone ~= 1
        fprintf('ipiptl variable must be IPI, PTL, or both: %s.\n', ipiptl);
    end
    %whos
    %cd(segmenterdir);
    %cd(currentFolder);
    toc;
end

function [pulses, ipis] = sortAndSavePulseTrains(unsortedpulses, sampfreq, ...
        ipicut, pulselabel, pulseoutfile, minpulse);
    pulses = sort(unsortedpulses);
    w5all = diff(pulses)./sampfreq;
    w5 = w5all(w5all <= ipicut);
    fprintf('Number of  %s pulse trains with at least %d pulses: %s\n', ...
        pulselabel, minpulse, num2str(length(w5)))
    save(strcat(pulseoutfile,pulselabel,'.mat'),'w5','w5all');
    dlmwrite(strcat(pulseoutfile,pulselabel,'min5pulse.txt'),w5,'delimiter','\n');
    ipis = w5;
end

function plotParameterHist(values, hbreaks, parname, wavname, xaxlabel, plotoutname)
    %disp(plotoutname)
    if hbreaks > length(values)/10
        hbreaks = max(round(length(values)/10),10);
    end
    [Y,X] = hist(values, hbreaks); %switch to 'histogram' in more recent releases of MATLAB
    Y = Y  ./ (sum(Y)*(X(2)-X(1)));
    plot(X*1000,Y)
    %try
    %    title(strcat(parname,' histogram for ',wavname))
    %catch MEtitle
    %    disp(class(wavname))
    %    disp(strcat(parname,' histogram for ',wavname))
    title(strcat(parname,' histogram'))
    %end
    xlabel([xaxlabel ' (N=' num2str(length(values)) ')'])
    ylabel ('Count')
    try
        saveas(gcf, plotoutname);
    catch MEplotname
        disp(plotoutname)
        rethrow(MEplotname)
    end
end

function noisefile = findNoiseFile(filename,wsignal)
    %find the noise templates filename based on the outname
    %e.g.: 2015-07-09_Channel_32_Noise.wav_datasignal1456789101112signalpeaks.mat
    %modify for use with a/b names
    noisedir = '/global/scratch/wynn/ClusteringOutputPerSpecies/ForNoise';
    noisefile = [];
    sf = strsplit(filename,'_');
    ab = [strfind(sf{3},'a') strfind(sf{3},'b')];
    if length(ab) == 0
        ss = strcat(noisedir, '/', sf{1}, '*', sprintf('%d',wsignal), '*');
        nfs = dir(ss);
        if length(nfs) == 1
            noisefile = strcat(noisedir,'/',nfs(1).name);
        else
            fprintf('Noise file for %s (%s) not found.\n',filename,ss);
        end
    else
        fprintf('%s needs a corresponding a/b noise file.',filename);
    end
end

%Currently doing mixture modeling in R, but the following
%could serve as a base for doing this analysis in MATLAB.
%Model IPI distribution as a mixture of Gaussians.
%Now doing mixture model in R, so don't need to spend time on it here.
%ipigm2 = fitgmdist(w.',2)
%ipigm3 = fitgmdist(w.',3)
%ipigm4 = fitgmdist(w.',4)

%Find some way to save means and proportions to text?
%gmout = strcat(outname,newtempoutname,'signal',sprintf('%d',whichsignal),'maxIPI',num2str(maxIPI),'GMModel');
%save(strcat(gmout,'.mat'),'ipigm2','ipigm3','ipigm4');
%save(strcat(gmout,'.txt'),'wav_file','wcount','ipigm2','-ascii');

redpajama_set_name: RedPajamaGithub


text:
class AvetmissData::Stores::V6::Achievement < AvetmissData::Stores::V6::Base
  nat_file('NAT00100', {
    client_identifier: 0...10,
    prior_education_achievement_identifier: 10...13,
    extras: 13..-1
  })

  alias_method :identifier, :client_identifier
end


text:
class Bazel < Formula
  desc "Google's own build tool"
  homepage "http://bazel.io/"
  url "https://github.com/bazelbuild/bazel/archive/0.1.4.tar.gz"
  sha256 "7668dea0e3455cb10d0ac7b59e81de533edabea875fde77deb8d7a7bf24feaf4"

  bottle do
    cellar :any_skip_relocation
    sha256 "3f2a2c5d3041fc41d39305073cb63a5744ec73d1e86cf71c6ff7bc73ec0f09ce" => :el_capitan
    sha256 "dcb6dbcb618acb7953ae217f121b54eda5887d70f1e0896fad489dc4a9dfbfc7" => :yosemite
  end

  depends_on :java => "1.8+"
  depends_on :macos => :yosemite

  def install
    inreplace "src/main/cpp/blaze_startup_options.cc",
      "/etc/bazel.bazelrc",
      "#{etc}/bazel/bazel.bazelrc"

    ENV["EMBED_LABEL"] = "#{version}-homebrew"

    system "./compile.sh"
    system "./output/bazel", "build", "scripts:bash_completion"

    (prefix/"base_workspace").mkdir
    cp_r Dir["base_workspace/*"], (prefix/"base_workspace"), :dereference_root => true
    bin.install "output/bazel" => "bazel"
    (prefix/"etc/bazel.bazelrc").write <<-EOS.undent
      build --package_path=%workspace%:#{prefix}/base_workspace
      query --package_path=%workspace%:#{prefix}/base_workspace
      fetch --package_path=%workspace%:#{prefix}/base_workspace
    EOS
    (etc/"bazel").install prefix/"etc/bazel.bazelrc"

    bash_completion.install "bazel-bin/scripts/bazel-complete.bash"
    zsh_completion.install "scripts/zsh_completion/_bazel"
  end

  test do
    touch testpath/"WORKSPACE"

    (testpath/"ProjectRunner.java").write <<-EOS.undent
      public class ProjectRunner {
        public static void main(String args[]) {
          System.out.println("Hi!");
        }
      }
    EOS

    (testpath/"BUILD").write <<-EOS.undent
      java_binary(
        name = "bazel-test",
        srcs = glob(["*.java"]),
        main_class = "ProjectRunner",
      )
    EOS

    system "#{bin}/bazel", "build", "//:bazel-test"
    system "bazel-bin/bazel-test"
  end
end


text:
(function(exports){

    var mustache = require('mustache');

    // simple tokener (doesn't understand {{= =}})
    var tokenize = exports.tokenize = function(text) {
        return text
            .replace(/{{{/g, '{{&')
            .replace(/}}}/g, '}}')
            .match(/{{[#^](.+?)}}[\w\W]+?{{\/\1}}|{{.+?}}|[\w\W]+?(?={{|$)/g);
    };

    var normalize = exports.normalize = function(xml) {
        return xml
            // whitespace at beginning / end
            .replace(/^\s*/g, '')
            .replace(/\s*$/g, '')
            // whitespace between elements
            .replace(/>\s*</g, '><')
            // whitespace between elements and mustaches
            .replace(/>\s*{{/g, '>{{')
            .replace(/}}\s*</g, '}}<')
            // whitespace between mustaches
            .replace(/}}\s*{{/g, '}}{{')
            // empty elements
            .replace(/<(\w+)([^\/>]*)\/>/g, '<$1$2></$1>');
    };

    var isTemplate = function(token) {
        return /^[^{]/.test(token);
    };

    var isPlain = function(token) {
        return /^{{\s*[a-zA-z0-9-_\.]+\s*}}$/.test(token);
    };

    var isRich = function(token) {
        return /^{{\s*&\s*[a-zA-z0-9-_\.]+\s*}}$/.test(token);
    };

    var isSection = function(token) {
        return /^{{\s*#/.test(token);
    };

    var isPartial = function(token) {
        return /^{{\s*>/.test(token);
    };

    var getname = function(mustache) {
        return mustache.match(/^{{\s*\W?\s*(.+?)\s*}}/)[1];
    };

    // stolen from http://stackoverflow.com/questions/11299284/javascript-deep-copying-object
    // and modified to support arrays
    var mixin = function(destination, source) {
        if (!destination) destination = {};
        for (var property in source) {
            if (Object.prototype.toString.call(source[property]) == '[object Array]') {
                destination[property] = destination[property] || [];
                mixin(destination[property], source[property]);
            } else if (typeof source[property] === "object" && source[property] !== null ) {
                destination[property] = destination[property] || {};
                mixin(destination[property], source[property]);
            } else {
                destination[property] = source[property];
            }
        }
        return destination;
    };

    var extractTemplate = function(tmpl, view) {
        if (view.indexOf(tmpl) == 0) return {};

        return;
    };

    var extractPlain = function(tmpl, hint, view) {
        var len, val;
        var result = {};
        if (!hint) {
            len = view.length;
        } else {
            len = view.indexOf(hint);
        }

        if (len == -1) return;

        val = view.slice(0, len);
        result[getname(tmpl)] = val;
        return result;
    };

    var extractRich = extractPlain;

    var extractSection = function(tmpl, hint, view, partials, result) {
        var model;
        var name = getname(tmpl);
        tmpl = tmpl.replace(/^{{#\w+}}|{{\/\w+}}$/g, '');
        if (tmpl.length == 0) return result;

        if (tokenize(tmpl).length == 1 && (isRich(tmpl) || isPlain(tmpl))) {
            model = [extract(tmpl, hint, view, partials)];
        } else {
            model = extractSectionHelper(tmpl, view, partials, []);
        }

        if (model.length == 1 && model[0][name]) return model[0];
        // TODO: clean this up, much nicer to return nothing...
        if (model.length == 0) model = '';

        var result = {};
        result[name] = model;
        return result;
    };

    var extractSectionHelper = function(tmpl, view, partials, result) {
        var model = getModel(tmpl, view, partials);
        var matchedView = mustache.render(tmpl, model, partials);
        if (view.indexOf(matchedView) != 0) return result;

        result.push(model);
        view = view.slice(matchedView.length);
        return extractSectionHelper(tmpl, view, partials, result);
    }

    var extractPartial = function(tmpl, view, partials) {
        var name = getname(tmpl);
        var model = getModel(partials[name], view, partials);
        return model;
    };

    var extract = function(tmpl, hint, view, partials) {
        if (isTemplate(tmpl)) {
            return extractTemplate(tmpl, view);
        } else if (isPlain(tmpl)) {
            return extractPlain(tmpl, hint, view);
        } else if (isRich(tmpl)) {
            return extractRich(tmpl, hint, view);
        } else if (isSection(tmpl)) {
            return extractSection(tmpl, hint, view, partials);
        } else if (isPartial(tmpl)) {
            return extractPartial(tmpl, view, partials);
        }
        throw 'extract error, unknown mustache';
    };

    var getModel = exports.getModel = function(tmpl, view, partials, hint) {
        var model, matchedView;
        var tokens = tokenize(tmpl);
        if (!tokens || tokens.length == 0) return;

        return tokens
            .reduce(function(result, token, index) {
                if (!result) return;

                hint = tokens[index+1];
                model = extract(token, hint, view, partials);
                matchedView = mustache.render(token, model, partials);
                if (view.indexOf(matchedView) != 0) return;

// if (model.type && model.name) console.log('matched', model.type, 'with name', model.name);
// if (model.itemType && model.itemName) console.log('matched bundleRight', model.itemType, 'with name', model.itemName);
// if (model.id && model.name && model.role) console.log('matched group', model.name);
                view = view.slice(matchedView.length);
                return mixin(result, model);
            }, {});
    };

    var verify = exports.verify = function(tmpl, view, partials) {
        var model = getModel(tmpl, view, partials);
        var newView = mustache.render(tmpl, model, partials);

        return view == newView;
    };

    if (!verify('', '')) throw 'error testing empty template';
    if (!verify('foo', 'foo')) throw 'error testing template text';
    if (verify('foo', 'bar')) throw 'error testing template text not matching';

    if (!verify('{{foo}}', 'foo')) throw 'error testing plaintext (no hint)';
    if (!verify('{{foo}}bar', 'foobar')) throw 'error testing plaintext';
    if (!verify('foo{{bar}}baz', 'foobarbaz')) throw 'error testing plaintext (prefixed)';

    if (!verify('foo{{{bar}}}baz', 'foobarbaz')) throw 'error testing richtext';
    if (!verify('foo{{&bar}}baz', 'foobarbaz')) throw 'error testing richtext (alt syntax)';

    if (!verify('foo{{#bar}}baz{{/bar}}qux', 'foobazqux')) throw 'error testing section template';
    if (!verify('foo{{#bar}}{{bar}}{{/bar}}baz', 'foobarbaz')) throw 'error testing if section plaintext';
    if (!verify('foo{{#bar}}{{bar}}{{/bar}}baz', 'foobaz')) throw 'error testing if section plaintext (empty)';
    if (!verify('foo{{#bar}}{{{bar}}}{{/bar}}baz', 'foobarbaz')) throw 'error testing if section richtext';
    if (!verify('foo{{#bar}}{{baz}}bar{{/bar}}qux', 'foo1bar2bar3barqux')) throw 'error testing multiple section';
    if (!verify('foo{{#bar}}baz{{#baz}}ooga{{blargh}}ooga{{/baz}}baz{{/bar}}qux', 'foobazoogablarghoogabazqux')) throw 'error testing nested section';

    if (!verify('foo{{>bar}}qux', 'foobarbazqux', {bar: '{{bar}}baz'})) throw 'error testing partial'
    if (!verify('foo{{#bar}}{{>baz}}{{/bar}}qux', 'foobar1bazbar2bazbar3bazqux', {baz: '{{bar}}baz'})) throw 'error testing section partial'
    if (!verify('foo{{#bar}}{{>baz}}{{/bar}}qux', 'foofooquxfooquxqux', {baz: 'foo{{#bar}}{{>baz}}{{/bar}}qux'})) throw 'error testing nested partial';

}(typeof exports === 'undefined' ? this.razor = {} : exports));


text:
import { Schema, arrayOf } from 'normalizr';

// Define a schema for our entities.
// More info about normalizr Schemas you can find here: https://github.com/paularmstrong/normalizr
const match = new Schema('matches');

export default {
  MATCH: match,
  MATCHES: arrayOf(match)
};


text:
package memnets.fx

import memnets.model._
import scalafx.scene.image.ImageView
import scalafx.scene.shape.Rectangle
import scalafx.scene._

class FrameFX(loc: Loc = Loc(), zoom: Double = 1.0, w: Double = 600, h: Double = 600) extends Logging {
  import scalafx.scene.layout._
  private val ui: JVBox = "frame.fxml".loadFXML
  val fx = new VBox(ui)
  fx.managed = false
  fx.pickOnBounds = true
  val stackPane = new StackPane(ui.findById("stack"))
  val anchorPane = new AnchorPane(ui.findById("main"))
  protected val glass = new Rectangle(ui.findById("glass"))
  val base = new Rectangle(ui.findById("#base"))

  // NOTE : had issue with glass cache not resizing if SPEED set as quality
  glass.cacheHint = CacheHint.Quality
  base.cacheHint = CacheHint.Quality
  glass.cache = true
  base.cache = true

  def hideGlass(): Unit = {
    glass.getStyleClass.removeAll("glass")
    glass.fill = null
    glass.visible = false
  }

  /** must call AFTER hideGlass to work right */
  def showBorder(): Unit = {
    glass.strokeWidth = 2.5
    if (!glass.visible.value) glass.visible = true
  }
  def hideBase(): Unit = base.visibleProperty.setValue(false)

  import scalafx.Includes._
  def root = anchorPane.getChildren.headOption
  def root_=(node: Node): Unit = {
    fx.userData = node.userData
    anchorPane.getChildren.add(node)
    node.managed = true
    for {
      fbs <- node.as[FrameFXStyle]
      style <- fbs.paneStyle
    } anchorPane.style = style

    AnchorPane.clearConstraints(node)
    AnchorPane.setAnchors(node, 0, 0, 0, 0)
    node match {
      case im: ImageView =>
        im.fitWidth <== anchorPane.width
        im.fitHeight <== anchorPane.height
      case default =>
    }
  }
  def initFrame() = {
    // DO NOT CALL fx.layout()
    fx.scaleX = zoom
    fx.scaleY = zoom
    val off = glass.strokeWidth.value
    fx.relocate(
      loc.x - fx.scaleX.value * (off + anchorPane.prefWidth.value / 2.0),
      loc.y - fx.scaleY.value * (off + anchorPane.prefHeight.value / 2.0))
  }
  def resetFrame(): Unit = {
    anchorPane.prefWidthProperty.setValue(w)
    glass.widthProperty.setValue(w)
    base.widthProperty.setValue(w)

    anchorPane.prefHeightProperty.setValue(h)
    glass.heightProperty.setValue(h)
  }
  resetFrame()
}


text:
ActiveRecord::Schema.define(version: 20150502011227) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

  create_table "locations", force: true do |t|
    t.integer  "user_id"
    t.decimal  "longitude",  precision: 10, scale: 6
    t.decimal  "latitude",   precision: 10, scale: 6
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "transactions", force: true do |t|
    t.integer  "user_id"
    t.string   "transaction_type"
    t.decimal  "amount"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end


text:
/*
 * Android SDK for Piwik
 *
 * @link https://github.com/piwik/piwik-android-sdk
 * @license https://github.com/piwik/piwik-sdk-android/blob/master/LICENSE BSD-3 Clause
 */

package org.piwik.sdk;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import java.net.MalformedURLException;
import java.util.HashMap;

public class Piwik {
    public static final String LOGGER_PREFIX = "PIWIK:";

    private final static Object lock = new Object();

    private static HashMap<Application, Piwik> applications = new HashMap<Application, Piwik>();

    private Application application;

    private boolean optOut = false;

    private boolean dryRun = false;

    protected final static Thread.UncaughtExceptionHandler defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    private Piwik(Application application) {
        this.application = application;
    }

    public static Piwik getInstance(Application application) {
        synchronized (lock) {
            Piwik piwik = applications.get(application);
            if (piwik != null) {
                return piwik;
            }
            piwik = new Piwik(application);
            applications.put(application, piwik);
            return piwik;
        }
    }

    /**
     * @param trackerUrl (required) Tracking HTTP API endpoint, for example, http://your-piwik-domain.tld/piwik.php
     * @param siteId     (required) id of site
     * @param authToken  (optional) could be null or valid auth token. @deprecated since Piwik 2.8.
     *
     * @return Tracker object
     * @throws MalformedURLException
     */
    public Tracker newTracker(String trackerUrl, int siteId, String authToken) throws MalformedURLException {
        return new Tracker(trackerUrl, siteId, authToken, this);
    }

    public Tracker newTracker(String trackerUrl, int siteId) throws MalformedURLException {
        return new Tracker(trackerUrl, siteId, null, this);
    }

    public void setAppOptOut(boolean optOut) {
        this.optOut = optOut;
    }

    public boolean isOptOut() {
        return optOut;
    }

    public boolean isDryRun() {
        return dryRun;
    }

    /**
     * The dryRun flag set to true prevents any data from being sent to Piwik.
     * The dryRun flag should be set whenever you are testing or debugging an implementation and do not want
     * test data to appear in your Piwik reports. To set the dry run flag, use:
     * <p/>
     * Piwik.getInstance(this).setDryRun(true);
     */
    public void setDryRun(boolean dryRun) {
        this.dryRun = dryRun;
    }

    public String getApplicationDomain() {
        return application.getPackageName();
    }

    public Context getApplicationContext() {
        return application.getApplicationContext();
    }

    public SharedPreferences getSharedPreferences(String s, int modePrivate) {
        return application.getSharedPreferences(s, modePrivate);
    }
}


text:
package org.togglz.core.repository.jdbc;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.togglz.core.Feature;
import org.togglz.core.repository.FeatureState;
import org.togglz.core.repository.util.DefaultMapSerializer;
import org.togglz.core.util.DbUtils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.atomic.AtomicInteger;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

abstract class JDBCStateRepositoryTest {

    private static final AtomicInteger COUNTER = new AtomicInteger();

    DataSource dataSource;
    String tableName;
    JDBCStateRepository repository;

    @BeforeEach
    void before() throws SQLException {
        dataSource = createDataSource();
        tableName = "togglz" + COUNTER.getAndIncrement();
        repository = createRepository(dataSource);
    }

    abstract DataSource createDataSource() throws SQLException;

    JDBCStateRepository.Builder defaultBuilder(DataSource dataSource) {
        return JDBCStateRepository.newBuilder(dataSource)
                .tableName(tableName)
                .createTable(true)
                .serializer(DefaultMapSerializer.multiline());
    }

    JDBCStateRepository createRepository(DataSource dataSource) {
        return defaultBuilder(dataSource).build();
    }

    @Test
    void testShouldSaveStateWithoutStrategyOrParameters() {

        /*
         * WHEN a feature without strategy is persisted
         */
        FeatureState state = new FeatureState(TestFeature.F1).disable();
        repository.setFeatureState(state);

        /*
         * THEN there should be a corresponding entry in the database
         */
        assertEquals(1L, query(dataSource, substitute("SELECT COUNT(*) FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals(0, query(dataSource,  substitute("SELECT FEATURE_ENABLED FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertNull(query(dataSource, substitute("SELECT STRATEGY_ID FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertNull(query(dataSource, substitute("SELECT STRATEGY_PARAMS FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
    }

    @Test
    void testShouldSaveStateStrategyAndParameters() {

        /*
         * WHEN a feature without strategy is persisted
         */
        FeatureState state = new FeatureState(TestFeature.F1)
            .enable()
            .setStrategyId("someId")
            .setParameter("param", "foo");
        repository.setFeatureState(state);

        /*
         * THEN there should be a corresponding entry in the database
         */
        assertEquals(1L, query(dataSource, substitute("SELECT COUNT(*) FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals(1, query(dataSource, substitute("SELECT FEATURE_ENABLED FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("someId", query(dataSource, substitute("SELECT STRATEGY_ID FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("param=foo", query(dataSource, substitute("SELECT STRATEGY_PARAMS FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
    }

    @Test
    void testShouldReadStateWithoutStrategyAndParameters() {
        /*
         * GIVEN a database row containing a simple feature state
         */
        update(dataSource, substitute("INSERT INTO %TABLE% VALUES ('F1', 0, NULL, NULL)"));

        /*
         * WHEN the repository reads the state
         */
        FeatureState state = repository.getFeatureState(TestFeature.F1);

        /*
         * THEN the properties should be set like expected
         */
        assertNotNull(state);
        assertEquals(TestFeature.F1, state.getFeature());
        assertFalse(state.isEnabled());
        assertNull(state.getStrategyId());
        assertEquals(0, state.getParameterNames().size());
    }

    @Test
    void testShouldReadStateWithStrategyAndParameters() {
        /*
         * GIVEN a database row containing a simple feature state
         */
        update(dataSource, substitute("INSERT INTO %TABLE% VALUES ('F1', 1, 'myStrategy', 'param23=foobar')"));

        /*
         * WHEN the repository reads the state
         */
        FeatureState state = repository.getFeatureState(TestFeature.F1);

        /*
         * THEN the properties should be set like expected
         */
        assertNotNull(state);
        assertEquals(TestFeature.F1, state.getFeature());
        assertTrue(state.isEnabled());
        assertEquals("myStrategy", state.getStrategyId());
        assertEquals(1, state.getParameterNames().size());
        assertEquals("foobar", state.getParameter("param23"));
    }

    @Test
    void testShouldUpdateExistingDatabaseEntry() {
        /*
         * GIVEN a database row containing a simple feature state
         */
        update(dataSource, substitute("INSERT INTO %TABLE% VALUES ('F1', 1, 'myStrategy', 'param23=foobar')"));

        /*
         * AND the database entries are like expected
         */
        assertEquals(1L, query(dataSource, substitute("SELECT COUNT(*) FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals(1, query(dataSource, substitute("SELECT FEATURE_ENABLED FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("myStrategy", query(dataSource, substitute("SELECT STRATEGY_ID FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("param23=foobar", query(dataSource, substitute("SELECT STRATEGY_PARAMS FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));

        /*
         * WHEN the repository writes new state
         */
        FeatureState state = new FeatureState(TestFeature.F1)
            .disable()
            .setStrategyId("someId")
            .setParameter("param", "foo");
        repository.setFeatureState(state);

        /*
         * THEN the properties should be set like expected
         */
        assertEquals(1L, query(dataSource, substitute("SELECT COUNT(*) FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals(0, query(dataSource, substitute("SELECT FEATURE_ENABLED FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("someId", query(dataSource, substitute("SELECT STRATEGY_ID FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));
        assertEquals("param=foo", query(dataSource, substitute("SELECT STRATEGY_PARAMS FROM %TABLE% WHERE FEATURE_NAME = 'F1'")));

	}

	@Test
	void testShouldPropagateTheExceptionWhenReadFails() throws SQLException {

		/*
		 * GIVEN a database row containing a simple feature state
		 */
		update(dataSource, substitute("INSERT INTO %TABLE% VALUES ('F1', 0, NULL, NULL)"));

		/*
		 * AND the datasource throws an exception when we try to get a
		 * connection
		 */
		DataSource spyedDataSource = Mockito.spy(dataSource);
        repository = createRepository(spyedDataSource);
		Mockito.when(spyedDataSource.getConnection()).thenThrow(new SQLException("Failed to get a connection"));

		/*
		 * WHEN the repository reads the state
		 */
        assertThrows(IllegalStateException.class, () -> repository.getFeatureState(TestFeature.F1));

		/*
		 * THEN an IllegalStateException is thrown
		 */
	}

	@Test
	void testShouldPropagateTheExceptionWhenWriteFails() throws SQLException {

		/*
		 * GIVEN a feature state to persist
		 */
		FeatureState state = new FeatureState(TestFeature.F1).enable();

		/*
		 * AND the datasource throws an exception when we try to get a
		 * connection
		 */
		DataSource spyedDataSource = Mockito.spy(dataSource);
		repository = createRepository(spyedDataSource);
		Mockito.when(spyedDataSource.getConnection()).thenThrow(new SQLException("Failed to get a connection"));

		/*
		 * WHEN the feature state is persisted
		 */
        assertThrows(IllegalStateException.class, () -> repository.setFeatureState(state));
		/*
		 * THEN an IllegalStateException is thrown
		 */
    }

    Object query(DataSource dataSource, String sql) {
        try {
            Connection connection = dataSource.getConnection();
            try {
                Statement statement = connection.createStatement();
                try {
                    ResultSet resultSet = statement.executeQuery(sql);
                    try {
                        if (resultSet.next()) {
                            return resultSet.getObject(1);
                        }
                        return null;
                    } finally {
                        DbUtils.closeQuietly(resultSet);
                    }
                } finally {
                    DbUtils.closeQuietly(statement);
                }
            } finally {
                DbUtils.closeQuietly(connection);
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }

    }

    void update(DataSource dataSource, String sql) {
        try {
            Connection connection = dataSource.getConnection();
            try {

                Statement statement = connection.createStatement();
                try {
                    statement.executeUpdate(sql);
                } finally {
                    DbUtils.closeQuietly(statement);
                }
            } finally {
                DbUtils.closeQuietly(connection);
            }
        } catch (SQLException e) {
            throw new IllegalStateException(e);
        }
    }

    String substitute(String s) {
        return s.replace("%TABLE%", tableName);
    }

    private enum TestFeature implements Feature {
        F1
    }
}


text:
namespace YAF.Dialogs
{

    public partial class UserMedalEdit
    {

        /// <summary>
        /// UserMedalEditTitle-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.Label UserMedalEditTitle;

        /// <summary>
        /// HelpLabel23-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel HelpLabel23;

        /// <summary>
        /// UserName-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox UserName;

        /// <summary>
        /// UserSelectHolder-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.PlaceHolder UserSelectHolder;

        /// <summary>
        /// SelectedUserID-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.HiddenField SelectedUserID;

        /// <summary>
        /// HelpLabel19-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel HelpLabel19;

        /// <summary>
        /// UserMessage-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox UserMessage;

        /// <summary>
        /// HelpLabel20-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel HelpLabel20;

        /// <summary>
        /// UserSortOrder-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.TextBox UserSortOrder;

        /// <summary>
        /// HelpLabel22-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.HelpLabel HelpLabel22;

        /// <summary>
        /// UserHide-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::System.Web.UI.WebControls.CheckBox UserHide;

        /// <summary>
        /// AddUserSave-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.ThemeButton AddUserSave;

        /// <summary>
        /// Cancel-Steuerelement.
        /// </summary>
        /// <remarks>
        /// Automatisch generiertes Feld.
        /// Zum Ändern Felddeklaration aus der Designerdatei in eine Code-Behind-Datei verschieben.
        /// </remarks>
        protected global::YAF.Web.Controls.ThemeButton Cancel;
    }
}


text:
const fs = require('fs');
const path = require('path');
const ZipPlugin = require('zip-webpack-plugin');

module.exports = function (env) {
    const lambdaFunctionDir = path.join(__dirname, 'src', 'lambdas');
    const functionsToBuild = env && env.fxn ? env.fxn.split(",") : fs.readdirSync(lambdaFunctionDir).filter(item => fs.lstatSync(path.join(lambdaFunctionDir, item)).isDirectory() && !item.match(/^\./));
    console.log(`Building ${functionsToBuild.join(", ")}`);

    return functionsToBuild
        .map(fxn => ({
            mode: 'production',
            context: path.resolve(__dirname),
            entry: path.join(lambdaFunctionDir, fxn, 'index.js'),
            output: {
                path: path.join(__dirname, 'dist', fxn),
                filename: 'index.js',
                libraryTarget: 'commonjs2'
            },
            module: {
                rules: [
                    {
                        test: /\.js$/,
                        use: [
                            {
                                loader: 'babel-loader',
                                options: {
                                    presets: [['@babel/env', {targets: {node: '10.16'}}]],
                                    plugins: [],
                                    compact: false,
                                    babelrc: false,
                                    cacheDirectory: true
                                }
                            }
                        ]
                    },
                    {
                        test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$|\.wav$|\.mp3$/,
                        use: [
                            'file-loader'
                        ]
                    }
                ]
            },
            optimization: {
                minimize: false,
                namedModules: true
            },
            plugins: [
                new ZipPlugin({
                    path: path.join(__dirname, 'dist', fxn),
                    pathPrefix: '',
                    filename: `${fxn}.zip`
                })
            ],
            target: 'node',
            externals: {
                // These modules are already installed on the Lambda instance.
                'aws-sdk': 'aws-sdk',
                'awslambda': 'awslambda',
                'dynamodb-doc': 'dynamodb-doc',
                'imagemagick': 'imagemagick'
            },
            node: {
                // Allow these globals.
                __filename: false,
                __dirname: false
            },
            stats: 'errors-only',
            bail: true
        }));
};


text:
<?xml version="1.0" encoding="UTF-8"?>
<tileset name="desert_city_x4" tilewidth="32" tileheight="128">
 <image source="../graphics/tiles/desert_city_x4.png" width="256" height="128"/>
</tileset>


text:
SDLPerformInteractionResponse Class Reference

Section Contents

choiceID

manualTextEntry

triggerSource

Overview

PerformInteraction Response is sent, when SDLPerformInteraction has been called

@since SDL 1.0

      choiceID

ID of the choice that was selected in response to PerformInteraction. Only is valid if general result is <q>success:true</q>.

Optional, Integer, 0 - 2,000,000,000

Objective-C

@property (readwrite, strong, nonatomic, nullable) NSNumber<SDLInt> *choiceID;

Swift

var choiceID: (NSNumber & SDLInt)? { get set }

      manualTextEntry

Manually entered text selection, e.g. through keyboard. Can be returned in lieu of choiceID, depending on the trigger source.

Optional, Max length 500 chars

Objective-C

@property (readwrite, strong, nonatomic, nullable) NSString *manualTextEntry;

Swift

var manualTextEntry: String? { get set }

      triggerSource

A SDLTriggerSource object which will be shown in the HMI. Only is valid if resultCode is SUCCESS.

Objective-C

@property (readwrite, strong, nonatomic, nullable)
    SDLTriggerSource triggerSource;

Swift

var triggerSource: SDLTriggerSource? { get set }


text:
<?php

namespace FacebookAds\Object;

use FacebookAds\ApiRequest;
use FacebookAds\Cursor;
use FacebookAds\Http\RequestInterface;
use FacebookAds\TypeChecker;
use FacebookAds\Object\Fields\TargetingGeoLocationZipFields;

/**
 * This class is auto-genereated.
 *
 * For any issues or feature requests related to this class, please let us know
 * on github and we'll fix in our codegen framework. We'll not be able to accept
 * pull request for this class.
 *
 */

class TargetingGeoLocationZip extends AbstractObject {

  /**
   * @return TargetingGeoLocationZipFields
   */
  public static function getFieldsEnum() {
    return TargetingGeoLocationZipFields::getInstance();
  }

  protected static function getReferencedEnums() {
    $ref_enums = array();
    return $ref_enums;
  }

}


text:
.site-info{
  height: 100vh;
  background-image: url("../imgs/bridge.jpg");
  background-size: cover;
  background-repeat: no-repeat;
}
.wrapper{
  position: relative;
}
header{
  height:75px;
  text-align: center;
  line-height: 75px;
  font-size: 2em;
}
.top{
  height: 50%;
  position: relative;
  text-align: center;
}
.bottom{
  height: 50%;
  position: relative;
  text-align: center;
}
#map{
  height: 100vh;
  width: 100%;
}


text:
DEFINE_int32(master_registration_rpc_timeout_ms, 1500,
             "Timeout for retrieving master registration over RPC.");
TAG_FLAG(master_registration_rpc_timeout_ms, experimental);

DEFINE_int64(tsk_rotation_seconds, 60 * 60 * 24 * 1,
             "Number of seconds between consecutive activations of newly "
             "generated TSKs (Token Signing Keys).");
TAG_FLAG(tsk_rotation_seconds, advanced);
TAG_FLAG(tsk_rotation_seconds, experimental);

DEFINE_int64(authn_token_validity_seconds, 60 * 60 * 24 * 7,
             "Period of time for which an issued authentication token is valid. "
             "Clients will automatically attempt to reacquire a token after the "
             "validity period expires.");
TAG_FLAG(authn_token_validity_seconds, experimental);

DEFINE_int64(authz_token_validity_seconds, 60 * 5,
             "Period of time for which an issued authorization token is valid. "
             "Clients will automatically attempt to reacquire a token after the "
             "validity period expires.");
TAG_FLAG(authz_token_validity_seconds, experimental);

DEFINE_string(location_mapping_cmd, "",
              "A Unix command which takes a single argument, the IP address or "
              "hostname of a tablet server or client, and returns the location "
              "string for the tablet server. A location string begins with a / "
              "and consists of /-separated tokens each of which contains only "
              "characters from the set [a-zA-Z0-9_-.]. If the cluster is not "
              "using location awareness features this flag should not be set.");

using kudu::consensus::RaftPeerPB;
using kudu::fs::ErrorHandlerType;
using kudu::rpc::ServiceIf;
using kudu::security::TokenSigner;
using kudu::tserver::ConsensusServiceImpl;
using kudu::tserver::TabletCopyServiceImpl;
using std::min;
using std::shared_ptr;
using std::string;
using std::unique_ptr;
using std::vector;
using strings::Substitute;

namespace kudu {
namespace master {

Master::Master(const MasterOptions& opts)
  : KuduServer("Master", opts, "kudu.master"),
    state_(kStopped),
    catalog_manager_(new CatalogManager(this)),
    path_handlers_(new MasterPathHandlers(this)),
    opts_(opts),
    registration_initialized_(false) {
  const auto& location_cmd = FLAGS_location_mapping_cmd;
  if (!location_cmd.empty()) {
    location_cache_.reset(new LocationCache(location_cmd, metric_entity_.get()));
  }
  ts_manager_.reset(new TSManager(location_cache_.get(), metric_entity_));
}

Master::~Master() {
  ShutdownImpl();
}

Status Master::Init() {
  CHECK_EQ(kStopped, state_);

  cfile::BlockCache::GetSingleton()->StartInstrumentation(metric_entity());

  RETURN_NOT_OK(ThreadPoolBuilder("init").set_max_threads(1).Build(&init_pool_));

  RETURN_NOT_OK(KuduServer::Init());

  if (web_server_) {
    RETURN_NOT_OK(path_handlers_->Register(web_server_.get()));
  }

  maintenance_manager_.reset(new MaintenanceManager(
      MaintenanceManager::kDefaultOptions, fs_manager_->uuid()));

  // The certificate authority object is initialized upon loading
  // CA private key and certificate from the system table when the server
  // becomes a leader.
  cert_authority_.reset(new MasterCertAuthority(fs_manager_->uuid()));

  // The TokenSigner loads its keys during catalog manager initialization.
  token_signer_.reset(new TokenSigner(
      FLAGS_authn_token_validity_seconds,
      FLAGS_authz_token_validity_seconds,
      FLAGS_tsk_rotation_seconds,
      messenger_->shared_token_verifier()));
  state_ = kInitialized;
  return Status::OK();
}

Status Master::Start() {
  RETURN_NOT_OK(StartAsync());
  RETURN_NOT_OK(WaitForCatalogManagerInit());
  google::FlushLogFiles(google::INFO); // Flush the startup messages.
  return Status::OK();
}

Status Master::StartAsync() {
  CHECK_EQ(kInitialized, state_);
  fs_manager_->SetErrorNotificationCb(ErrorHandlerType::DISK_ERROR,
                                      &CrashMasterOnDiskError);
  fs_manager_->SetErrorNotificationCb(ErrorHandlerType::CFILE_CORRUPTION,
                                      &CrashMasterOnCFileCorruption);

  RETURN_NOT_OK(maintenance_manager_->Start());

  unique_ptr<ServiceIf> impl(new MasterServiceImpl(this));
  unique_ptr<ServiceIf> consensus_service(
      new ConsensusServiceImpl(this, catalog_manager_.get()));
  unique_ptr<ServiceIf> tablet_copy_service(
      new TabletCopyServiceImpl(this, catalog_manager_.get()));

  RETURN_NOT_OK(RegisterService(std::move(impl)));
  RETURN_NOT_OK(RegisterService(std::move(consensus_service)));
  RETURN_NOT_OK(RegisterService(std::move(tablet_copy_service)));
  RETURN_NOT_OK(KuduServer::Start());

  // Now that we've bound, construct our ServerRegistrationPB.
  RETURN_NOT_OK(InitMasterRegistration());

  // Start initializing the catalog manager.
  RETURN_NOT_OK(init_pool_->Submit([this]() { this->InitCatalogManagerTask(); }));
  state_ = kRunning;

  return Status::OK();
}

void Master::InitCatalogManagerTask() {
  Status s = InitCatalogManager();
  if (!s.ok()) {
    LOG(ERROR) << "Unable to init master catalog manager: " << s.ToString();
  }
  init_status_.Set(s);
}

Status Master::InitCatalogManager() {
  if (catalog_manager_->IsInitialized()) {
    return Status::IllegalState("Catalog manager is already initialized");
  }
  RETURN_NOT_OK_PREPEND(catalog_manager_->Init(is_first_run_),
                        "Unable to initialize catalog manager");
  return Status::OK();
}

Status Master::WaitForCatalogManagerInit() const {
  CHECK_EQ(state_, kRunning);

  return init_status_.Get();
}

Status Master::WaitUntilCatalogManagerIsLeaderAndReadyForTests(const MonoDelta& timeout) {
  Status s;
  MonoTime start = MonoTime::Now();
  int backoff_ms = 1;
  const int kMaxBackoffMs = 256;
  do {
    {
      CatalogManager::ScopedLeaderSharedLock l(catalog_manager_.get());
      if (l.first_failed_status().ok()) {
        return Status::OK();
      }
    }
    SleepFor(MonoDelta::FromMilliseconds(backoff_ms));
    backoff_ms = min(backoff_ms << 1, kMaxBackoffMs);
  } while (MonoTime::Now() < (start + timeout));
  return Status::TimedOut("Maximum time exceeded waiting for master leadership",
                          s.ToString());
}

Status Master::GetMasterRegistration(ServerRegistrationPB* reg) const {
  if (!registration_initialized_.load(std::memory_order_acquire)) {
    return Status::ServiceUnavailable("Master startup not complete");
  }
  reg->CopyFrom(registration_);
  return Status::OK();
}

Status Master::InitMasterRegistration() {
  CHECK(!registration_initialized_.load());

  ServerRegistrationPB reg;
  vector<Sockaddr> rpc_addrs;
  RETURN_NOT_OK_PREPEND(rpc_server()->GetAdvertisedAddresses(&rpc_addrs),
                        "Couldn't get RPC addresses");
  RETURN_NOT_OK(AddHostPortPBs(rpc_addrs, reg.mutable_rpc_addresses()));

  if (web_server()) {
    vector<Sockaddr> http_addrs;
    RETURN_NOT_OK(web_server()->GetAdvertisedAddresses(&http_addrs));
    RETURN_NOT_OK(AddHostPortPBs(http_addrs, reg.mutable_http_addresses()));
    reg.set_https_enabled(web_server()->IsSecure());
  }
  reg.set_software_version(VersionInfo::GetVersionInfo());
  reg.set_start_time(start_time_);

  registration_.Swap(&reg);
  registration_initialized_.store(true);

  return Status::OK();
}

void Master::ShutdownImpl() {
  if (kInitialized == state_ || kRunning == state_) {
    const string name = rpc_server_->ToString();
    LOG(INFO) << "Master@" << name << " shutting down...";

    // 1. Stop accepting new RPCs.
    UnregisterAllServices();

    // 2. Shut down the master's subsystems.
    init_pool_->Shutdown();
    maintenance_manager_->Shutdown();
    catalog_manager_->Shutdown();
    fs_manager_->UnsetErrorNotificationCb(ErrorHandlerType::DISK_ERROR);
    fs_manager_->UnsetErrorNotificationCb(ErrorHandlerType::CFILE_CORRUPTION);

    // 3. Shut down generic subsystems.
    KuduServer::Shutdown();
    LOG(INFO) << "Master@" << name << " shutdown complete.";
  }
  state_ = kStopped;
}

void Master::CrashMasterOnDiskError(const string& uuid) {
  LOG(FATAL) << Substitute("Disk error detected on data directory $0", uuid);
}

void Master::CrashMasterOnCFileCorruption(const string& tablet_id) {
  LOG(FATAL) << Substitute("CFile corruption detected on system catalog $0", tablet_id);
}

namespace {

// TODO(Alex Feinberg) this method should be moved to a separate class (along with
// ListMasters), so that it can also be used in TS and client when
// bootstrapping.
Status GetMasterEntryForHost(const shared_ptr<rpc::Messenger>& messenger,
                             const HostPort& hostport,
                             ServerEntryPB* e) {
  Sockaddr sockaddr;
  RETURN_NOT_OK(SockaddrFromHostPort(hostport, &sockaddr));
  MasterServiceProxy proxy(messenger, sockaddr, hostport.host());
  GetMasterRegistrationRequestPB req;
  GetMasterRegistrationResponsePB resp;
  rpc::RpcController controller;
  controller.set_timeout(MonoDelta::FromMilliseconds(FLAGS_master_registration_rpc_timeout_ms));
  RETURN_NOT_OK(proxy.GetMasterRegistration(req, &resp, &controller));
  e->mutable_instance_id()->CopyFrom(resp.instance_id());
  if (resp.has_error()) {
    return StatusFromPB(resp.error().status());
  }
  e->mutable_registration()->CopyFrom(resp.registration());
  e->set_role(resp.role());
  return Status::OK();
}

} // anonymous namespace

Status Master::ListMasters(vector<ServerEntryPB>* masters) const {
  if (!opts_.IsDistributed()) {
    ServerEntryPB local_entry;
    local_entry.mutable_instance_id()->CopyFrom(catalog_manager_->NodeInstance());
    RETURN_NOT_OK(GetMasterRegistration(local_entry.mutable_registration()));
    local_entry.set_role(RaftPeerPB::LEADER);
    masters->emplace_back(std::move(local_entry));
    return Status::OK();
  }

  auto consensus = catalog_manager_->master_consensus();
  if (!consensus) {
    return Status::IllegalState("consensus not running");
  }
  const auto config = consensus->CommittedConfig();

  masters->clear();
  for (const auto& peer : config.peers()) {
    HostPort hp = HostPortFromPB(peer.last_known_addr());
    ServerEntryPB peer_entry;
    Status s = GetMasterEntryForHost(messenger_, hp, &peer_entry);
    if (!s.ok()) {
      s = s.CloneAndPrepend(
          Substitute("Unable to get registration information for peer $0 ($1)",
                     peer.permanent_uuid(),
                     hp.ToString()));
      LOG(WARNING) << s.ToString();
      StatusToPB(s, peer_entry.mutable_error());
    } else if (peer_entry.instance_id().permanent_uuid() != peer.permanent_uuid()) {
      StatusToPB(Status::IllegalState(
          Substitute("mismatched UUIDs: expected UUID $0 from master at $1, but got UUID $2",
                     peer.permanent_uuid(),
                     hp.ToString(),
                     peer_entry.instance_id().permanent_uuid())),
                 peer_entry.mutable_error());
    }
    masters->emplace_back(std::move(peer_entry));
  }
  return Status::OK();
}

Status Master::GetMasterHostPorts(vector<HostPort>* hostports) const {
  auto consensus = catalog_manager_->master_consensus();
  if (!consensus) {
    return Status::IllegalState("consensus not running");
  }

  hostports->clear();
  consensus::RaftConfigPB config = consensus->CommittedConfig();
  for (const auto& peer : *config.mutable_peers()) {
    if (peer.member_type() == consensus::RaftPeerPB::VOTER) {
      // In non-distributed master configurations, we don't store our own
      // last known address in the Raft config. So, we'll fill it in from
      // the server Registration instead.
      if (!peer.has_last_known_addr()) {
        DCHECK_EQ(config.peers_size(), 1);
        DCHECK(registration_initialized_.load());
        DCHECK_GT(registration_.rpc_addresses_size(), 0);
        hostports->emplace_back(HostPortFromPB(registration_.rpc_addresses(0)));
      } else {
        hostports->emplace_back(HostPortFromPB(peer.last_known_addr()));
      }
    }
  }
  return Status::OK();
}

} // namespace master
} // namespace kudu


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Syst. veg. , Edn 16 4(1): 482 (1827)

#### Original name
null

### Remarks
null


text:
package org.iclub.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.Table;

@Entity
@Table(name = "content")
public class Content {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false)
    private Long id;

    @Column(name = "name", nullable = false, unique = true, length = 50)
    private String name;

    @Lob
    @Column(name = "content_text")
    private String contentText;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContentText() {
        return contentText;
    }

    public void setContentText(String contentText) {
        this.contentText = contentText;
    }

    @Override
    public String toString() {
        return "Content{id=" + id + ", name='" + name + '}';
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="generator" content="Source Themes Academic 4.1.0">
  <meta name="generator" content="Hugo 0.55.0" />

  <meta name="author" content="Shubham Gupta">

  <meta name="description" content="Worked with the leading auto part seller in the US, to improve sales forecast by implementing a sequence analysis approach with time-series data to improve the accuracy of the model.
This study investigates a novel application of sequence analysis to forecast new product demand, which is a modified version of the approach that has been used in the bioinformatics field for protein sequencing. For retailers, the problem of forecasting demand for products which have never existed previously is challenging.">

  <link rel="alternate" hreflang="en-us" href="https://ishub.github.io/project/autoparts/">

  <meta name="theme-color" content="#3f51b5">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha256-eSi1q2PG6J7g7ib17yAaWMcrr5GrtohYChqibrV7PBE=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/academicons/1.8.6/css/academicons.min.css" integrity="sha256-uFVgMKfistnJAfoCUQigIl+JfUaP47GrRKjf6CTPVmw=" crossorigin="anonymous">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.0/css/all.css" integrity="sha384-aOkxzJ5uQz7WBObEZcHvV5JvRW3TUc2rNPA7pe3AwnsUohiw1Vj2Rgx2KSOkF5+h" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.2.5/jquery.fancybox.min.css" integrity="sha256-ygkqlh3CYSUri3LhQxzdcm0n1EQvH2Y+U5S2idbLtxs=" crossorigin="anonymous">

          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css" crossorigin="anonymous" title="hl-light">
          <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/dracula.min.css" crossorigin="anonymous" title="hl-dark" disabled>

  <link rel="stylesheet" href="//fonts.googleapis.com/css?family=Montserrat:400,700|Roboto:400,400italic,700|Roboto+Mono">

  <link rel="stylesheet" href="/styles.css">

    <link rel="stylesheet" href="/css/academic.0382c2e797d86765c6773b01e17588bc.css">

  <link rel="alternate" href="https://ishub.github.io/index.xml" type="application/rss+xml" title="Shubham Gupta">
  <link rel="feed" href="https://ishub.github.io/index.xml" type="application/rss+xml" title="Shubham Gupta">

  <link rel="manifest" href="/site.webmanifest">
  <link rel="icon" type="image/png" href="/img/icon.png">
  <link rel="apple-touch-icon" type="image/png" href="/img/icon-192.png">

  <link rel="canonical" href="https://ishub.github.io/project/autoparts/">

  <meta property="twitter:card" content="summary_large_image">

  <meta property="twitter:site" content="@shubham_gupta_">
  <meta property="twitter:creator" content="@shubham_gupta_">

  <meta property="og:site_name" content="Shubham Gupta">
  <meta property="og:url" content="https://ishub.github.io/project/autoparts/">
  <meta property="og:title" content="Sequence Analysis approach to improve product forecasts | Shubham Gupta">
  <meta property="og:description" content="Worked with the leading auto part seller in the US, to improve sales forecast by implementing a sequence analysis approach with time-series data to improve the accuracy of the model.
This study investigates a novel application of sequence analysis to forecast new product demand, which is a modified version of the approach that has been used in the bioinformatics field for protein sequencing. For retailers, the problem of forecasting demand for products which have never existed previously is challenging."><meta property="og:image" content="https://ishub.github.io/project/autoparts/featured.png">
  <meta property="og:locale" content="en-us">

  <meta property="article:published_time" content="2018-09-27T23:01:41-04:00">

  <meta property="article:modified_time" content="2018-09-27T23:01:41-04:00">

  <!DOCTYPE html>

  <title>Sequence Analysis approach to improve product forecasts | Shubham Gupta</title>

Search

        <input name="q" id="search-query" placeholder="Search..." autocapitalize="off"
        autocomplete="off" autocorrect="off" role="textbox" spellcheck="false" type="search">

      Shubham Gupta

      <button type="button" class="navbar-toggler" data-toggle="collapse"
              data-target="#navbar" aria-controls="navbar" aria-expanded="false" aria-label="Toggle navigation">

      </button>

            Home

            Projects

            Experience

            Cool Stuff

            Contact

Sequence Analysis approach to improve product forecasts

<meta content="2018-09-27 23:01:41 -0400 EDT" itemprop="datePublished">
<meta content="2018-09-27 23:01:41 -0400 EDT" itemprop="dateModified">

    <time>Sep 27, 2018</time>

  PDF

Sequence Analysis approach to improve product forecasts

<meta content="2018-09-27 23:01:41 -0400 EDT" itemprop="datePublished">
<meta content="2018-09-27 23:01:41 -0400 EDT" itemprop="dateModified">

    <time>Sep 27, 2018</time>

  PDF

Worked with the leading auto part seller in the US, to improve sales forecast by implementing a sequence analysis approach with time-series data to improve the accuracy of the model.

This study investigates a novel application of sequence analysis to forecast new product demand, which is a modified version of the approach that has been used in the bioinformatics field for protein sequencing. For retailers, the problem of forecasting demand for products which have never existed previously is challenging. Knowledge of how demand will fluctuate, especially for new product in the portfolio, will enable stores and distribution centers to manage inventory and utilize their shelf space more efficiently. We collaborated with a U.S. national retailer to develop a sequence analysis model to identify the likely sequence of purchasing future spares for various types of products on the basis of similar historical SKU sales data.

  course

  highlights

Shubham Gupta

Your friendly neighbourhood data science enthusiast

    Powered by the
    Academic theme for
    Hugo.

Cite

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

           Copy

           Download


text:
using NUnit.Framework;
using TournamentsMVC.Controllers;
using TestStack.FluentMVCTesting;

namespace TournamentsMVCTests.UnitTests.Controllers.ChatControllerTests
{
    [TestFixture]
    public class Index_Should
    {
        [Test]
        public void ReturnDefaultView()
        {
            // Arrange
            var controller = new ChatController();

            // Act & Assert
            controller.WithCallTo(c => c.Index()).ShouldRenderDefaultView();
        }
    }
}


text:
package scouter.server.db

import scouter.lang.pack.AlertPack
import scouter.io.DataOutputX
import scouter.server.Logger
import scouter.server.db.alert.AlertIndex
import scouter.server.db.alert.AlertWriter
import scouter.server.plugin.PlugInManager
import scouter.util.DateUtil
import scouter.util.FileUtil
import scouter.util.IClose
import scouter.util.RequestQueue
import java.io.File
import scouter.server.util.ThreadScala
import scouter.server.util.OftenAction

object AlertWR {

    val queue = new RequestQueue[AlertPack](DBCtr.MAX_QUE_SIZE)

    val alert = "alert"
    ThreadScala.start("scouter.server.db.AlertWR") {
        var currentDateUnit = 0L
        while (DBCtr.running) {
            val p = queue.get()
            try {
                PlugInManager.alert(p)

                if (currentDateUnit != DateUtil.getDateUnit(p.time)) {
                    currentDateUnit = DateUtil.getDateUnit(p.time)
                    close()
                    open(DateUtil.yyyymmdd(p.time))
                }

                if (index == null) {
                    queue.clear();
                    Logger.println("S120", 10, "can't open db")

                    OftenAction.act("AlertWR", 10) {
                        currentDateUnit = 0L
                    }
                } else {
                    val b = new DataOutputX().writePack(p).toByteArray()
                    val location = writer.write(b)
                    index.add(p.time, location)
                }
            } catch {
                case t: Throwable => t.printStackTrace()
            }
        }
        close()
    }

    def add(p: AlertPack) {
        val ok = queue.put(p)
        if (ok == false) {
            Logger.println("S121", 10, "queue exceeded!!")
        }
    }

    var index: AlertIndex = null
    var writer: AlertWriter = null

    def close() {
        FileUtil.close(index)
        FileUtil.close(writer)
        index = null
        writer = null
    }

    def open(date: String) {
        try {
            val path = getDBPath(date)
            val f = new File(path)
            if (f.exists() == false)
                f.mkdirs()
            val file = path + "/" + alert
            index = AlertIndex.open(file)
            writer = AlertWriter.open(file)
            return
        } catch {
            case e: Throwable => {
                e.printStackTrace()
                close()
            }
        }
    }
    def getDBPath(date: String): String = {
        val sb = new StringBuffer()
        sb.append(DBCtr.getRootPath())
        sb.append("/").append(date).append("/alert")
        return sb.toString()
    }

}


text:
package c

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

// Conf configuration for Oracle
type Conf struct {
	Flagged   []string `yaml:"flaggedPhrases"`
	Year      int      `yaml:"yearsBack"`
	Month     int      `yaml:"monthsBack"`
	Day       int      `yaml:"daysBack"`
	Files     []string `yaml:"filesToWatch"`
	ScanEvery string   `yaml:"scanEvery"`
	OutputDir string   `yaml:"outputDir"`
	Regexs    []string `yaml:"timeRegexPatterns"`
}

// GetConf gets configuration from the yaml file
func GetConf(path string) (c Conf, err error) {
	data, err := ioutil.ReadFile(path)
	if nil != err {
		return c, err
	}
	err = yaml.Unmarshal([]byte(data), &c)
	return c, err
}


text:
package cmd

import (
	"errors"
	"fmt"
	"io"

	"github.com/spf13/cobra"

	kapi "k8s.io/kubernetes/pkg/api"
	"k8s.io/kubernetes/pkg/api/meta"
	kcmd "k8s.io/kubernetes/pkg/kubectl/cmd"
	kcmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
	"k8s.io/kubernetes/pkg/kubectl/resource"
	"k8s.io/kubernetes/pkg/runtime"

	buildapi "github.com/openshift/origin/pkg/build/api"
	"github.com/openshift/origin/pkg/cmd/util/clientcmd"
	deployapi "github.com/openshift/origin/pkg/deploy/api"
)

// LogsRecommendedName is the recommended command name
// TODO: Probably move this pattern upstream?
const LogsRecommendedName = "logs"

const (
	logsLong = `
Print the logs for a resource.

Supported resources are builds, build configs (bc), deployment configs (dc), and pods.
When a pod is specified and has more than one container, the container name should be
specified via -c. When a build config or deployment config is specified, you can view
the logs for a particular version of it via --version.

If your pod is failing to start, you may need to use the --previous option to see the
logs of the last attempt.`

	logsExample = `  # Start streaming the logs of the most recent build of the openldap build config.
  %[1]s -f bc/openldap

  # Start streaming the logs of the latest deployment of the mysql deployment config.
  %[1]s -f dc/mysql

  # Get the logs of the first deployment for the mysql deployment config. Note that logs
  # from older deployments may not exist either because the deployment was successful
  # or due to deployment pruning or manual deletion of the deployment.
  %[1]s --version=1 dc/mysql

  # Return a snapshot of ruby-container logs from pod backend.
  %[1]s backend -c ruby-container

  # Start streaming of ruby-container logs from pod backend.
  %[1]s -f pod/backend -c ruby-container`
)

// OpenShiftLogsOptions holds all the necessary options for running oc logs.
type OpenShiftLogsOptions struct {
	// Options should hold our own *LogOptions objects.
	Options runtime.Object
	// KubeLogOptions contains all the necessary options for
	// running the upstream logs command.
	KubeLogOptions *kcmd.LogsOptions
}

// NewCmdLogs creates a new logs command that supports OpenShift resources.
func NewCmdLogs(name, parent string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	o := OpenShiftLogsOptions{
		KubeLogOptions: &kcmd.LogsOptions{},
	}
	cmd := kcmd.NewCmdLogs(f.Factory, out)
	cmd.Short = "Print the logs for a resource."
	cmd.Long = logsLong
	cmd.Example = fmt.Sprintf(logsExample, parent+" "+name)
	cmd.SuggestFor = []string{"builds", "deployments"}
	cmd.Run = func(cmd *cobra.Command, args []string) {
		kcmdutil.CheckErr(o.Complete(f, out, cmd, args))
		if err := o.Validate(); err != nil {
			kcmdutil.CheckErr(kcmdutil.UsageError(cmd, err.Error()))
		}
		kcmdutil.CheckErr(o.RunLog())
	}
	cmd.Flags().Int64("version", 0, "View the logs of a particular build or deployment by version if greater than zero")

	return cmd
}

// Complete calls the upstream Complete for the logs command and then resolves the
// resource a user requested to view its logs and creates the appropriate logOptions
// object for it.
func (o *OpenShiftLogsOptions) Complete(f *clientcmd.Factory, out io.Writer, cmd *cobra.Command, args []string) error {
	if err := o.KubeLogOptions.Complete(f.Factory, out, cmd, args); err != nil {
		return err
	}
	namespace, _, err := f.DefaultNamespace()
	if err != nil {
		return err
	}

	podLogOptions := o.KubeLogOptions.Options.(*kapi.PodLogOptions)

	mapper, typer := f.Object(false)
	infos, err := resource.NewBuilder(mapper, typer, resource.ClientMapperFunc(f.ClientForMapping), kapi.Codecs.UniversalDecoder()).
		NamespaceParam(namespace).DefaultNamespace().
		ResourceNames("pods", args...).
		SingleResourceType().RequireObject(false).
		Do().Infos()
	if err != nil {
		return err
	}
	if len(infos) != 1 {
		return errors.New("expected a resource")
	}

	version := kcmdutil.GetFlagInt64(cmd, "version")
	_, resource := meta.KindToResource(infos[0].Mapping.GroupVersionKind)

	// TODO: podLogOptions should be included in our own logOptions objects.
	switch resource.GroupResource() {
	case buildapi.Resource("build"), buildapi.Resource("buildconfig"):
		bopts := &buildapi.BuildLogOptions{
			Follow:       podLogOptions.Follow,
			Previous:     podLogOptions.Previous,
			SinceSeconds: podLogOptions.SinceSeconds,
			SinceTime:    podLogOptions.SinceTime,
			Timestamps:   podLogOptions.Timestamps,
			TailLines:    podLogOptions.TailLines,
			LimitBytes:   podLogOptions.LimitBytes,
		}
		if version != 0 {
			bopts.Version = &version
		}
		o.Options = bopts
	case deployapi.Resource("deploymentconfig"):
		dopts := &deployapi.DeploymentLogOptions{
			Follow:       podLogOptions.Follow,
			Previous:     podLogOptions.Previous,
			SinceSeconds: podLogOptions.SinceSeconds,
			SinceTime:    podLogOptions.SinceTime,
			Timestamps:   podLogOptions.Timestamps,
			TailLines:    podLogOptions.TailLines,
			LimitBytes:   podLogOptions.LimitBytes,
		}
		if version != 0 {
			dopts.Version = &version
		}
		o.Options = dopts
	default:
		o.Options = nil
	}

	return nil
}

// Validate runs the upstream validation for the logs command and then it
// will validate any OpenShift-specific log options.
func (o OpenShiftLogsOptions) Validate() error {
	if err := o.KubeLogOptions.Validate(); err != nil {
		return err
	}
	if o.Options == nil {
		return nil
	}
	switch t := o.Options.(type) {
	case *buildapi.BuildLogOptions:
		if t.Previous && t.Version != nil {
			return errors.New("cannot use both --previous and --version")
		}
	case *deployapi.DeploymentLogOptions:
		if t.Previous && t.Version != nil {
			return errors.New("cannot use both --previous and --version")
		}
	default:
		return errors.New("invalid log options object provided")
	}
	return nil
}

// RunLog will run the upstream logs command and may use an OpenShift
// logOptions object.
func (o OpenShiftLogsOptions) RunLog() error {
	if o.Options != nil {
		// Use our own options object.
		o.KubeLogOptions.Options = o.Options
	}
	_, err := o.KubeLogOptions.RunLogs()
	return err
}


text:
{% extends "base.html" %}

{% block content %}

Autoservicio De Lujo - Administración

{{fecha}}

               Serv. Realizados

                Ir a Servicios

               Prod. Vendidos

                Ir a Productos

               Empleados

                Ir a Empleados

               Clientes

                Ir a Clientes

               Semana

                Ir a Semana

               Facturar

                Ir a Facturar

{% endblock %}


text:
<?php
/**
 * Processes a request to review a product
 */

if( !Auth::isAuthenticated() ) {
    Util::getTemplate( 'login.php' );
    return;
}

//force a search query
if( !isset( $_REQUEST['q'] ) || empty( $_REQUEST['q'] ) ) {
    Util::getTemplate( 'products.search.php' );
    return;
}

//ensure we have a request to create
if( !isset(
    $_REQUEST['rating'],
    $_REQUEST['review']
) ) {
    Util::getTemplate( 'reviews.product.create.php' );
    return;
}

if( isset( $_REQUEST['entry'] ) )
    $entry = ApiLinks::decodeHateoasLink( $_REQUEST['entry'] );
else
    $entry = LSM_API_ENDPOINT . "review/product";

$lsm = new LsmCurl;
$lsm->setEndpoint( $entry );
$lsm->usePut();

//build the request
$ProductReview = new StdClass;
$ProductReview->productID = (int) $_REQUEST['q'];
$ProductReview->rating = (int) $_REQUEST['rating'];
$ProductReview->review = $_REQUEST['review'];
$ProductReview->customerID = Auth::getCustomerId();

$lsm->setParameters( $ProductReview );
$lsm->sendRequest();

$review = $lsm->getResponseContent();
if( !$review || (int) $lsm->getResponseStatus() != 200 ) {
    Util::getTemplate( '500.php' );
    return;
}

Util::getHeader();
if( DEBUG_API_CALLS ) {
    echo "
"; var_dump( $review ); echo"
";
}

?>

Review Created Successfully

        <?php
        $review->productID = $ProductReview->productID;
        echo ApiLinks::linksToHtml( $review );
        ?>

<?php
Util::getFooter();


text:
/*
 *
 *
 */
function enablePublishToggle(url)
{
    var enableTxt = 'enable';
    var disableTxt = 'disable';

    $("td.rt-admin-publish-toggle span").click(function(){
      if($(this).hasClass('loading')) {
        return;
      }

      $(this).removeClass('ui-icon-check');
      $(this).removeClass('ui-icon-close');

      $(this).addClass('loading');

      // ajax call to toggle action
      var commentId = $(this).next('div').html();
      var spanElement = $(this);

      $.ajax({
        url: url,
        data: { id: commentId },
        success: function(data) {
          spanElement.removeClass('loading');
          if(data == 'activated') {
            spanElement.addClass('ui-icon-check');
          } else {
            spanElement.addClass('ui-icon-close');
          }
        }
      });
    });
}

function enableTogglePanels()
{
  $('.rt-admin-toggle-panel h2').click(function(){
    $(this).next('.rt-admin-toggle-panel-content').toggle('blind');
  }).next('.rt-admin-toggle-panel-content').find('.error_list').parents('.rt-admin-toggle-panel-content').toggle();
}

// rt-admin-toggle-panel

/*
 * Enable the link panel.
 */
function enableLinkPanel(inputId, buttonId, updatePanel, updateUrl, targetTextField)
{
  $(inputId).keydown(function(event) {
    if (event.keyCode == '13') {
      triggerLinkPanelLookup(inputId, updatePanel, updateUrl);
      event.preventDefault();
    }
  });
  $(buttonId).click(function() {
    triggerLinkPanelLookup(inputId, updatePanel, updateUrl);
    return false;
  });
}
/*
 * Trigger the search / lookup for the link panel
 */
function triggerLinkPanelLookup(inputId, updatePanel, updateUrl)
{
    $.ajax({
        url: updateUrl,
        dataType: 'json',
        data: {q : $(inputId).attr('value')},
        success: function(data) {
            $(updatePanel).show();
            $(updatePanel).html('');
            $.each(data.items, function(index, value) {
                if(value.placeholder == ''){
                  $('
'+value.title+'
').appendTo(updatePanel);
                }
                else
                {
                  $('
'+value.title+'
').appendTo(updatePanel);
                }
            });
        }
    });
}

/*
 * Run global methods.
 */
$(function() {
  enableTogglePanels();
});


text:
require 'mediacloth/mediawikiwalker'

#A walker to build textual representation of the parse tree.
#
#Use as any other walker and then query for tree:
# parser = MediaWikiParser.new
# parser.lexer = MediaWikiLexer.new
# ast = parser.parse(input)
# walker = DebugWalker.new
# walker.parse(ast)
# puts walker.tree
class DebugWalker < MediaWikiWalker

    #The textual representation of the parse tree.
    attr_reader :tree

    def initialize
        super
        @tree = ""
        @left_space = 0
    end

protected

    def parse_wiki_ast(ast)
        info(ast)
        @left_space += 1
        super(ast) if ast.children
        @left_space -= 1
    end

    def parse_text(ast)
        info(ast, ast.formatting)
        super(ast)
    end

    def parse_list(ast)
        info(ast, ast.class)
        @left_space += 1
        super(ast)
        @left_space -= 1
    end

    def parse_internal_link(ast)
        info(ast)
        @left_space += 1
        ast.children.map do |c|
            parse_wiki_ast(c)
        end
        @left_space -= 1
    end

    def parse_resource_link(ast)
        info(ast)
        @left_space += 1
        ast.children.map do |c|
            parse_wiki_ast(c)
        end
        @left_space -= 1
    end

    def parse_category_link(ast)
        info(ast)
        @left_space += 1
        ast.children.map do |c|
            parse_wiki_ast(c)
        end
        @left_space -= 1
    end

private
    #Pretty-print ast node information
    def info(ast, *args)
        @tree += "#{"    " * @left_space}#{ast.class}[#{ast.index}, #{ast.length}]"
        if args.length > 0
            @tree += ": "
            args.each { |arg| @tree += "#{arg} " }
        end
        @tree += "\n"
    end

end


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

namespace Peace.AOP
{
    public class InvokeContext
    {
        private string _methodName;
        public InvokeContext(string methodName)
        {
            _methodName = methodName;
        }

        public Type RealType { get; set; }
        public string MethodName
        {
            get { return _methodName; }
            set { _methodName = value; }
        }
        public object[] Parameters { get; set; }

        public object ResultValue { get; set; }

        public Exception Exception { get; set; }

        public object Tag { get; set; }
    }
}


text:
namespace content {

RTCVideoDecoderFactory::RTCVideoDecoderFactory(
    media::GpuVideoAcceleratorFactories* gpu_factories)
    : gpu_factories_(gpu_factories) {
  DVLOG(2) << __FUNCTION__;
}

RTCVideoDecoderFactory::~RTCVideoDecoderFactory() {
  DVLOG(2) << __FUNCTION__;
}

webrtc::VideoDecoder* RTCVideoDecoderFactory::CreateVideoDecoder(
    webrtc::VideoCodecType type) {
  DVLOG(2) << __FUNCTION__;
  return RTCVideoDecoder::Create(type, gpu_factories_).release();
}

void RTCVideoDecoderFactory::DestroyVideoDecoder(
    webrtc::VideoDecoder* decoder) {
  DVLOG(2) << __FUNCTION__;
  RTCVideoDecoder::Destroy(decoder, gpu_factories_);
}

}  // namespace content


text:
using Catalog.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;

namespace Catalog.Web.Framework
{
    public class CatalogueExistsConstraint : IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
          if (values[parameterName] == null || !Catalogue.Exists(values[parameterName].ToString()))
            {
                return false;
            }

            return true;
        }
    }
}


text:
import WidgetProperty from 'ember-eureka/widget-property';

export default WidgetProperty.extend({

    editing: false,

    toggleEditionMode: function() {
        this.toggleProperty('field.editing', true);
    },

    actions: {
        edit: function() {
            this.toggleEditionMode();
        },
        addRelation: function() {
            var field = this.get('field');
            var db = field.get('meta.modelMeta.store.db');
            var relationType = field.get('meta.type');
            var relation = db[relationType].createRecord();
            field.set('value', relation);
            this.toggleEditionMode();
        },
        deleteRelation: function() {
            this.set('field.value', null);
        },
        doneRelation: function() {
            var field = this.get('field');
            var relation;

            if (field.get('value.promise') !== undefined) {
                relation = field.get('value.content');  // it's a proxy-promise
            } else {
                relation = field.get('value');
            }

            if (relation.get('_syncNeeded')) {
                var that = this;
                relation.save().then(function(savedRelation) {
                    field.set('value', savedRelation);
                    that.toggleEditionMode();
                });
            } else {
                if (!relation.get('_id')) {
                    field.set('value', null);
                }
                this.toggleEditionMode();
            }
        },
        cancelRelation: function() {
            var field = this.get('field');
            if (field.get('value.promise') !== undefined) {
                this.get('field.value.content').rollback(); // it's a proxy-promise
            } else {
                this.get('field.value').rollback();
            }
            this.toggleEditionMode();
        }
    }

});


text:
using std::string;
using namespace std;
using vec_str    = std::vector<std::string>;

namespace eclipse {
// Constructor & destructor {{{
Node::Node() :
  Machine(context.id),
  logger (context.logger.get()),
  port   (context.settings.get<int>("network.ports.internal"))
{
}

Node::~Node() { }
// }}}
// get_ip {{{
string Node::get_ip() const { return ip_of_this; }
// }}}
}


text:
require File.dirname(__FILE__) + '/../spec_helper'

describe UserParent do
  it { is_expected.to belong_to(:user).inverse_of :user_parent }
  it { is_expected.to belong_to(:parent_user).inverse_of(:parentages).class_name "User" }

  it { is_expected.to validate_presence_of :name }
  it { is_expected.to validate_presence_of :child_name }
  it { is_expected.to validate_presence_of :user }

  describe UserParent, "creation" do
    it "should not trigger the delivery of any emails" do
      deliveries = Devise.mailer.deliveries.size
      # The blueprint makes an active user that was a created a little while ago
      # by default, so we need to make a new user here
      user = User.make
      up = UserParent.make!(
        user: User.new(
          login: user.login,
          email: user.email,
          birthday: 9.years.ago.to_date.to_s,
          password: "foofoo",
          password_confirmation: "foofoo"
        )
      )
      Delayed::Worker.new.work_off
      expect( Devise.mailer.deliveries.size ).to eq deliveries
    end

    it "should not allow an email that belongs to another user that is not the parent user" do
      existing_user = User.make!
      up = UserParent.make( email: existing_user.email )
      expect( up ).not_to be_valid
      expect( up.errors[:email] ).not_to be_blank
    end
    it "should allow an email that belongs to another user that is the parent user" do
      existing_user = User.make!
      up = UserParent.make!( email: existing_user.email, parent_user: existing_user )
      expect( up ).to be_valid
    end
  end

  describe UserParent, "update" do
    it "should allow the donorbox_donor_id to be set even if a non-parent user exists with the same email address" do
      up = UserParent.make!
      u = User.make!( email: up.email )
      up.update( donorbox_donor_id: 1 )
      expect( up ).to be_valid
    end
  end

  describe UserParent, "donorbox_donor_id" do
    it "should get set on create based on the parent_user" do
      up = UserParent.make!( parent_user: User.make!( donorbox_donor_id: 1 ) )
      expect( up.donorbox_donor_id ).not_to be_blank
      expect( up.donorbox_donor_id ).to eq up.parent_user.donorbox_donor_id
    end
    it "should deliver an email when set on update" do
      up = UserParent.make!
      deliveries = ActionMailer::Base.deliveries.size
      up.update( donorbox_donor_id: 1 )
      expect( ActionMailer::Base.deliveries.size ).to eq deliveries + 1
    end
    it "should deliver an email when set on create" do
      deliveries = ActionMailer::Base.deliveries.size
      up = UserParent.make!( donorbox_donor_id: 1 )
      expect( ActionMailer::Base.deliveries.size ).to eq deliveries + 1
    end
  end
end