text:
/**
 *
 */
package br.ufrn.deeplearning.logprocess;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import br.ufrn.deeplearning.util.CSVUtils;

/**
 * STEP 2
 *
 * This class generate the output, or labels ou y_train data set by a heuristic
 *
 * @author jadson
 *
 */
public class GenerateOutDataSet {

	//public final static String DEFAULT_DIRECTORY         = "/Users/jadson/git/deeplearning/data/";
	public final static String DEFAULT_DIRECTORY             = "/home/jadson/git/deeplearning/data/";
	public final static String TRAINING_DATA_DIRECTORY       = DEFAULT_DIRECTORY+"training/";
	public final static String TEST_DATA_DIRECTORY           = DEFAULT_DIRECTORY+"tests/";
	public final static String VALIDATION_DATA_DIRECTORY     = DEFAULT_DIRECTORY+"validation/";

	public static void main(String[] args) throws FileNotFoundException, IOException {
		normalizeData();
	}

	/**
	 * Generate a number form each URL
	 *
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private static void normalizeData() throws IOException, FileNotFoundException {

		List<String> urls = new ArrayList<String>();

		////////////////// for training data  //////////////////
		forfiles:
		for (int i = 1; i < 1000000; i++) {
			String csvFile = TRAINING_DATA_DIRECTORY+"training_"+i+".csv";

			String csvOutFile = TRAINING_DATA_DIRECTORY+"y_training_"+i+".csv";

			File file = new File(csvFile);

			if( file.exists() ) {

				Float[] y = new Float[10]; // value of output of 10 classes

				for (int f = 0; f < y.length; f++) {
					y[f] = 0f;
				}

				FileReader fileReader = new FileReader(file);

				try(   BufferedReader br = new BufferedReader(fileReader)  ) {

				    String line = br.readLine();

				    while (line != null) {
				    	urls.add( line );
				        line = br.readLine();
				    }

				    // END ALL LINES

				    applyHeuristic(urls, y);

				    saveOutPutFile(csvOutFile, y);

				    urls = new ArrayList<String>();

				}

			}else {
				break forfiles;
			}
		}

		forfiles:
			for (int i = 1; i < 1000000; i++) {
				String csvFile = TEST_DATA_DIRECTORY+"test_"+i+".csv";

				String csvOutFile = TEST_DATA_DIRECTORY+"y_test_"+i+".csv";

				File file = new File(csvFile);

				if( file.exists() ) {

					Float[] y = new Float[10]; // value of output of 10 classes

					for (int f = 0; f < y.length; f++) {
						y[f] = 0f;
					}

					FileReader fileReader = new FileReader(file);

					try(   BufferedReader br = new BufferedReader(fileReader)  ) {

					    String line = br.readLine();

					    while (line != null) {
					    	urls.add( line );
					        line = br.readLine();
					    }

					    // END ALL LINES

					    applyHeuristic(urls, y);

					    saveOutPutFile(csvOutFile, y);

					    urls = new ArrayList<String>();

					}

				}else {
					break forfiles;
				}
			}

		forfiles:
			for (int i = 201; i < 1000000; i++) {
				String csvFile = VALIDATION_DATA_DIRECTORY+"test_"+i+".csv";

				String csvOutFile = VALIDATION_DATA_DIRECTORY+"y_test_"+i+".csv";

				File file = new File(csvFile);

				if( file.exists() ) {

					Float[] y = new Float[10]; // value of output of 10 classes

					for (int f = 0; f < y.length; f++) {
						y[f] = 0f;
					}

					FileReader fileReader = new FileReader(file);

					try(   BufferedReader br = new BufferedReader(fileReader)  ) {

					    String line = br.readLine();

					    while (line != null) {
					    	urls.add( line );
					        line = br.readLine();
					    }

					    // END ALL LINES

					    applyHeuristic(urls, y);

					    saveOutPutFile(csvOutFile, y);

					    urls = new ArrayList<String>();

					}

				}else {
					break forfiles;
				}
			}

	}

	/**
	 * Apply Heuristic to try to determinate the output for the 100 urls sequence.
	 *
	 * 1. Create new Event
     * 2. Open Submission Period
	 * 3. Open Subscription Period
	 * 4. Create programming
	 * 5. Create Keynotes
	 * 6. Distribute Submission
	 * 7. Create Event Page
	 * 8. Perform Evaluation
	 * 9. Make Submission
	 * 10. Make Subscription
	 *
	 * @param urls
	 * @param y
	 */
	private static void applyHeuristic(List<String> urls, Float[] y) {
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/formCadastraAlteraEvento.xhtml") ) {
			y[0] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/formCadastraAlteraDadosEventoPrincipal.xhtml") ) {
			y[0] += 0.5f;
		}

		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/listaPeriodosDeSubmissaoEvento.xhtml") ) {
			y[1] += 0.3f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/formPeriodosDeSubmissaoEvento.xhtml") ) {
			y[1] += 0.5f;
		}

		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/formPeriodosDeInscricaoEvento.xhtml") ) {
			y[2] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/eventos/listaPeriodosDeInscricaoEvento.xhtml") ) {
			y[2] += 0.5f;
		}

		//Create programming
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/locais_apresentacao/listaLocaisApresentacaoTrabalho.xhtml") ) {
			y[3] += 0.3f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/locais_apresentacao/formLocaisApresentacaoTrabalho.xhtml") ) {
			y[3] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/pesquisas/buscaPadraoEventos.xhtml") ) {
			y[3] += 0.1f;
		}

		//  Create Keynotes
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/palestrantes/formCadastraPalestranteEvento.xhtml") ) {
			y[4] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/palestrantes/listaPalestrantesGerenciar.xhtml") ) {
			y[4] += 0.3f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/pesquisas/buscaPadraoEventos.xhtml") ) {
			y[4] += 0.1f;
		}

		// Distribute Submission
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/avaliacoes/distribuicao/formDistribuiSubmissoes.xhtml") ) {
			y[5] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/permissoes/cadastraPermissoesPessoaSelecionada.xhtml") ) {
			y[5] += 0.1f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/cadastros/permissoes/listaPermissoesPessoaSelecionada.xhtml") ) {
			y[5] += 0.1f;
		}

		// Create Event Page
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/paginaPublicaEvento/formConfiguracoesPaginaPublica.xhtml") ) {
			y[6] += 0.7f;
		}

		//  Perform Evaluation
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/avaliacoes/parciais/formAvaliacaoParcial.xhtml") ) {
			y[7] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/avaliacoes/parciais/listaMinhasAvaliacoes.xhtml") ) {
			y[7] += 0.3f;
		}

		// Make Submission
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/submissoes/formSubmeterTrabalho.xhtml") ) {
			y[8] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/submissoes/listaMinhasSubmissoes.xhtml") ) {
			y[8] += 0.3f;
		}

		// Make Subscription
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/inscricoes/formInscreveseEvento.xhtml") ) {
			y[9] += 0.5f;
		}
		if( urls.contains("http://www.sigeventos.ufrn.br/eventos/interno/inscricoes/listaMinhasIncricoes.xhtml") ) {
			y[9] += 0.3f;
		}

	}

	private static void saveOutPutFile(String csvOutFile, Float[] y) throws IOException {
		// save the mapping to return //

		FileWriter writer = new FileWriter(csvOutFile);

		StringBuilder builder = new StringBuilder();
		for (int i = 0; i < y.length; i++) {
			if(i < y.length-1)
				builder.append(y[i]+";");
			else
				builder.append(y[i]);
		}
		CSVUtils.writeLine(writer, Arrays.asList( builder.toString() )  );

        writer.flush();
        writer.close();
	}

}


text:
Analyses comparison operators. If '... == ...', '... != ...' (equality) constructions are used,
type-enforcing identical operators are suggested instead ('... === ...', '... !== ...').

Refactoring this might present a significant cost in terms of
additional development and legacy code reverse engineering, so
the cost-benefit should be weighed carefully.

redpajama_set_name: RedPajamaGithub


text:
"use strict";

// Import Gulp module
import gulp from "gulp";
// BrowserSync is used to live-reload your website
import browserSync from "browser-sync";
// Command line (CLI) argument
var argv = require("./yargs.config");
// Configuration file for gulp tasks
const config = require("./gulp.config");
// Lazy load plugins, save on var declaration
var plugins = require("gulp-load-plugins")(config.gulpLoadPlugins.options);

/**
 * Require Gulp Task
 * @param {task} task - What Gulp task do you require
 * @return {function} function - Returns task function from module export
 */
function requireTask(task) {
  // Require Gulp task module, passing in Gulp, config, argv and plugin objects
  return require("./tasks/" + task + ".js")(
    gulp,
    config,
    argv,
    plugins
  );
}

/**
 * Require Gulp Clean Task
 * @param {directory} directory - What directory do you want cleaned
 * @return {function} function  - Returns task function from moudle export
 */
function requireCleanTask(directory) {
  // Require gulp task module
  return require("./tasks/clean")(
    directory,
    plugins
  );
}

/**
 * Require Gulp Inject Task
 * @param {target} target           - What html file do we want to inject reference
 * @param {references} references   - What files to we want to reference
 * @param {destination} destination - Where does the inject file go
 * @return {function} function      - Returns task function from module export
 */
function requireInjectTask(target, references, destination) {
  // Require gulp task module
  return require("./tasks/inject")(
    target,
    references,
    destination,
    gulp,
    config,
    plugins
  );
}

/**
 * Require Gulp Copy Task
 * @param {source} source - Source files to be copied
 * @param {destination} destination - Destination folder to copy files into
 * @return {function} function - Returns task function from module export
 */
function requireCopyTask(source, destination) {
  // Require gulp task module
  return require("./tasks/copy")(
    source,
    destination,
    gulp,
    config,
    plugins
  );
}

/**
 * Scripts Tasks
 * Usage: gulp scripts:clean  - Clean main.js from the JavaScripts build folder
 * Usage: gulp scripts:build  - Build main.js from source into build folder
 * Usage: gulp scripts        - Clean build folder, then build from source into build folder
*/
gulp.task(
  "scripts:clean",
  requireCleanTask(
    config.scripts.dest + "/**/*"
  )
);
gulp.task(
  "scripts:build",
  requireTask(
    "scripts"
  )
);
gulp.task(
  "scripts",
  gulp.series(
    "scripts:clean",
    "scripts:build"
  )
);

/**
 * Styles Tasks
 * Usage: gulp styles:clean - Clean main.css from styles build folder
 * Usage: gulp styles:build - Build main.css from source into build folder
 * Usage: gulp styles       - Clean build folder, then build from source into build folder
*/
gulp.task(
  "styles:clean",
  requireCleanTask(
    config.styles.dest + "/**/*"
  )
);
gulp.task(
  "styles:build",
  requireTask(
    "styles"
  )
);
gulp.task(
  "styles",
  gulp.series(
    "styles:clean",
    "styles:build"
  )
);

/**
 * Styles Tasks
 * Usage: gulp styles:clean - Clean main.css from styles build folder
 * Usage: gulp styles:build - Build main.css from source into build folder
 * Usage: gulp styles       - Clean build folder, then build from source into build folder
*/
gulp.task(
  "fonts:clean",
  requireCleanTask(
    config.fonts.dest + "/**/*.{eot,svg,ttf,woff,woff2,otf}"
  )
);
gulp.task(
  "fonts:build",
  requireTask(
    "fonts"
  )
);
gulp.task(
  "fonts",
  gulp.series(
    "fonts:clean",
    "fonts:build"
  )
);

/**
 * Jekyll Tasks
 * Usage: gulp jekyll:clean - Clean generated pages from build folder
 * Usage: gulp jekyll:build - Build generated pages
 * Usage: gulp jekyll       - Clean build folder, then build generated pages from source
*/
gulp.task(
  "jekyll:clean",
  requireCleanTask(
    config.jekyll.dest + "/**/*"
  )
);
gulp.task(
  "jekyll:build",
  requireTask(
    "jekyll"
  )
);
gulp.task(
  "jekyll",
  gulp.series(
    "jekyll:clean",
    "jekyll:build"
  )
);

/**
 * HTML Tasks
 * Usage: gulp html:clean - Clean zipped pages from build folder
 * Usage: gulp html:build - Build minified and zipped pages
 * Usage: gulp html       - Clean build folder, then minify and zip pages from source
*/
gulp.task(
  "html:cleanGZips",
  requireCleanTask(
    config.jekyll.dest + "/**/*.gz"
  )
);
gulp.task(
  "html:build",
  requireTask(
    "html"
  )
);
gulp.task(
  "html",
  gulp.series(
    "html:cleanGZips",
    "html:build"
  )
);

/**
 * Images Tasks
 * Usage: gulp images:clean - Clean images from build folder
 * Usage: gulp images:build - Copy and minify images to build folder
 * Usage: gulp images       - Clean build folder, then minify and copy images to build folder
*/
gulp.task(
  "images:clean",
  requireCleanTask(
    config.images.dest + "/**/*.{png,gif,jpg}"
  )
);
gulp.task(
  "images:build",
  requireTask(
    "images"
  )
);
gulp.task(
  "images",
  gulp.series(
    "images:clean",
    "images:build"
  )
);

/**
 * Download Tasks
 * Usage: gulp downloads:clean - Clean downlaods from build folder
 * Usage: gulp downloads:build - Copy downloads to build folder
 * Usage: gulp downloads       - Clean build folder, then copy downloads to build folder
*/
gulp.task(
  "downloads:clean",
  requireCleanTask(
    config.downloads.dest + "/**/*"
  )
);
gulp.task(
  "downloads:build",
  requireTask(
    "downloads"
  )
);
gulp.task(
  "downloads",
  gulp.series(
    "downloads:clean",
    "downloads:build"
  )
);

/**
 * Inject Tasks
 * Usage: gulp inject:scripts - Inject scripts into scripts.html
 * Usage: gulp inject:styles  - Inject styles into styles.html
 * Usage: gulp inject         - Inject scripts and styles into Jekyll include files
*/
gulp.task(
  "inject:scripts",
  requireInjectTask(
    config.inject.scripts.target,
    config.inject.scripts.references,
    config.inject.scripts.destination
  )
);
gulp.task(
  "inject:styles",
  requireInjectTask(
    config.inject.styles.target,
    config.inject.styles.references,
    config.inject.styles.destination
  )
);
gulp.task(
  "inject",
  gulp.parallel(
    "inject:scripts",
    "inject:styles"
  )
);

/**
 * GitHub Pages
 * usage: gulp gh-pages - Push files to GitHub registry
 */
gulp.task(
  "gh-pages",
  requireTask("gh-pages")
);

/**
 * Assets Tasks
 * Usage: gulp copyAssetsToBuild:clean        - Delete all files in build (assets) destination folder
 * Usage: gulp copyAssetsToBuild:scripts      - Copy JavaScript files into build destination folder
 * Usage: gulp copyAssetsToBuild:styles       - Copy CSS files into build destination folder
 * Usage: gulp copyAssetsToBuild:image        - Copy png, gif & jpg files into build destination folder
 * Usage: gulp copyAssetsToBuild:fonts        - Copy eot, svg, ttf, woff, woff2 & otf files into build destination folder
 * Usage: gulp copyAssetsToBuild:downloads    - Copy files in download into build destination folder
 * Usage: gulp copyAssetsToBuild:scripts      - Copy JavaScript files into build destination folder
*/
gulp.task(
  "copyAssetsToBuild:clean",
  requireCleanTask(
    config.jekyll.assets)
);
gulp.task(
  "copyAssetsToBuild:scripts",
  requireCopyTask(
    config.jekyll.tmp + "/scripts/**/*.{js,gz}",
    config.jekyll.assets + "/scripts")
);
gulp.task(
  "copyAssetsToBuild:styles",
  requireCopyTask(
    config.jekyll.tmp + "/styles/**/*.{css,gz}",
    config.jekyll.assets + "/styles")
);
gulp.task(
  "copyAssetsToBuild:images",
  requireCopyTask(
    config.jekyll.tmp + "/images/**/*.{png,gif,jpg}",
    config.jekyll.assets + "/images")
);
gulp.task(
  "copyAssetsToBuild:fonts",
  requireCopyTask(
    config.jekyll.tmp + "/fonts/**/*.{eot,svg,ttf,woff,woff2,otf}",
    config.jekyll.assets + "/fonts")
);
gulp.task(
  "copyAssetsToBuild:downloads",
  requireCopyTask(
    config.jekyll.tmp + "/downloads/**/*",
    config.jekyll.assets + "/downloads")
);
gulp.task("copyAssetsToBuild",
  gulp.series(
    "copyAssetsToBuild:clean",
    gulp.parallel(
      "copyAssetsToBuild:scripts",
      "copyAssetsToBuild:styles",
      "copyAssetsToBuild:images",
      "copyAssetsToBuild:fonts",
      "copyAssetsToBuild:downloads")
  )
);

/**
 * Gulp Serve
 * Usage: gulp serve - Start BrowserSync and start watching for file changes
 */
gulp.task("serve", () => {
  // What directory are we starting browserSync in
  var baseDir = config.browserSync.development;
  if (argv.p) {
    baseDir = config.browserSync.production;
  }

  // Start browserSync
  browserSync({
    // files: ['./src/**', './tmp/**'],
    server: baseDir
  });

  // Watch for Jekyll file changes
  gulp.watch(
    [
      "src/**/*.md",
      "src/**/*.html",
      "src/**/*.yml",
      "src/**/*.xml",
      "src/**/*.txt"
    ]
  ).on("change", gulp.series(
    "jekyll:build",
    browserSync.reload
  ));

  // Watch for Script changes
  gulp.watch(
    "src/assets/scripts/**/*.js"
  ).on("change", gulp.series(
    "scripts",
    browserSync.reload
  ));

  // Watch for Styles changes
  gulp.watch(
    [
      "src/assets/sass/**/*.scss",
      "src/assets/styles/**/*.css"
    ]
  ).on("change", gulp.series(
      "styles",
      browserSync.reload
  ));

  // Watch for image changes
  gulp.watch(
    "src/assets/images/**/*"
  ).on("change", gulp.series(
      "images:build",
      browserSync.reload
  ));
});

/**
 * Gulp Default
 * Usage: gulp - Compile styles, scripts, images and fonts. Then inject references, build jekyll and server up.
 */
gulp.task("default",
  gulp.series(
    gulp.parallel("downloads", "styles", "scripts", "images:build", "fonts:build"),
    gulp.series(
      "inject",
      "jekyll:build",
      "serve"
    )
  )
);

/**
 * Gulp Build
 * Usage: gulp build -prod - Compile styles, scripts, images and fonts. Then inject references, build jekyll compress html and copy assets to build folder.
 */
gulp.task("build",
  gulp.series(
    gulp.parallel("downloads", "styles", "scripts", "images:build", "fonts:build"),
    gulp.series(
      "inject",
      "jekyll:build",
      "html",
      "copyAssetsToBuild"
    )
  )
);

/**
 * Gulp testProd
 * Usage: gulp testProd -prod - Run build for production
 */
gulp.task("testProd",
  gulp.series(
    gulp.parallel("downloads", "styles", "scripts", "images:build", "fonts:build"),
    gulp.series(
      "inject",
      "jekyll:build",
      "html",
      "copyAssetsToBuild",
      "serve"
    )
  )
);

/**
 * Gulp deploy
 * Usage: gulp deploy -prod - Build website and push to Github
 */
gulp.task(
  "deploy",
  gulp.series("build", "gh-pages")
);

gulp.task(
  "clean",
  gulp.series("copyAssetsToBuild:clean", "html:cleanGZips", "jekyll:clean")
);

gulp.task(
  "jsdocs",
  requireTask("jsdocs")
);


text:
<?xml version="1.0" encoding="utf-8"?>
<project name="BatchPaymentSFTPProvider" level="0" description="" />


text:
package com.cloud.network;

import org.apache.cloudstack.api.Identity;
import org.apache.cloudstack.api.InternalIdentity;

public interface CiscoNexusVSMDevice extends InternalIdentity, Identity {

    // This tells us whether the VSM is currently enabled or disabled. We may
    // need this if we would like to carry out any sort of maintenance on the
    // VSM or CS.
    public enum VSMDeviceState {
    	Enabled,
    	Disabled
    }

    // This tells us whether the VSM is currently configured with a standby (HA)
    // or does not have any standby (Standalone).
    public enum VSMConfigMode {
        Standalone,
        HA
    }

    // This tells us whether the VSM is currently a primary or a standby VSM.
    public enum VSMConfigState {
        Primary,
        Standby
    }

    public String getvsmName();

    public long getHostId();

    public String getUserName();

    public String getPassword();

    public String getipaddr();

    public int getManagementVlan();

    public int getControlVlan();

    public int getPacketVlan();

    public int getStorageVlan();

    public long getvsmDomainId();

    public VSMConfigMode getvsmConfigMode();

    public VSMConfigState getvsmConfigState();

    public VSMDeviceState getvsmDeviceState();

    public String getUuid();

}


text:
package com.sap.cloud.lm.sl.cf.core.model;

import java.util.Collections;
import java.util.Map;
import java.util.function.Supplier;

import org.apache.commons.collections4.map.AbstractReferenceMap.ReferenceStrength;
import org.apache.commons.collections4.map.ReferenceMap;

public class CachedMap<K, V> {

    private long expirationTimeInSeconds;
    private Supplier<Long> currentTimeSupplier = System::currentTimeMillis;

    private Map<K, CachedObject<V>> referenceMap = Collections
        .synchronizedMap(new ReferenceMap<>(ReferenceStrength.HARD, ReferenceStrength.SOFT));

    public CachedMap(long expirationTimeInSeconds) {
        this.expirationTimeInSeconds = expirationTimeInSeconds;
    }

    public synchronized V get(K key, Supplier<V> refreshFunction) {
        CachedObject<V> value = referenceMap.get(key);
        if (value == null) {
            value = new CachedObject<>(expirationTimeInSeconds, currentTimeSupplier);
            referenceMap.put(key, value);
        }
        return value.get(refreshFunction);
    }

    public synchronized V forceRefresh(K key, Supplier<V> refreshFunction) {
        CachedObject<V> value = referenceMap.get(key);
        if (value == null) {
            value = new CachedObject<>(expirationTimeInSeconds, currentTimeSupplier);
            referenceMap.put(key, value);
        }
        return value.forceRefresh(refreshFunction);
    }

}


text:
using System.Linq;
using StockportContentApi.ContentfulModels;
using StockportContentApi.Model;
using StockportContentApi.Utils;

namespace StockportContentApi.ContentfulFactories.GroupFactories
{
    public class GroupHomepageContentfulFactory : IContentfulFactory<ContentfulGroupHomepage, GroupHomepage>
    {
        private readonly DateComparer _dateComparer;
        private IContentfulFactory<ContentfulGroup, Group> _groupFactory;
        private IContentfulFactory<ContentfulGroupCategory, GroupCategory> _groupCategoryListFactory;
        private IContentfulFactory<ContentfulGroupSubCategory, GroupSubCategory> _groupSubCategoryListFactory;
        private readonly IContentfulFactory<ContentfulAlert, Alert> _alertFactory;
        private readonly IContentfulFactory<ContentfulEventBanner, EventBanner> _eventBannerFactory;

        public GroupHomepageContentfulFactory(IContentfulFactory<ContentfulGroup, Group> groupFactory, IContentfulFactory<ContentfulGroupCategory, GroupCategory> groupCategoryListFactory, IContentfulFactory<ContentfulGroupSubCategory, GroupSubCategory> groupSubCategoryListFactory, ITimeProvider timeProvider, IContentfulFactory<ContentfulAlert, Alert> alertFactory, IContentfulFactory<ContentfulEventBanner, EventBanner> eventBannerFactory)
        {
            _groupFactory = groupFactory;
            _groupCategoryListFactory = groupCategoryListFactory;
            _groupSubCategoryListFactory = groupSubCategoryListFactory;
            _dateComparer = new DateComparer(timeProvider);
            _alertFactory = alertFactory;
            _eventBannerFactory = eventBannerFactory;
        }

        public GroupHomepage ToModel(ContentfulGroupHomepage entry)
        {
            var backgroundImage = ContentfulHelpers.EntryIsNotALink(entry.BackgroundImage.SystemProperties)
                                           ? entry.BackgroundImage.File.Url : string.Empty;

            var groups = entry.FeaturedGroups.Select(g => _groupFactory.ToModel(g));

            var groupCategory = _groupCategoryListFactory.ToModel(entry.FeaturedGroupsCategory);

            var groupSubCategory = _groupSubCategoryListFactory.ToModel(entry.FeaturedGroupsSubCategory);

            var featuredGroup = groups.Where(group => _dateComparer.DateNowIsNotBetweenHiddenRange(
                group.DateHiddenFrom, group.DateHiddenTo)).ToList();

            var alerts = entry.Alerts.Select(_ => _alertFactory.ToModel(_));

            var bodyHeading = entry.BodyHeading;

            var body = entry.Body;

            var secondaryBodyHeading = entry.SecondaryBodyHeading;

            var secondaryBody = entry.SecondaryBody;

            var eventBanner = ContentfulHelpers.EntryIsNotALink(entry.EventBanner.Sys)
                ? _eventBannerFactory.ToModel(entry.EventBanner) : new NullEventBanner();

            return new GroupHomepage(entry.Title, entry.Slug, entry.MetaDescription, backgroundImage, entry.FeaturedGroupsHeading, featuredGroup, groupCategory, groupSubCategory, alerts, bodyHeading, body, secondaryBodyHeading, secondaryBody, eventBanner);
        }
    }
}


text:
package com.castlemock.service.mock.rest.project.output;

import com.castlemock.model.core.Output;
import com.castlemock.model.core.validation.NotNull;
import com.castlemock.model.mock.rest.domain.RestMethod;

/**
 * @author Karl Dahlgren
 * @since 1.0
 */
public final class UpdateRestMethodOutput implements Output {

    @NotNull
    private final RestMethod restMethod;

    private UpdateRestMethodOutput(RestMethod restMethod) {
        this.restMethod = restMethod;
    }

    public RestMethod getRestMethod() {
        return restMethod;
    }

    public static Builder builder(){
        return new Builder();
    }

    public static final class Builder {

        private RestMethod restMethod;

        public Builder restMethod(final RestMethod restMethod){
            this.restMethod = restMethod;
            return this;
        }

        public UpdateRestMethodOutput build(){
            return new UpdateRestMethodOutput(this.restMethod);
        }

    }
}


text:
@class FMXDatabaseManager;
@class FMXDatabaseConfiguration;

@interface FMXDatabaseMigration : NSObject

@property (strong, nonatomic) NSString *versionTable;
@property (strong, nonatomic) FMXDatabaseConfiguration *configuration;
@property (assign, nonatomic) int currentVersion;

- (id)initWithVersionTable:(NSString *)versionTable;
- (void)prepareMigrationWithConfiguration:(FMXDatabaseConfiguration *)configuration;
- (void)migrate;
- (void)upToVersion:(int)version action:(void (^)(FMDatabase *db))action;

@end


text:
package io.netflow.storage.redis

import io.netflow.flows.cflow._
import io.netflow.lib._

private[netflow] object NetFlowV6Packet extends FlowPacketMeta[NetFlowV6Packet] {
  def persist(fp: NetFlowV6Packet): Unit = ()
}


text:
module CError (module Foreign.C.Error) where
import Foreign.C.Error


text:
<?
    // Basic structure
    // 1. Display CSV file and field order inputs
    // 2. Display confirmation
    // 3. Update database
    //  a. Read in state of database
    //  b. Add rows to this local state
    //  c. Write out new rows--that is, the rows in our local state that are not in the database
    // This process allows us to check for duplicates and other conditions in the database state
    // just by comparing array elements and without additional database queries

    // We create a new row in the location database iff locationName does not exist
    // We create a new row in the users database iff firstName . middleInit . lastName, email, userID do not exist
    Include("Includes/global.inc.php");
    checkPermissions(1, 1800);

    // The set up--you need this
    if ($_SESSION['stuckAtLocation']) {
        $importFields = array($progText249, $progText250, $progText251,
            $progText255, $progText256, $progText437);
    } else {
        $importFields = array($progText249, $progText250, $progText251, $progText91,
            $progText255, $progText256, $progText437);
    }

    // These are used in a few different places, might as well define them here
    function varFieldsToQueryString()
    {
        global $importFields;
        // Put field order back into GET query string so the user gets their inputted order back in case of error
        $fieldTerms = "";
        for ($i = 0; $i < count($importFields) - 1; $i++)
            $fieldTerms .= "varFields$i=" . $_POST['varFields' . $i] . (($i != count($importFields) - 2) ? "&" : "");
        return $fieldTerms;
    }
    function cleanHeaderFields()
    {
        global $importFields;
        for ($i = 0; $i < count($importFields) - 1; $i++)
            $_POST['varFields' . $i] = cleanFormInput($_POST['varFields' . $i]);
    }
    // ***
    // Submit clicked? Confirm input.
    // ***
    if ($_POST['btnSubmit'])
    {
        cleanHeaderFields();
        // Check that two fields (e.g. Field 1 and Field 2) don't both represent the same attribute (e.g. First Name)
        $duplicateFields = "";
        for ($i = 0; $i < count($importFields) - 1 && $duplicateFields == ""; $i++)
            for ($j = $i + 1; $j < count($importFields) - 1 && $duplicateFields == ""; $j++)
                if ($_POST['varFields' . $i] == $_POST['varFields' . $j] && $_POST['varFields' . $i] != $progText437)
                    $duplicateFields = $_POST['varFields' . $i];
        if ($duplicateFields != "")
            redirect("importUsers.php", "strError=" . $progText1055 . $duplicateFields . "&" . varFieldsToQueryString()); // two fields are representing [field name]
        else
        {
            // Check that required fields are present in user's order selection
            // Relies on the last 3 importFields not being required
            $missingField == "";
            for ($i = 0; $i < count($importFields) - 3 && $missingField == ""; $i++)
            {
                $found = 0;
                for ($j = 0; $j < count($importFields) && $found == 0; $j++)
                    if ($_POST['varFields' . $j] == $importFields[$i])
                        $found = 1;
                if ($i != 1 && ($_SESSION['stuckAtLocation'] || $i != 3) && !$found)
                    $missingField = $importFields[$i];
            }
            if ($missingField != "")
                redirect("importUsers.php", "strError=" . $missingField . " " . $progText540 . "&" . varFieldsToQueryString()); // [field name] is required
            else
            {
                if ($_FILES['csvFile']['size'] <= 0 ||
                    ($_FILES['csvFile']['type'] != "application/octet-stream" AND
                     $_FILES['csvFile']['type'] != "application/vnd.ms-excel" AND
                     $_FILES['csvFile']['type'] != "text/csv" AND
                     $_FILES['csvFile']['type'] != "text/comma-separated-values" AND
                     $_FILES['csvFile']['type'] != "application/csv" AND
                     $_FILES['csvFile']['type'] != "text/plain"))
                    redirect("importUsers.php", "strError=" . $progText1056 . "&" . varFieldsToQueryString()); // Error uploading file
                else
                {
                    // Show the table of input value to confirm
                    // Include hidden inputs to pass along values from file
                    writeHeader($progText1050);
                    declareError(TRUE);
                    $strLines = file($_FILES['csvFile']['tmp_name']);
                    echo "
$progText1054
\n";
                    echo "<form action=\"importUsers.php\" method=\"post\">\n";
                    echo "<input type='hidden' name='fileLinesCount' value='" . count($strLines) . "'>\n";

                    // Must separate hidden inputs that preserve header fields from header cells
                    //  because we don't display header cells if they contain N/A
                    for ($i = 0; $i < count($importFields) - 1; $i++)
                        echo "<input type='hidden' name='varFields$i' value='" . $_POST['varFields' . $i] . "'>";
                    echo "

";
                    echo "<input type='checkbox' name='chkConservative' checked> 	\n";
                    echo "$progText1120 - $progText1122	\n";
                    echo "

\n\n

\n";
                    // Header cells
                    for ($i = 0; $i < count($importFields) - 1; $i++)
                        if ($_POST['varFields' . $i] != $progText437) // display only if not an N/A field
                            echo "" . $_POST['varFields' . $i] . " 	\n";
                    echo "
";
                    // Rest of table
                    for ($i = 0; $i < count($strLines); $i++)
                    {
                        $strLines[$i] = cleanFormInput($strLines[$i]);
                        // Weed out blank lines
                        if ($strLines[$i] != "")
                        {
                            echo "
";
                            // Split table cells on commas in file
                            $fileVals = explode(",", $strLines[$i]);
                            for ($j = 0; $j < count($importFields) - 1; $j++)
                                if ($_POST['varFields' . $j] != $progText437) // display if not an N/A field
                                {
                                    if ($_POST['varFields' . $j] == $progText250 && $fileVals[$j])
                                        echo "" . substr($fileVals[$j], 0, 1) . " 	\n";
                                    else
                                        echo "" . $fileVals[$j] . " 	\n";
                                }
                            echo "<input type='hidden' name='fileLines$i' value='" . $strLines[$i] . "'>";
                            echo "
\n";
                        }
                    }
                    echo "
";
                    echo "
<input type='submit' name='btnConfirm' value='$progText1057'> <input type='submit' name='btnCancel' value='$progText1060'>
</form>\n";
                }
            }
        }
    }
    // ***
    // Cancel clicked? Return to data collecting (first) page
    // ***
    elseif ($_POST['btnCancel'])
        redirect("importUsers.php", varFieldsToQueryString());
    // ***
    // Confirm clicked? Do database update.
    // ***
    elseif ($_POST['btnConfirm'])
    {
        function getKeys($total, $hashIn)
        {
            return array_merge($total, array_keys($hashIn));
        }
        function getUserIDs($total, $hashIn)
        {
            $total[] = $hashIn['userID'];
            return $total;
        }
        function getEmails($total, $hashIn)
        {
            $total[] = $hashIn['email'];
            return $total;
        }
        function addImportError(&$strErrors, $i, $builtName, $progTextError)
        {
            global $progText1063, $progText1064;
            $strErrors[count($strErrors)] = $progText1063 . " #" . ($i + 1) . " - " . $builtName . " - " . $progText1064 . ": " . $progTextError;
        }

        cleanHeaderFields();
        $_POST['fileLinesCount']  = cleanFormInput($_POST['fileLinesCount']);
        $chkConservative = cleanFormInput($_POST['chkConservative']);
        // Init array we'll use to display errors
        unset($strErrors);
        // Init front end => db style field name mapper
        if ($_SESSION['stuckAtLocation']) {
            $frontEndToDBStyleFields = array($importFields[0] => 'firstName',
                                    $importFields[1] => 'middleInit',
                                    $importFields[2] => 'lastName',
                                    $importFields[3] => 'userID',
                                    $importFields[4] => 'email');
        } else {
            $frontEndToDBStyleFields = array($importFields[0] => 'firstName',
                                    $importFields[1] => 'middleInit',
                                    $importFields[2] => 'lastName',
                                    $importFields[3] => 'locationName',
                                    $importFields[4] => 'userID',
                                    $importFields[5] => 'email');
        }

        /* Read in State of Database */
        // Get our current list of locations, key on locationName
        // initialize key prefixes -- these prevent collisions among keys of different fields
        // --useless for locations..!
        $keyPrefix['locationName'] = md5("locationName");
        $strSQL = "SELECT locationID, locationName FROM locations WHERE accountID=" . $_SESSION['accountID'] . "";
        $result = dbquery($strSQL);
        while ($row = mysql_fetch_assoc($result))
            $dbLocs[$keyPrefix['locationName'] . $row['locationName']] = $row;
        // Get users, key on firstName . lastName, email, userID
        // initialize key prefixes
        $keyPrefix['fullName'] = md5("fullName");
        $keyPrefix['userID'] = md5("userID");
        $keyPrefix['email'] = md5("email");
        $strSQL = "SELECT * FROM tblSecurity WHERE hidden='0' AND accountID=" . $_SESSION['accountID'] . "";
        $result = dbquery($strSQL);
        while ($row = mysql_fetch_assoc($result))
        {
            $dbUsers[$keyPrefix['fullName'] . $row['firstName'] . $row['middleInit'] . $row['lastName']][] = $row;
            if (isset($row['userID']))
                $dbUsers[$keyPrefix['userID'] . $row['userID']][] = $row;
            if (isset($row['email']))
                $dbUsers[$keyPrefix['email'] . $row['email']][] = $row;
        }

        /* Add Rows to Local State */
        // For each row in the input file...
        for ($i = 0; $i < $_POST['fileLinesCount']; $i++)
        {
            if ($_POST['fileLines' . $i] == "")
                continue;
            // Explode values on commas from POST input from confirmation page
            $fileLineVals = explode(',', $_POST['fileLines' . $i]);
            // Generate an associative array that maps a field name (User ID, Last Name, ...) to its value
            for ($j = 0; $j < count($importFields); $j++)
                $currentAssVals[$frontEndToDBStyleFields[$_POST['varFields' . $j]]] = $fileLineVals[$j];
            // Middle initial fix
            if ($currentAssVals['middleInit'])
                $currentAssVals['middleInit'] = substr($currentAssVals['middleInit'], 0, 1);
            // Save a bit of typing:
            $currentAssVals['fullName']  = $currentAssVals['firstName'] . $currentAssVals['middleInit'] . $currentAssVals['lastName'];
            $currentAssVals['builtName'] = buildName($currentAssVals['firstName'], $currentAssVals['middleInit'], $currentAssVals['lastName']);
            // Validate input
            $currentAssVals['firstName']    = validateText($progText249, $currentAssVals['firstName'], 2, 40, TRUE, FALSE);
            $currentAssVals['middleInit']   = validateText($progText250, $currentAssVals['middleInit'], 1, 1, FALSE, FALSE);
            $currentAssVals['lastName']     = validateText($progText251, $currentAssVals['lastName'], 2, 40, TRUE, FALSE);
            if ($_SESSION['stuckAtLocation']) {
                $currentAssVals['locationName'] = "";
            } else {
                $currentAssVals['locationName'] = validateText($progText91, $currentAssVals['locationName'], 2, 60, FALSE, FALSE);
            }
            $currentAssVals['userID']       = validateText($progText255, $currentAssVals['userID'], 3, 20, FALSE, FALSE);
            $currentAssVals['email']        = validateEmail($progText256, $currentAssVals['email'], FALSE);
            if ($strError != "")
            {
                $strErrors[count($strErrors)] = $progText1063 . " #" . ($i + 1) . " - " . $currentAssVals['builtName'] . " - " . $progText1064 . ": " . $strError;
                $strError = "";
            }
            else
            {
                // Check if this user is already in the db using full name, email address, and userID
                // There's a couple ways to do this. The problem is that PHP doesn 't want to do an
                // array search on something that's not an array. Ideally it would just return 0 if
                // it weren't an array. So we just suppress the error. I don't know if this solution
                // is faster than checking to see whether the DB entry is an array before searching it.
                $builtKeys      = @array_reduce($dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']], "getKeys", array());
                $existsDbUserId = @in_array("userID", $builtKeys);
                $existsDbEmail  = @in_array("email", $builtKeys);
                $builtUserIDs   = @array_reduce($dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']], "getUserIDs", array());
                $matchUserId    = @in_array($currentAssVals['userID'], $builtUserIDs);
                $builtEmails    = @array_reduce($dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']], "getEmails", array());
                $matchEmail     = @in_array($currentAssVals['email'], $builtEmails);
                if  ($currentAssVals['userID']
                    && $dbUsers[$keyPrefix['userID'] . $currentAssVals['userID']])
                {
                    addImportError(&$strErrors, $i, $currentAssVals['builtName'], $progText257);
                }
                elseif ($currentAssVals['email']
                    && $dbUsers[$keyPrefix['email'] . $currentAssVals['email']])
                {
                    addImportError(&$strErrors, $i, $currentAssVals['builtName'], $progText258);
                }
                elseif ((($chkConservative == "on")
                     && ($dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']])
                     && (($existsDbUserId && !$currentAssVals['userID'])
                      || (!$existsDbUserId && $currentAssVals['userID'])
                      || ($existsDbEmail && !$currentAssVals['email'])
                      || (!$existsDbEmail && $currentAssVals['email'])))
                    && !(($currentAssVals['userID'] && $existsDbUserId && !$matchUserId)
                      || ($currentAssVals['email'] && $existsDbEmail && !$matchEmail)))
                {
                    addImportError(&$strErrors, $i, $currentAssVals['builtName'], $progText1059);
                }
                elseif (($dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']])
                     && $matchUserId && $matchEmail)
                {
                    addImportError(&$strErrors, $i, $currentAssVals['builtName'], $progText1059);
                }
                else
                {
                    // Check if this user is associated with a new location
                    if (!isset($dbLocs[$keyPrefix['locationName'] . $currentAssVals['locationName']]))
                    {
                        // Add location to $dbLocs hash table
                        // and to sequential array representing incremental change in 'locations' table
                        $dbLocs[$keyPrefix['locationName'] . $currentAssVals['locationName']] = $currentAssVals;
                        // deltaLocs is just an array of locationNames, not an array of associative arrays
                        $dbDeltaLocs[count($dbDeltaLocs)] = $currentAssVals['locationName'];
                    }
                    else
                        $dbDeltaLocs[count($dbDeltaLocs)] = "";
                    // Add user to $dbUsers hash table
                    //  and to sequential array representing incremental change in 'tblSecurity' table
                    $dbUsers[$keyPrefix['fullName'] . $currentAssVals['fullName']][] = $currentAssVals;
                    if ($currentAssVals['userID'])
                        $dbUsers[$keyPrefix['userID'] . $currentAssVals['userID']][] = $currentAssVals;
                    if ($currentAssVals['email'])
                        $dbUsers[$keyPrefix['email'] . $currentAssVals['email']][] = $currentAssVals;
                    $dbDeltaUsers[count($dbDeltaUsers)] = $currentAssVals;
                }
            }
        }
        /* Write Out New Rows */
        // For each new user..
        for ($i = 0; $i < count($dbDeltaUsers); $i++)
        {
            // Add new location if needed
            if ($dbDeltaLocs[$i] != "" && !$_SESSION['stuckAtLocation'])
            {
                dbquery("INSERT INTO locations (locationName, accountID) VALUES ('" . $dbDeltaLocs[$i] . "', " . $_SESSION['accountID'] . ")");
                // Not sure what the db is going to assign for locationID, so grab it
                $result = dbquery("SELECT locationID FROM locations WHERE locationName='" . $dbDeltaLocs[$i] . "' AND accountID=" . $_SESSION['accountID'] . "");
                $row = mysql_fetch_assoc($result);
                $dbDeltaUsers[$i]['locationID'] = $row['locationID'];
            }
            else {
                if ($_SESSION['stuckAtLocation']) {
                    $dbDeltaUsers[$i]['locationID'] = $_SESSION['locationStatus'];
                } else {
                    $dbDeltaUsers[$i]['locationID'] = $dbLocs[$keyPrefix['locationName'] . $dbDeltaUsers[$i]['locationName']]['locationID'];
                }
            }
            // Add user
            $result = dbquery("INSERT INTO tblSecurity (userID, firstName, middleInit, lastName, email, securityLevel, userLocationID, accountID)
                VALUES (" . makeNull($dbDeltaUsers[$i]['userID'], TRUE) . ", '" . $dbDeltaUsers[$i]['firstName'] . "', '"
                . $dbDeltaUsers[$i]['middleInit'] . "', '" . $dbDeltaUsers[$i]['lastName'] . "', " . makeNull($dbDeltaUsers[$i]['email'], TRUE) . ", 3, "
                . makeNull($dbDeltaUsers[$i]['locationID'], TRUE) . ", " . $_SESSION['accountID'] . ")");
        }
        if (count($strErrors) == 0)
            $strError = $progText1061; // success
        else
        {
            $strError = $progText1062 . "
"; // completed, but with errors
            for ($i = 0; $i < count($strErrors); $i++)
                $strError .= "
" . $strErrors[$i];
        }

        redirect("importUsers.php", "strError=$strError&" . varFieldsToQueryString());
    }
    // ***
    // No submit buttons clicked? Display file and field order inputs.
    // ***
    else
    {
        writeHeader($progText1050);
        declareError(TRUE);
        function getFieldComboBox($index)
        {
            global $importFields;
            $toReturn = "<select name='varFields$index'>\n";
            for ($i = 0; $i < count($importFields); $i++)
            {
                if (isset($_GET['varFields' . $index]))
                    $strSelected = ($importFields[$i] == $_GET['varFields' . $index] ? "selected" : "");
                else
                    $strSelected = ($i == $index ? "selected" : "");
                $toReturn .= "<option value='" . $importFields[$i] . "' " . $strSelected . ">$importFields[$i]</option>\n";
            }
            return $toReturn;
        }
        echo "
$progText1053
";
        echo "<form enctype=\"multipart/form-data\" action=\"importUsers.php\" method=\"post\">";
        echo "
";
        // echo "<input type='hidden' name='MAX_FILE_SIZE' value='500000'>"
        echo "
$progText1052	<input name='csvFile' type='file' size='20'>
";
        for ($i = 0; $i < count($importFields) - 1; $i++)
        {
            echo "
" . $progText1051 . " " . ($i + 1) .
                "	" . getFieldComboBox($i) . "
";
        }
        // Yeah, gonna unrem these when David feels like QAing Default Location
        //echo "
" . $progText1121 . ": 	";
        //buildLocationSelect($_POST['cboLocationID']);
        echo "
\n";
        echo "
";
        echo "
<input type='submit' name='btnSubmit' value='$progText21'>
</form>";
    }
    writeFooter();
?>


text:
(function (sx, $, _) {
    sx.createNamespace('classes.shop', sx);

    /**
     * Объект корзины
     * Слушает события магазина
     * Умеет обновляться update();
     *
     * @events:
     * update
     * beforeUpdate
     */
    sx.classes.shop._Cart = sx.classes.Component.extend({

        construct: function (Shop, id, opts) {
            var self = this;
            opts = opts || {};

            if (!Shop instanceof sx.classes.shop._App) {
                throw new Error("Shop object not found");
            }

            this.id = String(id);
            this.Shop = Shop;
            this.Shop.registerCart(this);

            //this.parent.construct(opts);
            this.applyParentMethod(sx.classes.Component, 'construct', [opts]); // TODO: make a workaround for magic parent calling
        },

        _init: function () {
            var self = this;

            this.Shop.bind('change', function (e, data) {
                self.update();
            });
        },

        update: function () {
            this.trigger('beforeUpdate', {
                'Cart': this
            });
            //throw new Error("Not implemented this method");
            return this;
        },

        /**
         * @returns {*|HTMLElement}
         * @constructor
         */
        JWrapper: function () {
            return $('#' + this.id);
        }
    });

    sx.classes.shop.Cart = sx.classes.shop._Cart.extend({});

    /**
     * Корзина которая перезагружается Pjax
     *
     * @options:
     * delay - задержка обновления контейнера
     */
    sx.classes.shop.CartPjax = sx.classes.shop.Cart.extend({

        _init: function () {
            this.applyParentMethod(sx.classes.shop.Cart, '_init', []);

            var self = this;

            self.JWrapper().on('pjax:complete', function () {
                self.trigger('update', {
                    'Cart': this
                });
            });
        },

        /**
         * @returns {sx.classes.shop.CartPjax}
         */
        update: function () {
            var self = this;

            this.trigger('beforeUpdate', {
                'Cart': this
            });

            _.delay(function () {
                var selector = '';

                if (self.JWrapper().get(0).id) {
                    selector = "#" + self.JWrapper().get(0).id;
                } else {
                    //todo depricated в jquery > 1.8
                    selector = self.JWrapper().selector;
                }

                $.pjax.reload(selector, {
                    push: false
                });
            }, Number(this.get('delay', 0)));

            return this;
        },
    });

})(sx, sx.$, sx._);


text:
class cGameObject;

class cAction : public cObject
{
protected:
	float m_fPassedTime;
	SYNTHESIZE(float, m_fActionTime, ActionTime);
	SYNTHESIZE(cGameObject*, m_pOwner, Owner);
	SYNTHESIZE(iActionDelegate*, m_pDelegate, Delegate);

public:
	cAction();
	virtual ~cAction();
	virtual void Start() {}
	virtual void Update(float delta) = 0;
};


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

/*
 *    UnivariateIntervalEstimator.java
 *    Copyright (C) 2009-2012 University of Waikato, Hamilton, New Zealand
 *
 */

package weka.estimators;

/**
 * Interface that can be implemented by simple weighted univariate
 * interval estimators.
 *
 * @author Eibe Frank (eibe@cs.waikato.ac.nz)
 * @version $Revision: 8034 $
 */
public interface UnivariateIntervalEstimator {

  /**
   * Adds a value to the interval estimator.
   *
   * @param value the value to add
   * @param weight the weight of the value
   */
  void addValue(double value, double weight);

  /**
   * Returns the intervals at the given confidence value. Each row has
   * one interval. The first element in each row is the lower bound,
   * the second element the upper one.
   *
   * @param confidenceValue the value at which to evaluate
   * @return the interval
   */
  double[][] predictIntervals(double confidenceValue);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="?android:attr/colorBackground"
    android:orientation="vertical">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="0dp"
        android:background="?android:colorForegroundInverse"
        android:orientation="vertical"
        android:paddingLeft="0dp"
        android:paddingRight="0dp">

        <FrameLayout
            android:id="@+id/FrameLayoutSince"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="4dp"
            android:paddingLeft="8dp"
            android:paddingRight="8dp"
            android:paddingTop="4dp">

            <TextView
                android:id="@+id/stats_since"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:fontFamily="sans-serif-light"
                android:maxLines="1"
                android:text="Since"
                android:textSize="@dimen/text_size_medium"
                android:visibility="visible" />
        </FrameLayout>
    </LinearLayout>

        <ListView
            android:id="@+id/wakelock_data_listview1"
            android:layout_width="fill_parent"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:background="?android:attr/colorBackground"
            android:dividerHeight="1px" />

</LinearLayout>


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>OrderDoneMessage | GDAX Trading Toolkit API Reference</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="../assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					GDAX Trading Toolkit API Reference

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

					"src/core/Messages"

					OrderDoneMessage

Interface OrderDoneMessage

In order-level books, means an order has been filled, or cancelled. RemainingSize indicated how much of the order
						was left unfilled if it was cancelled

Hierarchy

						BaseOrderMessage

								OrderDoneMessage

Index

Properties

order<wbr>Id

price

product<wbr>Id

reason

remaining<wbr>Size

sequence

side

source<wbr>Sequence

time

type

Properties

order<wbr>Id

order<wbr>Id: string

Inherited from BaseOrderMessage.orderId

Defined in src/core/Messages.ts:71

price

price: string

Inherited from BaseOrderMessage.price

Defined in src/core/Messages.ts:72

product<wbr>Id

product<wbr>Id: string

Inherited from OrderbookMessage.productId

Defined in src/core/Messages.ts:57

reason

reason: string

Defined in src/core/Messages.ts:93

remaining<wbr>Size

remaining<wbr>Size: string

Defined in src/core/Messages.ts:94

sequence

sequence: number

Inherited from OrderbookMessage.sequence

Defined in src/core/Messages.ts:55

side

side: string

Inherited from OrderbookMessage.side

Defined in src/core/Messages.ts:58

Optional source<wbr>Sequence

source<wbr>Sequence: number

Inherited from OrderbookMessage.sourceSequence

Defined in src/core/Messages.ts:56

time

time: Date

Inherited from StreamMessage.time

Defined in src/core/Messages.ts:25

type

type: string

Inherited from StreamMessage.type

Defined in src/core/Messages.ts:24

						Globals

						"src/core/<wbr>Messages"

						Base<wbr>Order<wbr>Message

						Cancel<wbr>Order<wbr>Request<wbr>Message

						Changed<wbr>Order<wbr>Message

						Error<wbr>Message

						Level<wbr>Message

						My<wbr>Order<wbr>Placed<wbr>Message

						New<wbr>Order<wbr>Message

						Order<wbr>Done<wbr>Message

								order<wbr>Id

								price

								product<wbr>Id

								reason

								remaining<wbr>Size

								sequence

								side

								source<wbr>Sequence

								time

								type

						Orderbook<wbr>Message

						Place<wbr>Order<wbr>Message

						Snapshot<wbr>Message

						Stream<wbr>Message

						Ticker<wbr>Message

						Trade<wbr>Executed<wbr>Message

						Trade<wbr>Finalized<wbr>Message

						Trade<wbr>Message

						Unknown<wbr>Message

						is<wbr>Error<wbr>Message

						is<wbr>Order<wbr>Message

						is<wbr>Orderbook<wbr>Message

						is<wbr>Stream<wbr>Message

						is<wbr>Unknown<wbr>Message

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the AutenticationService provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/

@Injectable()
export class AutenticationService {

  public data: any;
  public api_url: string;

  constructor(public http: Http) {
   this.api_url = 'http://localhost:8282/dedao/app_carona/webservice/';
  }

  // Insere usuário
  add(nome, email, senha) {

    return new Promise(resolve => {
      this.http.post(this.api_url + 'usuarios/add', {'Usuario': {'nome': nome, 'email': email, 'senha': senha}})
        .map(res => res.json())
        .subscribe(data => {
          this.data = data.results;
          resolve(this.data);
        });
    });
  }

}


text:
<!doctype html>
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/cookies/resources/testharness-helpers.js"></script>
<body>
<script>
// Set cookies on ORIGINAL_HOST, then move ourselves to TEST_ROOT so
// we can verify cross-origin behavior.
if (window.location.hostname == "127.0.0.1") {
    window.location.hostname = ORIGINAL_HOST;
} else if (window.location.hostname == ORIGINAL_HOST) {
    clearKnownCookies();
    document.cookie = STRICT_DOM + "=1; SameSite=Strict; Max-Age=100; path=/";
    document.cookie = LAX_DOM + "=1; SameSite=Lax; Max-Age=100; path=/";
    document.cookie = NORMAL_DOM + "=1; Max-Age=100; path=/";
    window.location.hostname = TEST_HOST;
} else {
    async_test(t => {
        window.addEventListener("message", t.step_func_done(e => {
            assert_equals(e.data.http[STRICT_DOM], undefined, "strict");
            assert_equals(e.data.http[LAX_DOM], undefined, "lax");
            assert_equals(e.data.http[NORMAL_DOM], "1", "normal");
            // TODO(mkwst): This should exclude the samesite cookies.
            assert_equals(e.data.document, STRICT_DOM + "=1; " + LAX_DOM + "=1; " + NORMAL_DOM + "=1");
            e.source.close();
        }));

        var f = document.createElement('form');
        f.action = "http://" + ORIGINAL_HOST + ":8000/cookies/resources/post-cookies-to-opener.php";
        f.method = "POST";
        f.target = "_blank"
        window.onload = t.step_func(f.submit.bind(f));
        document.body.appendChild(f);
    }, "'" + ORIGINAL_HOST + "' is not same-site with '" + TEST_HOST + "', so samesite cookies are not sent via POST.");
}
</script>
</body>


text:
namespace EntityStore {

enum class EntityState {
  Default,
  OnlyUpdated,
  InsertedByThis,
  ReInsertedByThis,
  RemovedByThis,
};

class EntityStateHandler {
public:
  void insert();
  void update();
  void remove();

  [[nodiscard]] bool needsToInsertToParent() const;
  [[nodiscard]] bool needsToUpdateInParent() const;
  [[nodiscard]] bool needsToRemoveFromParent() const;
  [[nodiscard]] const EntityState &state() const;

private:
  EntityState m_state{EntityState::Default};
};

class EntityTransaction;

class EntityStatesManager {
public:
  friend EntityTransaction;
  using StateHandlerMap = std::unordered_map<EntityId, EntityStateHandler>;

  EntityStatesManager() = default;
  EntityStatesManager(const EntityStatesManager &) = default;
  EntityStatesManager(EntityStatesManager &&) = default;
  EntityStatesManager &operator=(const EntityStatesManager &) = default;
  // Cannot be noexcept because of std::unordered_map is not noexcept move constructible
  EntityStatesManager &operator=(EntityStatesManager &&) = default;
  ~EntityStatesManager() = default;

  [[nodiscard]] const EntityStateHandler *tryGetState(const EntityId id) const;
  [[nodiscard]] const EntityStateHandler &getState(const EntityId id) const;

  // TODO(antaljanosbenjamin) Add insert/update/remove tokens to make sure only the regarding operation can be done
  [[nodiscard]] EntityTransaction startInsert(const EntityId id);
  [[nodiscard]] EntityTransaction startUpdate(const EntityId id);
  [[nodiscard]] EntityTransaction startRemove(const EntityId id);

  [[nodiscard]] std::unordered_set<EntityId> createEntityIdsSet() const;
  bool eraseStateHandler(const EntityId id);
  [[nodiscard]] const StateHandlerMap &stateHandlers() const;

private:
  StateHandlerMap m_stateHandlers;
};

class EntityTransaction {
public:
  friend EntityStatesManager;
  EntityTransaction() = delete;
  EntityTransaction(EntityTransaction &) = delete;
  EntityTransaction(EntityTransaction &&) = delete;
  EntityTransaction &operator=(EntityTransaction &) = delete;
  EntityTransaction &operator=(EntityTransaction &&) = delete;

  ~EntityTransaction();
  // TODO(antaljanosbenjamin) Check if explicit commiting is feasible
  void abort();

  EntityStateHandler &operator*();
  const EntityStateHandler &operator*() const;
  EntityStateHandler *operator->();
  const EntityStateHandler *operator->() const;

private:
  enum class Type {
    Insert,
    Update,
    Remove,
  };

  EntityTransaction(EntityStatesManager &manager, const EntityId id, Type type);

  // TODO(antaljanosbenjamin) Use pointer here and remove const from m_type to make move work
  EntityStatesManager &m_manager;
  const Type m_type;
  typename EntityStatesManager::StateHandlerMap::iterator m_handlerIt;
  bool m_aborted;
};

} // namespace EntityStore


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Coleostephus clausonis Pomel

### Remarks
null


text:
struct configuration
{
    // To transfer e.g. c:/_svn/boost/trunk/boost/geometry/algorithms/area.hpp
    // to #include <boost/geometry/...>
    // We need to find the position where the include path should start,
    // so fill out "boost" here, or "boost/geometry" (it uses rfind)
    std::string start_include;

    // Convenience headers (headefiles with solely purpose of including others
    std::string convenience_header_path;
    std::vector<std::string> convenience_headers;

    std::string skip_namespace;

    enum output_style_type {def, alt};
    output_style_type output_style;
    configuration() : output_style(def) {}
};

#endif // CONFIGURATION_HPP


text:
package edu.umass.ciir.kbbridge.features.util

/**
 *
 */

object TfidfUtil {
  case class TfIDfEntry(term:String, mCount:Int, idf:Double,  eCount:Int){
    def addETerm:TfIDfEntry =  {
      TfIDfEntry(term, mCount, idf, eCount +1)
    }
    def tfidf:Double = {
      1.0 * idf * mCount * eCount
    }

    def innerProduct:Double = {
      1.0 * mCount * eCount
    }

    def normFirst:Double = {
      (idf * mCount) * (idf * mCount)
    }
    def normSecond:Double = {
      (idf * eCount) * (idf * eCount)
    }
  }

  type TfIDFMap = Map[String,  TfIDfEntry]

  def baseMap(contextTerms:Seq[String], fetchIdf:(String => Double)):TfIDFMap = {
    val mHash = contextTerms.groupBy(x => x).map(entry => entry._1 -> entry._2.length)
    val mIdfHash = mHash.map(entry => (entry._1 -> TfIDfEntry(entry._1, entry._2, fetchIdf(entry._1), 0)))
    mIdfHash
  }

  def baseBatchMap(contextTerms:Seq[String], fetchIdfBatch:(Seq[String] => Map[String, Double])):TfIDFMap = {
    val mHash = contextTerms.groupBy(x => x).map(entry => entry._1 -> entry._2.length)
    val idf = fetchIdfBatch(mHash.keys.toSeq)
    val zipped = mHash.zip(idf)
    val mIdfHash =
      for(((term:String,  tf:Int),(term2:String, df:Double)) <- zipped) yield {
         if(term != term2) throw new RuntimeException("terms do not match, zip went wrong "+term+" - "+term2)
        (term -> TfIDfEntry(term, tf, df, 0))
      }
//    val mIdfHash = mHash.map(entry => (entry._1 -> TfIDfEntry(entry._1, entry._2, fetchIdf(entry._1), 0)))
    mIdfHash
  }

  def updateBaseMap(contextTerms: scala.Seq[String], baseMap: TfIDFMap): TfIDFMap ={
    val map =
      contextTerms.foldLeft(baseMap)({
        case (hash: TfIDFMap, term: String) => {
          val res = hash.get(term)
          if (res == None) hash
          else {
            hash.updated(term, res.get.addETerm)
          }
        }
      })

    map.filter(_._2.eCount>0)
  }

  def computeNorm(tfidfMap:TfIDFMap):(Double,  Double) = {
    val (first, second) = tfidfMap.values.map(entry => (entry.normFirst, entry.normSecond)).unzip
    (first.sum, second.sum)
  }

  //==================================
  //== Measures ==
  //--
  //-

  def computeTfidf(tfidfMap:TfIDFMap):Double = {
    val score = tfidfMap.values.map(_.tfidf).sum
    score
  }

  def computeCosine(tfidfMap:TfIDFMap):Double = {
    val num = 1.0 * tfidfMap.values.map(_.innerProduct).sum
    val (firstLen, secondLen) = computeNorm(tfidfMap)
    val den = 1.0 * math.sqrt(firstLen) *  math.sqrt(secondLen)
    val score =
      if(den == 0.0) 0.0 else {
      num/den
    }
    score
  }

  def computeTanimoto(tfidfMap:TfIDFMap):Double = {
//    throw new RuntimeException("I dont think this code is correct.")
    val (firstLen, secondLen) = computeNorm(tfidfMap)
    val num =  tfidfMap.values.map(_.innerProduct).sum
    val den = firstLen + secondLen - num

    val score =
      if(num == 0.0) 0.0
      else 1.0*num/den
    score
  }

}


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

package com.google.security.zynamics.binnavi.Database.Interfaces;

/**
 * Listener interface for events that relate to {@link SQLProvider provider} changes
 */
public interface SQLProviderListener {

  /**
   * Method to notify that the {@link SQLProvider provider} is closing.
   *
   * @param provider the {@link SQLProvider provider} that is closed.
   */
  public void providerClosing(final SQLProvider provider);
}


text:
require 'rubygems'
require 'sinatra/base'
require 'filesize'
include FileUtils::Verbose

class ServiceEdt < Sinatra::Base
  set :port, 80

  helpers do
    def to_french(size)
      size.gsub!(/[i]/, '').gsub!(/[B]/, 'o')
    end
  end

  ['/', '/form'].each do |route|
    get route do
      @title = "Sinatra Application"
      erb :index
    end
  end

  # Réception des fichiers signés et cryptés
  post '/' do
    redirect '/form' if params.empty?

    @filename = params[:file][:filename]
    tempfile = params[:file][:tempfile]
    @filesize = to_french Filesize.from(tempfile.length.to_s + " B").pretty
    cp(tempfile.path, "public/uploads/"+ Time.now.to_s + @filename)

    erb :upload_ok
  end

end


text:
Phoda\Session
==============

Simple session management component

How to use it
=============

Setting and getting properties
------------------------------

	use Phoda\Session\Session;

    require 'Session.php';

    Session::start();

    $session = new Session();
    $session->name = 'My name';
    $session->emails = array('email1@example.com', 'email2@example.com');

	// Objects are serialized and unserialized automatically
    $session->user = new stdClass();

    var_dump($session->name);
    var_dump($session->emails);
    var_dump($session->user);

    Session::destroy();

Checking whether the property isset and removing the property
--------------------------

	use Phoda\Session\Session;

    require 'Session.php';

    Session::start();

    $session = new Session();
    $session->name = 'My name';
    $session->emails = array('email1@example.com', 'email2@example.com');
    $session->user = new stdClass();

	var_dump(isset($session->name));
	$session->remove('name');
	var_dump(isset($session->name));

    Session::destroy();

Iterating thru the session
--------------------------

	use Phoda\Session\Session;

    require 'Session.php';

    Session::start();

    $session = new Session();
    $session->name = 'My name';
    $session->emails = array('email1@example.com', 'email2@example.com');
    $session->user = new stdClass();

    foreach ($session as $prop)
        var_dump($prop);

    Session::destroy();

Counting properties
-------------------

	use Phoda\Session\Session;

    require 'Session.php';

    Session::start();

    $session = new Session();
    $session->name = 'My name';
    $session->emails = array('email1@example.com', 'email2@example.com');
    $session->user = new stdClass();

    echo count($session);

    Session::destroy();

Regenerating session_id
--------------------------

	use Phoda\Session\Session;

    require 'Session.php';

    Session::start();

    $session = new Session();
    $session->name = 'My name';
    $session->emails = array('email1@example.com', 'email2@example.com');
    $session->user = new stdClass();

    Session::regenerateId();

    Session::destroy();

License Information
===================

Copyright (c) 2011, Thiago Rigo.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.

* Neither the name of Thiago Rigo nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


text:
define(['./kindOf'], function (kindOf) {

    var _win = this;

    /**
     * Convert array-like object into array
     */
    function toArray(val){
	var ret = [],
	    kind = kindOf(val),
	    n;

	if (val != null) {
	    if ( val.length == null || kind === 'String' || kind === 'Function' || kind === 'RegExp' || val === _win ) {
		//string, regexp, function have .length but user probably just want
		//to wrap value into an array..
		ret[ret.length] = val;
	    } else {
		//window returns true on isObject in IE7 and may have length
		//property. `typeof NodeList` returns `function` on Safari so
		//we can't use it (#58)
		n = val.length;
		while (n--) {
		    ret[n] = val[n];
		}
	    }
	}
	return ret;
    }
    return toArray;
});


text:
package com.xapo.utils.url;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Utility class for building http query strings.
 */
public class QueryString {

    private StringBuilder query = new StringBuilder();

    /**
     * Add a new query parameter.
     *
     * @param name query parameter's name.
     * @param value query parameter's value.
     */
    public void add(String name, String value) {
        if (query.length() != 0)
            query.append("&");

        encode(name, value);
    }

    /**
     * Return the query string representation of this class.
     *
     * @return the encoded query string.
     */
    public String getQuery() {
        return query.toString();
    }

    public String toString() {
        return getQuery();
    }

    private void encode(String name, String value) {
        try {
            query.append(URLEncoder.encode(name, "UTF-8"));
            query.append("=");
            query.append(URLEncoder.encode(value, "UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            throw new RuntimeException("Broken VM does not support UTF-8");
        }
    }
}


text:
(function() {
    'use strict';
    angular
        .module('app')
        .factory('todoStorage', TodoStorage)
        .controller('TodoCtrl', TodoCtrl);

        TodoStorage.$inject = ['ngStore'];
        function TodoStorage(ngStore) {
            return ngStore.model('todo');
        }

        TodoCtrl.$inject = ['$scope', '$location', '$filter', 'todoStorage'];
        function TodoCtrl($scope, $location, $filter, todoStorage) {
            var vm = $scope;
            var todos = vm.todos = todoStorage.findAll();

            vm.newTodo = '';
            vm.remainingCount = $filter('filter')(todos, {completed: false}).length;

            vm.location = $location;

            vm.$watch('location.path()', function (path) {
                vm.statusFilter = { '/app/todo/active': {completed: false}, '/app/todo/completed': {completed: true} }[path];
            });

            vm.$watch('remainingCount == 0', function (val) {
                vm.allChecked = val;
            });

            vm.addTodo = addTodo;
            vm.editTodo = editTodo;
            vm.doneEditing = doneEditing;
            vm.revertEditing = revertEditing;
            vm.removeTodo = removeTodo;
            vm.todoCompleted = todoCompleted;
            vm.clearCompletedTodos = clearCompletedTodos;
            vm.markAll = markAll;

            function addTodo() {
                var newTodo = vm.newTodo.trim();
                if (newTodo.length === 0) {
                    return;
                }

                var item = {
                    id: todoStorage.nextId(),
                    title: newTodo,
                    completed: false
                };
                todos.push( todoStorage.create(item) );

                vm.newTodo = '';
                vm.remainingCount++;
            };

            function editTodo(todo) {
                todo.editedTodo = true;
                // Clone the original todo to restore it on demand.
                vm.originalTodo = angular.extend({}, todo);
            };

            function doneEditing(todo) {
                todo.editedTodo = false;
                todo.title = todo.title.trim();

                if (!todo.title) {
                    vm.removeTodo(todo);
                }

                todoStorage.update(todo);
            };

            function revertEditing(todo) {
                todos[todos.indexOf(todo)] = vm.originalTodo;
                vm.doneEditing(vm.originalTodo);
            };

            function removeTodo(todo) {
                vm.remainingCount -= todo.completed ? 0 : 1;
                todos.splice(todos.indexOf(todo), 1);
                todoStorage.destroy(todo);
            };

            function todoCompleted(todo) {
                vm.remainingCount += todo.completed ? -1 : 1;
                todoStorage.update(todo);
            };

            function clearCompletedTodos() {
                todos.filter(function (todo) {
                    if(todo.completed){
                        todos.splice(todos.indexOf(todo), 1);
                        todoStorage.destroy(todo);
                    }
                });
            };

            function markAll(completed) {
                todos.forEach(function (todo) {
                    todo.completed = completed;
                    todoStorage.update(todo);
                });
                vm.remainingCount = !completed ? todos.length : 0;
            };
        }
})();


text:
using Amazon.DynamoDBv2;
using AwsTools;
using GalleryBackend.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Threading.Tasks;
using Amazon.DynamoDBv2.Model;

namespace GalleryBackend
{
    public class GalleryUserAccess
    {
        private IAmazonDynamoDB Client { get; }
        private IDynamoDbClient<GalleryUser> AwsToolsClient { get; }
        private ILogging Logging { get; }
        private ILogging AccessLogging { get; }

        public GalleryUserAccess(IAmazonDynamoDB client, ILogging logging, IDynamoDbClient<GalleryUser> awsToolsClient, ILogging accessLogging)
        {
            Client = client;
            Logging = logging;
            AwsToolsClient = awsToolsClient;
            AccessLogging = accessLogging;
        }

        public GalleryUser GetUserAndUpdateSaltIfNecessary(string usernamePasswordHash)
        {
            Dictionary<string, AttributeValue> userHashIndexKey = Conversion<GalleryUser>.ConvertToDynamoDb(new GalleryUser {Hash = usernamePasswordHash});
            var user = AwsToolsClient.Get(GalleryUser.USER_HASH_INDEX, userHashIndexKey).Result;

            if (user == null)
            {
                return null;
            }

            string newSaltDate = DateTime.UtcNow.Date.ToString("yyyy-MM-dd");
            if (!(user.TokenSaltDate ?? string.Empty).Equals(newSaltDate))
            {
                JObject log = new JObject
                {
                    {"saltDateChanged", "salt date was " + user.TokenSaltDate + " salt date is now " + newSaltDate}
                };

                var newSalt = Authentication.GetSalt();
                log.Add("saltChanged", "salt was " + user.TokenSalt + " salt is now " + newSalt);
                user.TokenSalt = newSalt;
                user.TokenSaltDate = newSaltDate;

                Task.WaitAll(AwsToolsClient.Insert(user));
                log.Add("updatedGalleryUser", JsonConvert.SerializeObject(user));

                AccessLogging.Log(log.ToString());
            }

            return user;
        }

    }
}


text:
package stexfires.io.markdown.list;

import org.jetbrains.annotations.Nullable;
import stexfires.io.ReadableWritableRecordFileSpec;
import stexfires.record.ValueRecord;
import stexfires.util.CharsetCoding;
import stexfires.util.LineSeparator;

import java.io.BufferedWriter;
import java.io.OutputStream;
import java.util.Objects;

/**
 * @author Mathias Kalb
 * @since 0.1
 */
public final class MarkdownListFileSpec extends ReadableWritableRecordFileSpec<ValueRecord, ValueRecord> {

    public enum BulletPoint {
        NUMBER, STAR, DASH
    }

    public static final String BULLET_POINT_NUMBER = ".";
    public static final String BULLET_POINT_STAR = "*";
    public static final String BULLET_POINT_DASH = "-";

    public static final String FILL_CHARACTER = " ";
    public static final long START_NUMBER = 1L;

    // DEFAULT - write
    public static final BulletPoint DEFAULT_BULLET_POINT = BulletPoint.STAR;
    public static final boolean DEFAULT_SKIP_NULL_VALUE = false;

    // FIELD - write
    private final BulletPoint bulletPoint;
    private final boolean skipNullValue;

    public MarkdownListFileSpec(CharsetCoding charsetCoding,
                                LineSeparator lineSeparator,
                                @Nullable String textBefore,
                                @Nullable String textAfter,
                                BulletPoint bulletPoint,
                                boolean skipNullValue) {
        super(charsetCoding, lineSeparator, textBefore, textAfter);
        Objects.requireNonNull(bulletPoint);

        // write
        this.bulletPoint = bulletPoint;
        this.skipNullValue = skipNullValue;
    }

    public static MarkdownListFileSpec write(CharsetCoding charsetCoding,
                                             LineSeparator lineSeparator) {
        return new MarkdownListFileSpec(charsetCoding,
                lineSeparator,
                null,
                null,
                DEFAULT_BULLET_POINT,
                DEFAULT_SKIP_NULL_VALUE);
    }

    public static MarkdownListFileSpec write(CharsetCoding charsetCoding,
                                             LineSeparator lineSeparator,
                                             @Nullable String textBefore,
                                             @Nullable String textAfter,
                                             BulletPoint bulletPoint,
                                             boolean skipNullValue) {
        return new MarkdownListFileSpec(charsetCoding,
                lineSeparator,
                textBefore,
                textAfter,
                bulletPoint,
                skipNullValue);
    }

    @Override
    public MarkdownListConsumer consumer(OutputStream outputStream) {
        return new MarkdownListConsumer(charsetCoding().newBufferedWriter(outputStream), this);
    }

    @Override
    public MarkdownListConsumer consumer(BufferedWriter bufferedWriter) {
        return new MarkdownListConsumer(bufferedWriter, this);
    }

    public BulletPoint bulletPoint() {
        return bulletPoint;
    }

    public boolean skipNullValue() {
        return skipNullValue;
    }

}


text:
/**
 * Root Reducer
 */
import { combineReducers } from 'redux';

// Import Reducers
import app from './modules/App/AppReducer';
import auth from './modules/Auth/AuthReducer';
import users from './modules/Users/UsersReducer';
import records from './modules/Records/RecordsReducer';
import posts from './modules/Post/PostReducer';
import intl from './modules/Intl/IntlReducer';

// Combine all reducers into one root reducer
export default combineReducers({
  app,
  auth,
  users,
  records,
  posts,
  intl,
});


text:
require 'test_helper'

class ClientTitleTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
from datetime import datetime
from structlog import get_logger
from app.submitter.convert_payload_0_0_1 import convert_answers_to_payload_0_0_1
from app.submitter.convert_payload_0_0_2 import convert_answers_to_payload_0_0_2

logger = get_logger()

class DataVersionError(Exception):
    def __init__(self, version):
        super().__init__()
        self.version = version

    def __str__(self):
        return 'Data version {} not supported'.format(self.version)

def convert_answers(metadata, collection_metadata, schema, answer_store, routing_path, flushed=False):
    """
    Create the JSON answer format for down stream processing
    :param metadata: metadata for the questionnaire
    :param collection_metadata: Any metadata about the collection of the questionnaire
    :param schema: QuestionnaireSchema class with populated schema json
    :param answer_store: the users answers
    :param routing_path: the path followed by the user when answering the questionnaire
    :param flushed: True when system submits the users answers, False when user submits there own answers
    :return: a JSON object in the following format:
      {
        'tx_id': '0f534ffc-9442-414c-b39f-a756b4adc6cb',
        'type' : 'uk.gov.ons.edc.eq:surveyresponse',
        'version' : '0.0.1',
        'origin' : 'uk.gov.ons.edc.eq',
        'survey_id': '021',
        'flushed': true|false
        'collection':{
          'exercise_sid': 'hfjdskf',
          'instrument_id': 'yui789',
          'period': '2016-02-01'
        },
        'started_at': '2016-03-06T15:28:05Z',
        'submitted_at': '2016-03-07T15:28:05Z',
        'metadata': {
          'user_id': '789473423',
          'ru_ref': '432423423423'
        },
        'data': {}
      }
    """
    survey_id = schema.json['survey_id']
    submitted_at = datetime.utcnow()
    payload = {
        'tx_id': metadata['tx_id'],
        'type': 'uk.gov.ons.edc.eq:surveyresponse',
        'version': schema.json['data_version'],
        'origin': 'uk.gov.ons.edc.eq',
        'survey_id': survey_id,
        'flushed': flushed,
        'submitted_at': submitted_at.isoformat(),
        'collection': _build_collection(metadata),
        'metadata': _build_metadata(metadata),
        'case_id': metadata['case_id'],
    }
    if collection_metadata.get('started_at'):
        payload['started_at'] = collection_metadata['started_at']
    if metadata.get('case_id'):
        payload['case_id'] = metadata['case_id']
    if metadata.get('case_ref'):
        payload['case_ref'] = metadata['case_ref']

    if schema.json['data_version'] == '0.0.2':
        payload['data'] = convert_answers_to_payload_0_0_2(answer_store, schema, routing_path)
    elif schema.json['data_version'] == '0.0.1':
        payload['data'] = convert_answers_to_payload_0_0_1(answer_store, schema, routing_path)
    else:
        raise DataVersionError(schema.json['data_version'])

    logger.info('converted answer ready for submission')
    return payload

def _build_collection(metadata):
    return {
        'exercise_sid': metadata['collection_exercise_sid'],
        'instrument_id': metadata['form_type'],
        'period': metadata['period_id'],
    }

def _build_metadata(metadata):
    downstream_metadata = {
        'user_id': metadata['user_id'],
        'ru_ref': metadata['ru_ref'],
    }

    if metadata.get('ref_p_start_date'):
        downstream_metadata['ref_period_start_date'] = metadata['ref_p_start_date']
    if metadata.get('ref_p_end_date'):
        downstream_metadata['ref_period_end_date'] = metadata['ref_p_end_date']

    return downstream_metadata

def convert_feedback(message, name, email, url, metadata, survey_id):
    """
    Create the JSON answer format for down stream processing
    :param metadata: metadata for the questionnaire
    :param feedback_json: the feedback json
    :param survey_id: the string representing the survey id
    :return: a JSON object in the following format:
      {
        'tx_id': '0f534ffc-9442-414c-b39f-a756b4adc6cb',
        'type' : 'uk.gov.ons.edc.eq:feedback',
        'version' : '0.0.1',
        'origin' : 'uk.gov.ons.edc.eq',
        'survey_id': '021',
        'collection':{
          'exercise_sid': 'hfjdskf',
          'instrument_id': 'yui789',
          'period': '201602'
        },
        'submitted_at': '2016-03-07T15:28:05Z',
        'metadata': {
          'user_id': '789473423',
          'ru_ref': '432423423423'
        },
        'data': {}
      }
    """
    submitted_at = datetime.utcnow()
    payload = {
        'tx_id': metadata['tx_id'],
        'type': 'uk.gov.ons.edc.eq:feedback',
        'version': '0.0.1',
        'origin': 'uk.gov.ons.edc.eq',
        'survey_id': survey_id,
        'submitted_at': submitted_at.isoformat(),
        'collection': _build_collection(metadata),
        'metadata': _build_metadata(metadata),
    }

    payload['data'] = {
        'message': message,
        'name': name,
        'email': email,
        'url': url,
    }

    return payload


text:
using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

using Xamarin.Forms.Platform.Android;
//using Refractored.Xam.Forms.Vibrate.Droid;
using Refractored.Xam.TTS;
using ImageCircle.Forms.Plugin.Droid;

namespace TestAppForms.Droid
{
  [Activity(Label = "Plugins for Xamarin", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
  public class MainActivity : AndroidActivity
  {
    protected override void OnCreate(Bundle bundle)
    {
      base.OnCreate(bundle);

      Xamarin.Forms.Forms.Init(this, bundle);
      //Vibrate.Init();
      CrossTextToSpeech.Current.Init();
      ImageCircleRenderer.Init();
      SetPage(App.GetMainPage());
    }
  }
}


text:
- rush v0.5.0
    - add flag `--eta` to show ETA progress bar. Thanks to @howeyc. [#39](https://github.com/shenwei356/rush/pull/39)
- rush v0.4.3
    - add shortcut `-I` for `--immediate-output`
- rush v0.4.2
    - fix bug of escaping symbols. [#28](https://github.com/shenwei356/rush/issues/28)
- rush v0.4.1
    - appending finished cmds to `--succ-cmd-file` now
    - fix variable replacement for complex commands. [#25](https://github.com/shenwei356/rush/issues/25)
- rush v0.4.0
    - new flags:
        - `--cleanup-time` allow child processes to clean up between stop / kill signals
        - `--immediate-output` print output immediately and interleaved, to aid debugging
        - `--no-kill-exes strings` exe names to exclude from kill signal, example: mspdbsrv.exe; or use all for all exes (default none)
        - `--no-stop-exes strings` exe names to exclude from stop signal, example: mspdbsrv.exe; or use all for all exes (default none)
    - removed flags:
        - `--kill-on-ctrl-c ` kill child processes on ctrl-c (default true)
    - try to fix for issue [#17](https://github.com/shenwei356/rush/issues/17): rush -e does not kill jobs
- rush v0.3.0
    - Added `--propagate-exit-status` command line arg, default true.
    Propagates child process exit status to rush exit status, so rush fails if a child fails
    - Added `--print-retry-output` command line arg, default true.
    Prints child output from retries, so users can see what caused retries
    - Added `--kill-on-ctrl-c` command line arg, default true
    Toggles child process kill or not
    - **For windows if `--kill-on-ctrl-c`, kill whole child process tree, so we don't orphan child processes**
    - **Modified logic to print child output even if commands failed, so users can see what failed**
- rush v0.2.0
    - support escaping special symbols like "$#&`" by flag `-q/--escape`.
- rush v0.1.9
    - fix colorful output in Windows
    - new replacement string `{@regex}`. e.g.,
- rush v0.1.8
    - Supporting **Preset variable (macro)**, e.g., `rush -v p={^suffix} 'echo {p}_new_suffix'`,
    where `{p}` is replaced with `{^suffix}`.
    This can make the long list of commands clearer (See [example 17](https://github.com/shenwei356/rush#examples))
- rush v0.1.7
    - Adding short flag (-T) for flag --trim, and adding return character for trimming (now: " \t\r\n") with better support for Windows platform.
- rush v0.1.6
    - ignoring input only containing newline character ("\n")
    - value of flag -D/--record-delimiter can be empty
- rush v0.1.5
    - fix continue (-c): immediately saving ignored commands when successful commands file is not empty (usually when running command with flag -c for 3+th times)
- rush v0.1.4
    - fix: remove duplicated commands in file of successful commands (-C/--succ-cmd-file)
- rush v0.1.3
    - fix bug of closing closed channel when using flag -e
- rush v0.1.2
    - fix job id for multiple input file
    - make sure message "stop on first error(s)" be printed
    - better windows support
    - better solution to avoid closing closed channel (cancel)
    - doc: add section: special cases
- rush v0.1.1
    - safer replacement string: return original replacement string if it is
        - unsupported
        - undefined variable by flag `-v`. It's a common mistake, leaving it be blank was wrong and some times dangerous. e.g.
- rush v0.1.0
    - fix indexing function for record delimiter, support multi-characters record delimiter (`-D`) now.
    - support continue for multi-line commands
    - immediately flush after a job successfully done
    - add flag alias `-C` for `--succ-cmd-file`
- rush v0.0.9
    - fix replacement strings: {.} and {:} only take effect on basename
- rush v0.0.8
    - add replacement string {^suffix} for removing suffix. For example:
- rush v0.0.7
    - fix help message of flag -D
    - add flag: `-J/--records-join-seq`, record separator for joining multi-records (default is "\n")
- rush v0.0.6
    - Avoid mixed line from multiple processes without loss of performance, e.g. the first half of a line is from one process and the last half of the line is from another process. similar with parallel --line-buffer
- rush v0.0.5
    - support safe interrupt by Ctrl + C
    - support continue jobs
    - fix some bugs
    - fix tests for lots of stdout
- rush v0.0.4
    - implement retry interval
    - do not send empty data
    - update docs
- rush v0.0.3
    - fix timeout and other bugs
    - update docs
- rush v0.0.2
    - doc improvement
- rush v0.0.1
    - first release