<commit_before>function Window3(title){

	var win = Ti.UI.createWindow({
		title: title
	});

	// base view
	var view = Ti.UI.createView({
		backgroundImage: '/images/bg_sample.png'
	});

	// top view
	var view_top = Ti.UI.createView({
		height: '35%',
		width: 'auto',
		fill: false,
		top: 0
	});

	var view_top_back = Ti.UI.createView({
		//backgroundColor: '#dcdcdc',
		opacity: 0,
		height: '90%',
		width: '80%',
		fill: false,
	});

	var icon_image = Ti.UI.createImageView({
		image: '/images/icon_umbrella.png',
		width: 110
	});

	// bottom view
	var view_bottom = Ti.UI.createView({
		height: '65%',
		width: 'auto',
	  	fill: false,
		bottom: 0
	});

	var view_bottom_back = Ti.UI.createView({
	 	backgroundColor: '#dcdcdc',
	 	opacity: 0.5
	});

	var view_list = Ti.UI.createView({
		height: '90%',
		width: '80%',
		fill: false,
		// このなかに、リストビューを埋め込む
		// それぞれのユーザ情報を取得して表示
	});

	var users = [
					{text:'user1', per: '50%'},
					{text:'user2', per: '20%'},
					{text:'user3', per: '70%'},
					{text:'user4', per: '50%'},
					{text:'user5', per: '20%'},
					{text:'user6', per: '60%'},
					{text:'user7', per: '10%'}
				];//仮のデータです
	var data = [];

	for (var i=0;i<users.length;i++) {
    	var user = users[i];
    	var row = Ti.UI.createTableViewRow({
    		height: 80
    	});
    	var nameLabel = Ti.UI.createLabel({
    		font: { fontSize:30 },
    		color: '#000',
    		top: 0
    	});
    	var perLabel = Ti.UI.createLabel({
    		font: { fontSize:25 },
	    	color: '#000',
    		bottom: 0
    	});
    	nameLabel.text = user.text;
    	perLabel.text = user.per;
    	row.add(nameLabel);
    	row.add(perLabel);
    	data.push(row);
	}

	var user_list = Ti.UI.createTableView({
		opacity: 0.5,
		data: data
	});

	user_list.addEventListener('click', function(e){
		var Prof = require('ui/common/profile');
		var prof = new Prof('user');
		//Ti.UI.currentTab.open(prof,{animated:true});
		prof.open();
	});
	view_list.add(view_bottom_back);
	view_list.add(user_list);

	view_top.add(view_top_back);
	view_top.add(icon_image);
	view_bottom.add(view_list);

	view.add(view_top);
	view.add(view_bottom);

	win.add(view);

	return win;
}

module.exports = Window3;<commit_msg>Set Size user_list<commit_after>function Window3(title){

	var win = Ti.UI.createWindow({
		title: title
	});

	// base view
	var view = Ti.UI.createView({
		backgroundImage: '/images/bg_sample.png'
	});

	// top view
	var view_top = Ti.UI.createView({
		height: '35%',
		width: 'auto',
		fill: false,
		top: 0
	});

	var view_top_back = Ti.UI.createView({
		//backgroundColor: '#dcdcdc',
		opacity: 0,
		height: '90%',
		width: '80%',
		fill: false
	});

	var icon_image = Ti.UI.createImageView({
		image: '/images/icon_umbrella.png',
		width: 110
	});

	// bottom view
	var view_bottom = Ti.UI.createView({
		height: '65%',
		width: 'auto',
	  	fill: false,
		bottom: 0
	});

	var view_bottom_back = Ti.UI.createView({
	 	backgroundColor: '#dcdcdc',
	 	opacity: 0.5
	});

	var view_list = Ti.UI.createView({
		height: '90%',
		width: '80%',
		fill: false,
		// このなかに、リストビューを埋め込む
		// それぞれのユーザ情報を取得して表示
	});

	var users = [
					{text:'user1', per: '50%'},
					{text:'user2', per: '20%'},
					{text:'user3', per: '70%'},
					{text:'user4', per: '50%'},
					{text:'user5', per: '20%'},
					{text:'user6', per: '60%'},
					{text:'user7', per: '10%'}
				];//仮のデータです
	var data = [];

	for (var i=0;i<users.length;i++) {
    	var user = users[i];
    	var row = Ti.UI.createTableViewRow({
    		height: 50
    	});
    	var nameLabel = Ti.UI.createLabel({
    		font: { fontSize:20 },
    		color: '#000',
    		top: 5
    	});
    	var perLabel = Ti.UI.createLabel({
    		font: { fontSize:15 },
	    	color: '#000',
    		bottom: 5
    	});
    	nameLabel.text = user.text;
    	perLabel.text = user.per;
    	row.add(nameLabel);
    	row.add(perLabel);
    	data.push(row);
	}

	var user_list = Ti.UI.createTableView({
		opacity: 0.5,
		data: data
	});

	user_list.addEventListener('click', function(e){
		var Prof = require('ui/common/profile');
		var prof = new Prof('user');
		//Ti.UI.currentTab.open(prof,{animated:true});
		prof.open();
	});
	view_list.add(view_bottom_back);
	view_list.add(user_list);

	view_top.add(view_top_back);
	view_top.add(icon_image);
	view_bottom.add(view_list);

	view.add(view_top);
	view.add(view_bottom);

	win.add(view);

	return win;
}

module.exports = Window3;<|endoftext|>


<commit_before>import React, { Component } from 'react'

export default class Contact extends Component {
  render() {
    return (

        <form method="post">

Contact us

            Sign in if you would like a response.

            <input className="form-control" type="text" name="name" placeholder="Your name" />

            <textarea className="form-control" rows="14" name="message" placeholder="Your message"></textarea>

            <button className="btn btn-primary" type="submit">Send to Happy Spirit Games</button>

        </form>

    )
  }
}
<commit_msg>Added WIP disclaimer to contact page.<commit_after>import React, { Component } from 'react'

export default class Contact extends Component {
  render() {
    return (

Thanks for playing StoryTime.

This feedback form is not hooked up yet.

You can send email if you like.

        <form method="post">

Contact us

            Sign in if you would like a response.

            <input className="form-control" type="text" name="name" placeholder="Your name" />

            <textarea className="form-control" rows="14" name="message" placeholder="Your message"></textarea>

            <button className="btn btn-primary" type="submit">Send to Happy Spirit Games</button>

        </form>

    )
  }
}
<|endoftext|>


<commit_before>// Copyright (c) 2012, Joyent, Inc. All rights reserved.
var bunyan = require('bunyan');
var fs = require('fs');
var optimist = require('optimist');
var Shard = require('./lib/shard');

///--- Mainline

var ARGV = optimist.options({
        'd': {
                alias: 'debug',
                describe: 'debug level'
        },
        'f': {
                alias: 'file',
                demand: true,
                describe: 'configuration file'
        }
}).argv;

var CFG;

var LOG = bunyan.createLogger({
        level: ARGV.d ? (ARGV.d > 1 ? 'trace' : 'debug') : 'info',
        name: 'pg-sitter',
        serializers: {
                err: bunyan.stdSerializers.err
        },
        src: ARGV.d ? true : false
});

function readConfig() {
        if (!CFG) {
                CFG = JSON.parse(fs.readFileSync(ARGV.f, 'utf8'));
                LOG.info({config: CFG, file: ARGV.f}, 'Configuration loaded');
        }

        return (CFG);
}

var cfg = readConfig();
cfg.log = LOG;
cfg.zkCfg.log = LOG;
cfg.postgresManCfg.log = LOG;
cfg.postgresManCfg.backupClientCfg.log = LOG;
cfg.postgresManCfg.snapShotterCfg.log = LOG;
cfg.heartbeaterCfg.log = LOG;

var startTimeout = cfg.startTimeout || 7000;

// wait some time before starting shard so that previous emphemeral
// znodes are purgd from ZK

LOG.info('starting shard in %s seconds', startTimeout / 1000);
setTimeout(function() {
        new Shard(cfg);
}, startTimeout);

process.on('uncaughtException', function (err) {
        LOG.fatal({err: err}, 'uncaughtException (exiting error code 1)');
        process.exit(1);
});
<commit_msg>MANTA-168 s/postgresmanCfg/postgresMgrCfg<commit_after>// Copyright (c) 2012, Joyent, Inc. All rights reserved.
var bunyan = require('bunyan');
var fs = require('fs');
var optimist = require('optimist');
var Shard = require('./lib/shard');

///--- Mainline

var ARGV = optimist.options({
        'd': {
                alias: 'debug',
                describe: 'debug level'
        },
        'f': {
                alias: 'file',
                demand: true,
                describe: 'configuration file'
        }
}).argv;

var CFG;

var LOG = bunyan.createLogger({
        level: ARGV.d ? (ARGV.d > 1 ? 'trace' : 'debug') : 'info',
        name: 'pg-sitter',
        serializers: {
                err: bunyan.stdSerializers.err
        },
        src: ARGV.d ? true : false
});

function readConfig() {
        if (!CFG) {
                CFG = JSON.parse(fs.readFileSync(ARGV.f, 'utf8'));
                LOG.info({config: CFG, file: ARGV.f}, 'Configuration loaded');
        }

        return (CFG);
}

var cfg = readConfig();
cfg.log = LOG;
cfg.zkCfg.log = LOG;
cfg.postgresMgrCfg.log = LOG;
cfg.postgresMgrCfg.backupClientCfg.log = LOG;
cfg.postgresMgrCfg.snapShotterCfg.log = LOG;
cfg.heartbeaterCfg.log = LOG;

var startTimeout = cfg.startTimeout || 7000;

// wait some time before starting shard so that previous emphemeral
// znodes are purgd from ZK

LOG.info('starting shard in %s seconds', startTimeout / 1000);
setTimeout(function() {
        new Shard(cfg);
}, startTimeout);

process.on('uncaughtException', function (err) {
        LOG.fatal({err: err}, 'uncaughtException (exiting error code 1)');
        process.exit(1);
});
<|endoftext|>


<commit_before>Template.login.events({
  "submit .login form": function(event) {
    event.preventDefault();

    var username = $(".login form input").val();
    console.log("logging in " + userName + "...");
    Meteor.insecureUserLogin(username);
  }
});
<commit_msg>variable name misspelling in login<commit_after>Template.login.events({
  "submit .login form": function(event) {
    event.preventDefault();

    var username = $(".login form input").val();
    console.log("logging in " + username + "...");
    Meteor.insecureUserLogin(username);
  }
});
<|endoftext|>


<commit_before>const {JSDOM} = require('jsdom');
const {window, document} = new JSDOM('');
global.window = window;
global.document = document;
const jQuery = require('jquery');

const glob = require('glob');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const copy = require('copy');

const prettier = require('prettier');

function phpArrayToJSON(string) {
    if (!string) {
        return {};
    }
    const replaced = string
        .replace(/^, /, '')
        .replace(/'/g, '"')
        .replace(/array\(("\w+"(, )?)+\)/, '[$1]')
        .replace(/array/g, '')
        .replace(/\(/g, '{')
        .replace(/\)/g, '}')
        .replace(/\=\>/g, ':');
    try {
        return JSON.parse(replaced);
    } catch (e) {
        console.error(replaced, e);
        throw new Error(' The hackish conversion of PHP syntax to JSON failed. check ./exmaple-generator.js');
    }
}
function forEachExampleToGenerate(cb, final) {
    glob('src/*/*.php', {}, (er, files) => {

        files.forEach(file => {
            const contents = fs.readFileSync(file, {encoding: 'utf8'});
            const section = path.dirname(file).replace('src/', '');
            const exampleRegEx = /example\('.+?',\s?'(.+?)',\s?'(.+?)'(.+)?\)\s?\?>/g;

            let matches;
            while ((matches = exampleRegEx.exec(contents))) {
                const [_, example, type, options] = matches;

                if (type === 'generated') {
                    cb(section, example, phpArrayToJSON(options));
                }
            }
        });
        final();
    });
}
module.exports = cb => {
    require('ts-node').register();
    const {vanillaToReact} = require('./src/example-runner/vanilla-to-react.ts');
    const {vanillaToAngular} = require('./src/example-runner/vanilla-to-angular.ts');

    const appModuleTS = fs.readFileSync(path.join('./src', 'example-runner', 'angular-generated-app-module.ts'));

    let count = 0;
    forEachExampleToGenerate((section, example, options) => {
        count ++;
        const document = glob.sync(path.join('./src', section, example, 'index.html'))[0];
        const script = glob.sync(path.join('./src', section, example, '*.js'))[0];
        const stylesGlob = path.join('./src', section, example, '*.css');
        const sources = [fs.readFileSync(script, {encoding: 'utf8'}), fs.readFileSync(document, {encoding: 'utf8'})];
        const _gen = path.join('./src', section, example, '_gen');

        let source, indexJSX, appComponentTS;

        let inlineStyles;
        const style = jQuery(`<div>${sources[1]}</div>`).find('style');

        if (style.length) {
            inlineStyles = prettier.format(style.text(), { parser: 'css' });
        }

        try {
            source = vanillaToReact(sources, options);
            indexJSX = prettier.format(source, {printWidth: 120});
        } catch (e) {
            console.error(`Failed at ./src/${section}/${example}`, e);
            // console.error(source);
            //throw new Error('Failed generating the react version');
        }

        try {
            source = vanillaToAngular(sources, options);
            appComponentTS = prettier.format(source, {printWidth: 120, parser: 'typescript'});
        } catch (e) {
            console.error(`Failed at ./src/${section}/${example}`, e);
            // console.error(source);
            // throw new Error('Failed generating the angular version');
        }

        const reactPath = path.join(_gen, 'react');
        mkdirp(reactPath, () => {
            fs.writeFileSync(path.join(reactPath, 'index.jsx'), indexJSX);
            if (inlineStyles) {
                fs.writeFileSync(path.join(reactPath, 'example.css'), inlineStyles);
            }
            copy(stylesGlob, reactPath, () => {});
        });

        const angularPath = path.join(_gen, 'angular');
        mkdirp(path.join(angularPath, 'app'), () => {
            fs.writeFileSync(path.join(angularPath, 'app', 'app.component.ts'), appComponentTS);
            fs.writeFileSync(path.join(angularPath, 'app', 'app.module.ts'), appModuleTS);
            if (inlineStyles) {
                fs.writeFileSync(path.join(angularPath, 'example.css'), inlineStyles);
            }
            copy(stylesGlob, angularPath, () => {});
        });

        const vanillaPath = path.join(_gen, 'vanilla');

        mkdirp(vanillaPath, () => {
            const srcFilesGlob = path.join('./src', section, example, '*.{html,js,css}');
            copy(srcFilesGlob, vanillaPath, () => {});
        });
    }, () => {
        console.log(`// ${count} examples generated`);
        cb();
    });

};
<commit_msg>Use styles.css so that it is below main.js<commit_after>const {JSDOM} = require('jsdom');
const {window, document} = new JSDOM('');
global.window = window;
global.document = document;
const jQuery = require('jquery');

const glob = require('glob');
const fs = require('fs');
const path = require('path');
const mkdirp = require('mkdirp');
const copy = require('copy');

const prettier = require('prettier');

function phpArrayToJSON(string) {
    if (!string) {
        return {};
    }
    const replaced = string
        .replace(/^, /, '')
        .replace(/'/g, '"')
        .replace(/array\(("\w+"(, )?)+\)/, '[$1]')
        .replace(/array/g, '')
        .replace(/\(/g, '{')
        .replace(/\)/g, '}')
        .replace(/\=\>/g, ':');
    try {
        return JSON.parse(replaced);
    } catch (e) {
        console.error(replaced, e);
        throw new Error(' The hackish conversion of PHP syntax to JSON failed. check ./exmaple-generator.js');
    }
}
function forEachExampleToGenerate(cb, final) {
    glob('src/*/*.php', {}, (er, files) => {

        files.forEach(file => {
            const contents = fs.readFileSync(file, {encoding: 'utf8'});
            const section = path.dirname(file).replace('src/', '');
            const exampleRegEx = /example\('.+?',\s?'(.+?)',\s?'(.+?)'(.+)?\)\s?\?>/g;

            let matches;
            while ((matches = exampleRegEx.exec(contents))) {
                const [_, example, type, options] = matches;

                if (type === 'generated') {
                    cb(section, example, phpArrayToJSON(options));
                }
            }
        });
        final();
    });
}
module.exports = cb => {
    require('ts-node').register();
    const {vanillaToReact} = require('./src/example-runner/vanilla-to-react.ts');
    const {vanillaToAngular} = require('./src/example-runner/vanilla-to-angular.ts');

    const appModuleTS = fs.readFileSync(path.join('./src', 'example-runner', 'angular-generated-app-module.ts'));

    let count = 0;
    forEachExampleToGenerate((section, example, options) => {
        count ++;
        const document = glob.sync(path.join('./src', section, example, 'index.html'))[0];
        const script = glob.sync(path.join('./src', section, example, '*.js'))[0];
        const stylesGlob = path.join('./src', section, example, '*.css');
        const sources = [fs.readFileSync(script, {encoding: 'utf8'}), fs.readFileSync(document, {encoding: 'utf8'})];
        const _gen = path.join('./src', section, example, '_gen');

        let source, indexJSX, appComponentTS;

        let inlineStyles;
        const style = jQuery(`<div>${sources[1]}</div>`).find('style');

        if (style.length) {
            inlineStyles = prettier.format(style.text(), { parser: 'css' });
        }

        try {
            source = vanillaToReact(sources, options);
            indexJSX = prettier.format(source, {printWidth: 120});
        } catch (e) {
            console.error(`Failed at ./src/${section}/${example}`, e);
            // console.error(source);
            //throw new Error('Failed generating the react version');
        }

        try {
            source = vanillaToAngular(sources, options);
            appComponentTS = prettier.format(source, {printWidth: 120, parser: 'typescript'});
        } catch (e) {
            console.error(`Failed at ./src/${section}/${example}`, e);
            // console.error(source);
            // throw new Error('Failed generating the angular version');
        }

        const reactPath = path.join(_gen, 'react');
        mkdirp(reactPath, () => {
            fs.writeFileSync(path.join(reactPath, 'index.jsx'), indexJSX);
            if (inlineStyles) {
                fs.writeFileSync(path.join(reactPath, 'styles.css'), inlineStyles);
            }
            copy(stylesGlob, reactPath, () => {});
        });

        const angularPath = path.join(_gen, 'angular');
        mkdirp(path.join(angularPath, 'app'), () => {
            fs.writeFileSync(path.join(angularPath, 'app', 'app.component.ts'), appComponentTS);
            fs.writeFileSync(path.join(angularPath, 'app', 'app.module.ts'), appModuleTS);
            if (inlineStyles) {
                fs.writeFileSync(path.join(angularPath, 'styles.css'), inlineStyles);
            }
            copy(stylesGlob, angularPath, () => {});
        });

        const vanillaPath = path.join(_gen, 'vanilla');

        mkdirp(vanillaPath, () => {
            const srcFilesGlob = path.join('./src', section, example, '*.{html,js,css}');
            copy(srcFilesGlob, vanillaPath, () => {});
        });
    }, () => {
        console.log(`// ${count} examples generated`);
        cb();
    });

};
<|endoftext|>


<commit_before>/**
 * zest.js support for ender.js
 *
 * zest.js
 * Copyright (c) 2011-2012, Christopher Jeffrey
 * https://github.com/chjj/zest
 *
 * ender.js
 * copyright @ded and @fat
 * https://github.com/ender-js
 */

// I try not to change the expected functionality here, however,
// these functions seem like they should belong in a dom library,
// not as part of the selector engine binding.

;(function() {
  var window = this
    , document = this.document
    , zest = this.zest.noConflict();

  $._select = function(str, context) {
    context = context || document;
    if (/^\s*</.test(str)) {
      context = context.nodeType === 9
              ? context : context.ownerDocument;

      var out = []
        , el = context.createElement('div');

      el.innerHTML = str;
      el = el.firstChild;
      while (el) {
        if (el.nodeType === 1) out.push(el);
        el = el.nextSibling;
      }

      return out;
    }
    return zest(str, context);
  };

  $.ender(function() {
    var has = function(obj, el) {
      var i = obj.length;
      while (i--) {
        if (obj[i] === el) return true;
      }
    };
    return {
      find: function(sel) {
        var res = []
          , i = this.length
          , r
          , k;

        while (i--) {
          r = zest(sel, this[i]);
          k = r.length;
          while (k--) {
            if (!has(res, r[k])) res.push(r[k]);
          }
        }
        return $(res);
      }
    };
  }());
}).call(this);
<commit_msg>refactor ender binding<commit_after>/**
 * zest.js support for ender.js
 *
 * zest.js
 * Copyright (c) 2011-2012, Christopher Jeffrey
 * https://github.com/chjj/zest
 *
 * ender.js
 * copyright @ded and @fat
 * https://github.com/ender-js
 */

;(function() {
  var zest = this.zest.noConflict()
    , document = this.document;

  $._select = function(str, context) {
    context = context || document;

    if (/^\s*</.test(str)) {
      context = context.nodeType !== 9
        ? context.ownerDocument
        : context;

      var el = context.createElement('div')
        , out = [];

      el.innerHTML = str;
      el = el.firstChild;
      while (el) {
        if (el.nodeType === 1) out.push(el);
        el = el.nextSibling;
      }

      return out;
    }

    return zest(str, context);
  };

  var has = function(obj, el) {
    var i = obj.length;
    while (i--) {
      if (obj[i] === el) return true;
    }
  };

  $.ender({
    find: function(sel) {
      var res = []
        , i = this.length
        , r
        , k;

      while (i--) {
        r = zest(sel, this[i]);
        k = r.length;
        while (k--) {
          if (!has(res, r[k])) res.push(r[k]);
        }
      }

      return $(res);
    }
  });
}).call(this);
<|endoftext|>


<commit_before>// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Genetic Algorithm, Evolving Shakespeare

// Demonstration of using a genetic algorithm to perform a search

// setup()
//  # Step 1: The Population
//    # Create an empty population (an array or ArrayList)
//    # Fill it with DNA encoded objects (pick random values to start)

// draw()
//  # Step 1: Selection
//    # Create an empty mating pool (an empty ArrayList)
//    # For every member of the population, evaluate its fitness based on some criteria / function,
//      and add it to the mating pool in a manner consistant with its fitness, i.e. the more fit it
//      is the more times it appears in the mating pool, in order to be more likely picked for reproduction.

//  # Step 2: Reproduction Create a new empty population
//    # Fill the new population by executing the following steps:
//       1. Pick two "parent" objects from the mating pool.
//       2. Crossover -- create a "child" object by mating these two parents.
//       3. Mutation -- mutate the child's DNA based on a given probability.
//       4. Add the child object to the new population.
//    # Replace the old population with the new population
//
//   # Rinse and repeat

let calc = false;
let log = false;
let font;
let popmax;
let mutationRate;
let population;

var bestPhrase;
var allPhrases;
var stats;

let wantCovered;

function setup() {
	//frameRate(1);
	bestPhrase = createP("");
	bestPhrase.position(10,10);
	bestPhrase.class("best");

	allPhrases = createP("");
	allPhrases.position(600,10);
	allPhrases.class("all");

	stats = createP("");
	stats.position(10,200);
	stats.class("stats");

	noLoop();
}

function draw() {
	if (calc) {
		// Refresh the timer
		population.updateTime();

		//Create next generation
		population.generate();
		// Calculate fitness
		population.calcFitness();

		population.evaluate();

		// If we found the target phrase, stop
		if (population.isFinished()) {
			//println(millis()/1000.0);
			noLoop();
		}

		if (log)
			displayInfo();
	}
}

function displayInfo() {
	// Display current status of population
	var answer = population.getBest();

	bestPhrase.html("Best phrase:
\t" + answer +
					"
Record:
\t" + population.everRecord +
					"
Select:
\t" + population.everRecordSelect +
					"
Covereds:
\t" + population.everRecordCovereds + " OF " + wantCovered);

	var statstext = "Stats
total generations:     " + population.getGenerations() + "
";
	statstext +=    "average fitness:       " + nf(population.getAverageFitness()) + "
";
	statstext +=    "total population:      " + popmax + "
";
	statstext +=    "mutation rate:         " + floor(mutationRate * 100) + "%";

	stats.html(statstext);

	//allPhrases.html("All phrases:
" + population.allPhrases())
}

<commit_msg>Removido o canvas do p5js<commit_after>// The Nature of Code
// Daniel Shiffman
// http://natureofcode.com

// Genetic Algorithm, Evolving Shakespeare

// Demonstration of using a genetic algorithm to perform a search

// setup()
//  # Step 1: The Population
//    # Create an empty population (an array or ArrayList)
//    # Fill it with DNA encoded objects (pick random values to start)

// draw()
//  # Step 1: Selection
//    # Create an empty mating pool (an empty ArrayList)
//    # For every member of the population, evaluate its fitness based on some criteria / function,
//      and add it to the mating pool in a manner consistant with its fitness, i.e. the more fit it
//      is the more times it appears in the mating pool, in order to be more likely picked for reproduction.

//  # Step 2: Reproduction Create a new empty population
//    # Fill the new population by executing the following steps:
//       1. Pick two "parent" objects from the mating pool.
//       2. Crossover -- create a "child" object by mating these two parents.
//       3. Mutation -- mutate the child's DNA based on a given probability.
//       4. Add the child object to the new population.
//    # Replace the old population with the new population
//
//   # Rinse and repeat

let calc = false;
let log = false;
let font;
let popmax;
let mutationRate;
let population;

var bestPhrase;
var allPhrases;
var stats;

let wantCovered;

function setup() {
	//frameRate(1);
	bestPhrase = createP("");
	bestPhrase.position(10,10);
	bestPhrase.class("best");

	allPhrases = createP("");
	allPhrases.position(600,10);
	allPhrases.class("all");

	stats = createP("");
	stats.position(10,200);
	stats.class("stats");

	noCanvas();
	noLoop();
}

function draw() {
	if (calc) {
		// Refresh the timer
		population.updateTime();

		//Create next generation
		population.generate();
		// Calculate fitness
		population.calcFitness();

		population.evaluate();

		// If we found the target phrase, stop
		if (population.isFinished()) {
			//println(millis()/1000.0);
			noLoop();
		}

		if (log)
			displayInfo();
	}
}

function displayInfo() {
	// Display current status of population
	var answer = population.getBest();

	bestPhrase.html("Best phrase:
\t" + answer +
					"
Record:
\t" + population.everRecord +
					"
Select:
\t" + population.everRecordSelect +
					"
Covereds:
\t" + population.everRecordCovereds + " OF " + wantCovered);

	var statstext = "Stats
total generations:     " + population.getGenerations() + "
";
	statstext +=    "average fitness:       " + nf(population.getAverageFitness()) + "
";
	statstext +=    "total population:      " + popmax + "
";
	statstext +=    "mutation rate:         " + floor(mutationRate * 100) + "%";

	stats.html(statstext);

	//allPhrases.html("All phrases:
" + population.allPhrases())
}

<|endoftext|>


<commit_before>iOlog("isOnline started");

opt = [{"name": "Online",          "value" : "online",  "color": "green"},
       {"name": "Away",            "value" : "absent",  "color": "orange"},
       {"name": "Offline (ghost)", "value" : "offline", "color": "grey"}];
isOwnAccount = false;
stop = 0;
try {localuser = document.documentElement.innerHTML.substring(document.documentElement.innerHTML.search("username")+10,document.documentElement.innerHTML.search("username")+100).match(/\'(.*)\'/).pop();main();}
catch(err) {document.onreadystatechange = function(){localuser = document.getElementsByClassName("profile-name")[0].innerHTML;main();}}

if(location.href.toLowerCase().startsWith("https://scratch.mit.edu/search/") && /\?q=the(%20|\+)best\1extension/i) location.href = "https://scratch.mit.edu/users/isOnlineV2/"; // easter egg!

function main() {

    /* One line account key validation */ if (window.location.href.startsWith("https://scratch.mit.edu/isonline-extension/verify")){stop = "On verification page";document.documentElement.innerHTML = "
Validating...
";test = new XMLHttpRequest();test.open("GET", ' https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + location.hash.substring(1) + "/test/", true);test.send();test.onreadystatechange = function() {if (test.readyState === 4 && test.status === 200  && test.responseText == '{"valid":true}') {localStorage.setItem("iOuser", localuser);localStorage.setItem("iOkey", location.hash.substring(1));document.documentElement.innerHTML = "
Successfully validated your Scratch account. isOnline is now working.
You can close this tab.
";}else {document.documentElement.innerHTML = "
An error occurred. Please contact @chooper100 if you come from isOnline account validation.
";}}}

    if (localStorage.getItem("iOuser") === null) {
        stop = "User didn't validate any account.";
        isError();
        didntValidate();}

    if (localuser != localStorage.getItem("iOuser") && localStorage.getItem("iOuser") !== null) {
        stop = "User validated another account.";
        isError();
        unvalidatedAcc();}

    if(stop!==0){console.error("isOnline error: "+stop);return;}

    url = window.location.href;
    user = window.location.href.substring(30,100).substring(0, window.location.href.substring(30,100).indexOf('/'));
    key = localStorage.getItem("iOkey");
    iOlog("Profile: " + user);
    iOlog("Local username: " + localuser);

    if (time()-localStorage.getItem("iOlastOn") > 10 && localstatus() == "online") {setOnline();}

    /* Manage statuses */ update(); setInterval(update, 3000);

    if (url.substring(24,29) == 'users' && (url.match(/\//g) || []).length == 5) {
        iOlog("Detected user is in a profile");
        /* Add status box next to location */ document.getElementsByClassName("location")[0].innerHTML += ' | Loading status...';
        if (localuser.toUpperCase() == user.toUpperCase()) {iOlog("Detected user is their own profile");isOwn();} else {status();}}

} // main function

function update() {
    if (stop !== 0) {return;}
    if (localstatus() == "online") {
        updateStatus("");
        if (time()-localStorage.getItem("iOlastOn") > 240 && time()-localStorage.getItem("iOlastAbs") > 120) {
            absentrequest = new XMLHttpRequest();
            absentrequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/absent', true);
            absentrequest.send();
            localStorage.setItem("iOlastAbs", time());
            iOlog("Sent away request");}}
    if (localstatus() == "absent"){
        updateStatus("orange");
        if (time()-localStorage.getItem("iOlastAbs") > 120) {
            absentrequest = new XMLHttpRequest();
            absentrequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/absent', true);
            absentrequest.send();
            localStorage.setItem("iOlastAbs", time());
            iOlog("Sent away request");}}
    if (localstatus() == "offline") {
        updateStatus("grey");}
}

function status() {

    if(stop!==0){return;}

    iOlog("Started status scan");

    getstatus = new XMLHttpRequest();getstatus.open("GET", ' https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + "/get/" + user, true);getstatus.send();

    getstatus.onreadystatechange = function() {
        if (getstatus.readyState === 4 && getstatus.status === 200) {

            response  = getstatus.responseText;
            timestamp = JSON.parse(response).timestamp;
            var status = JSON.parse(response).status;

            if (status == "online") {
                if (time() - timestamp < 300) {isOnline();} else{isOffline();}}

            if (status == "absent") {
                if (time() - timestamp < 180) {isAbsent();} else{isOffline();}}

        } // if 200

        if (getstatus.readyState === 4 && getstatus.status === 404) {noiO();}

        if (getstatus.readyState === 4 && getstatus.status === 403) {
            isError();
            var status = JSON.parse(getstatus.responseText).status;
            if (status=="incorrect key") {stop = "Key was changed";keyWasChanged();}
            if (status=="bot") {stop = "User is a bot";isBot();}
        }

        if (getstatus.readyState === 4 && getstatus.status === 500) {isError();}

    } // on ready

}

function isOwn(){
    isOwnAccount = true;
    document.getElementById("iOstatus").innerHTML = '';
    document.getElementById("iOstatus").innerHTML += " <select id='ioselect' style='font-weight: bold; color: " + opt.find(k => localstatus() === k.value).color + "; width: 120px; padding:0px; font-size:13px; height:23px; margin:0px;' onchange='this.style.color=opt[this.selectedIndex].color;localStorage.setItem(\"iOstatus\", opt[this.selectedIndex].value);document.getElementById(\"iostatusimage\").src=\"https://scratchtools.tk/isonline/assets/\" +opt[this.selectedIndex].value+\".svg\"'>" + opt.map(k => "<option style='background-color: " + k.color + "; color: white;' " + (k.value === localstatus() ? "selected" : "") +">" + k.name + "</option>") + "</select>";
    iOcrown();
}

function isOnline() {
    iOlog("Detected that the user is online");
    document.getElementById("iOstatus").innerHTML = ' Online';iOcrown();}

function isOffline() {
    iOlog("Detected that the user is offline");
    document.getElementById("iOstatus").innerHTML = ' Offline';iOcrown();}

function isAbsent() {
    iOlog("Detected that the user is away");
    document.getElementById("iOstatus").innerHTML = ' Away';iOcrown();}

function noiO() {
    iOlog("Detected that the user didn't install isOnline");
    document.getElementById("iOstatus").innerHTML = 'Not iO user';}

function isError() { try{
    try { document.getElementById("iOstatus").innerHTML = 'Error';} catch(err){
        document.getElementsByClassName("location")[0].innerHTML = document.getElementsByClassName("location")[0].innerHTML + ' | Error';}}catch(err){}}

function didntValidate() { try{
    document.getElementById("alert-view").innerHTML="
×Whoops! Looks like you didn't validate your account on isOnline. isOnline won't work until you validate your account. It takes around 20 seconds.
";}catch(err){}}

function unvalidatedAcc() { if(window.location.href.includes("users")){
    document.getElementById("alert-view").innerHTML="
×Whoops! Looks like you didn\'t validate isOnline on the account you are using now, so it's not working. If needed, login to " + localStorage.getItem("iOuser") + ", or unregister it by registering " + localuser + " instead.
";}}

function keyWasChanged() {
    console.error("isOnline error: Key was changed");
    document.getElementById("alert-view").innerHTML="
×Whoops! isOnline isn't working. This may ocurr if you installed iO on another computer. iO can only work at one computer at the same time. You can use isOnline on this computer by re-validating.
";}

function isBot() {
    console.error("isOnline error: User has been marked as a bot");
    document.getElementById("alert-view").innerHTML="
×Whoops! It looks like you've been marked as a bot by the isOnline server. isOnline isn't working. Please contact chooper100 to unblock your account.
";}

function iOlog(x) {
    if (localStorage.getItem("isonline_logs") === undefined) {return;}
    console.log("isOnline log @ " + new Date().toLocaleTimeString() + ": " + x);}

function setOnline() {
    iOlog("Sent online request");
    onlinerequest = new XMLHttpRequest();
    onlinerequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/online', true);
    onlinerequest.send();
    localStorage.setItem("iOlastOn", time());}

function updateStatus(color) {
    try {document.getElementsByClassName("user-name dropdown-toggle")[0].style.backgroundColor=color;}
    catch(err) {document.getElementsByClassName("link right account-nav")[0].style.backgroundColor=color;}
    color = color === "" ? "green" : color;
    if(isOwnAccount && document.getElementById("ioselect").style.color !== color){
        document.getElementById("ioselect").selectedIndex = opt.findIndex(k => k.color === color);
        document.getElementById("ioselect").style.color = color;
        document.getElementById("iostatusimage").src = "https://scratchtools.tk/isonline/assets/" + opt.find(k => k.color === color).value + ".svg";}
}

function localstatus(){if(localStorage.getItem("iOstatus")!==null){return localStorage.getItem("iOstatus");}else{return "online";}}

function time() {return Math.floor(Date.now() / 1000);}

function iOcrown() {try{if(document.getElementsByClassName("overview")[0].innerHTML.toLowerCase().includes("isonline.tk") || document.getElementsByClassName("overview")[1].innerHTML.toLowerCase().includes("isonline.tk")) {document.getElementsByClassName("header-text")[0].innerHTML = document.getElementsByClassName("header-text")[0].innerHTML.replace('
', ' 👑
').replace('
', '
');document.getElementsByClassName("box-head")[0].style.backgroundColor="black";document.getElementsByClassName("header-text")[0].style.backgroundColor="black";document.getElementsByClassName("group")[0].style.color="white";document.getElementsByClassName("profile-details")[0].style.color="white";document.getElementById("iOstatustext").style.color="white";}}catch(err) {if (document.getElementById("user-details").innerHTML.toLowerCase().includes("isonline.tk")) {document.getElementsByClassName("header-text")[0].innerHTML = document.getElementsByClassName("header-text")[0].innerHTML.replace('
', ' 👑
').replace('
', '
');document.getElementsByClassName("box-head")[0].style.backgroundColor="black";document.getElementsByClassName("header-text")[0].style.backgroundColor="black";document.getElementsByClassName("group")[0].style.color="white";document.getElementsByClassName("profile-details")[0].style.color="white";document.getElementById("iOstatustext").style.color="white";}}}

var openregister = false;
if (!localStorage['iO.was.installed']) {openregister = true; localStorage['iO.was.installed'] = '1'; localStorage['iO.version'] = "1.1";}
if (openregister) window.location="https://scratchtools.tk/isonline/register";

var openupdate = false;
if (localStorage['iO.version'] !== "1.1" && localStorage['iO.was.installed']!==null) {openupdate = true; localStorage['iO.version'] = "1.1";}
if (openupdate) window.location="https://isonlineupdate.blogspot.com";
<commit_msg>Fix if statement syntax | Easter egg<commit_after>iOlog("isOnline started");

opt = [{"name": "Online",          "value" : "online",  "color": "green"},
       {"name": "Away",            "value" : "absent",  "color": "orange"},
       {"name": "Offline (ghost)", "value" : "offline", "color": "grey"}];
isOwnAccount = false;
stop = 0;
try {localuser = document.documentElement.innerHTML.substring(document.documentElement.innerHTML.search("username")+10,document.documentElement.innerHTML.search("username")+100).match(/\'(.*)\'/).pop();main();}
catch(err) {document.onreadystatechange = function(){localuser = document.getElementsByClassName("profile-name")[0].innerHTML;main();}}

if(location.href.toLowerCase().startsWith("https://scratch.mit.edu/search/") && /\?q=the(%20|\+)best\1extension/i).test(location.search)) location.href = "https://scratch.mit.edu/users/isOnlineV2/"; // easter egg!

function main() {

    /* One line account key validation */ if (window.location.href.startsWith("https://scratch.mit.edu/isonline-extension/verify")){stop = "On verification page";document.documentElement.innerHTML = "
Validating...
";test = new XMLHttpRequest();test.open("GET", ' https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + location.hash.substring(1) + "/test/", true);test.send();test.onreadystatechange = function() {if (test.readyState === 4 && test.status === 200  && test.responseText == '{"valid":true}') {localStorage.setItem("iOuser", localuser);localStorage.setItem("iOkey", location.hash.substring(1));document.documentElement.innerHTML = "
Successfully validated your Scratch account. isOnline is now working.
You can close this tab.
";}else {document.documentElement.innerHTML = "
An error occurred. Please contact @chooper100 if you come from isOnline account validation.
";}}}

    if (localStorage.getItem("iOuser") === null) {
        stop = "User didn't validate any account.";
        isError();
        didntValidate();}

    if (localuser != localStorage.getItem("iOuser") && localStorage.getItem("iOuser") !== null) {
        stop = "User validated another account.";
        isError();
        unvalidatedAcc();}

    if(stop!==0){console.error("isOnline error: "+stop);return;}

    url = window.location.href;
    user = window.location.href.substring(30,100).substring(0, window.location.href.substring(30,100).indexOf('/'));
    key = localStorage.getItem("iOkey");
    iOlog("Profile: " + user);
    iOlog("Local username: " + localuser);

    if (time()-localStorage.getItem("iOlastOn") > 10 && localstatus() == "online") {setOnline();}

    /* Manage statuses */ update(); setInterval(update, 3000);

    if (url.substring(24,29) == 'users' && (url.match(/\//g) || []).length == 5) {
        iOlog("Detected user is in a profile");
        /* Add status box next to location */ document.getElementsByClassName("location")[0].innerHTML += ' | Loading status...';
        if (localuser.toUpperCase() == user.toUpperCase()) {iOlog("Detected user is their own profile");isOwn();} else {status();}}

} // main function

function update() {
    if (stop !== 0) {return;}
    if (localstatus() == "online") {
        updateStatus("");
        if (time()-localStorage.getItem("iOlastOn") > 240 && time()-localStorage.getItem("iOlastAbs") > 120) {
            absentrequest = new XMLHttpRequest();
            absentrequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/absent', true);
            absentrequest.send();
            localStorage.setItem("iOlastAbs", time());
            iOlog("Sent away request");}}
    if (localstatus() == "absent"){
        updateStatus("orange");
        if (time()-localStorage.getItem("iOlastAbs") > 120) {
            absentrequest = new XMLHttpRequest();
            absentrequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/absent', true);
            absentrequest.send();
            localStorage.setItem("iOlastAbs", time());
            iOlog("Sent away request");}}
    if (localstatus() == "offline") {
        updateStatus("grey");}
}

function status() {

    if(stop!==0){return;}

    iOlog("Started status scan");

    getstatus = new XMLHttpRequest();getstatus.open("GET", ' https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + "/get/" + user, true);getstatus.send();

    getstatus.onreadystatechange = function() {
        if (getstatus.readyState === 4 && getstatus.status === 200) {

            response  = getstatus.responseText;
            timestamp = JSON.parse(response).timestamp;
            var status = JSON.parse(response).status;

            if (status == "online") {
                if (time() - timestamp < 300) {isOnline();} else{isOffline();}}

            if (status == "absent") {
                if (time() - timestamp < 180) {isAbsent();} else{isOffline();}}

        } // if 200

        if (getstatus.readyState === 4 && getstatus.status === 404) {noiO();}

        if (getstatus.readyState === 4 && getstatus.status === 403) {
            isError();
            var status = JSON.parse(getstatus.responseText).status;
            if (status=="incorrect key") {stop = "Key was changed";keyWasChanged();}
            if (status=="bot") {stop = "User is a bot";isBot();}
        }

        if (getstatus.readyState === 4 && getstatus.status === 500) {isError();}

    } // on ready

}

function isOwn(){
    isOwnAccount = true;
    document.getElementById("iOstatus").innerHTML = '';
    document.getElementById("iOstatus").innerHTML += " <select id='ioselect' style='font-weight: bold; color: " + opt.find(k => localstatus() === k.value).color + "; width: 120px; padding:0px; font-size:13px; height:23px; margin:0px;' onchange='this.style.color=opt[this.selectedIndex].color;localStorage.setItem(\"iOstatus\", opt[this.selectedIndex].value);document.getElementById(\"iostatusimage\").src=\"https://scratchtools.tk/isonline/assets/\" +opt[this.selectedIndex].value+\".svg\"'>" + opt.map(k => "<option style='background-color: " + k.color + "; color: white;' " + (k.value === localstatus() ? "selected" : "") +">" + k.name + "</option>") + "</select>";
    iOcrown();
}

function isOnline() {
    iOlog("Detected that the user is online");
    document.getElementById("iOstatus").innerHTML = ' Online';iOcrown();}

function isOffline() {
    iOlog("Detected that the user is offline");
    document.getElementById("iOstatus").innerHTML = ' Offline';iOcrown();}

function isAbsent() {
    iOlog("Detected that the user is away");
    document.getElementById("iOstatus").innerHTML = ' Away';iOcrown();}

function noiO() {
    iOlog("Detected that the user didn't install isOnline");
    document.getElementById("iOstatus").innerHTML = 'Not iO user';}

function isError() { try{
    try { document.getElementById("iOstatus").innerHTML = 'Error';} catch(err){
        document.getElementsByClassName("location")[0].innerHTML = document.getElementsByClassName("location")[0].innerHTML + ' | Error';}}catch(err){}}

function didntValidate() { try{
    document.getElementById("alert-view").innerHTML="
×Whoops! Looks like you didn't validate your account on isOnline. isOnline won't work until you validate your account. It takes around 20 seconds.
";}catch(err){}}

function unvalidatedAcc() { if(window.location.href.includes("users")){
    document.getElementById("alert-view").innerHTML="
×Whoops! Looks like you didn\'t validate isOnline on the account you are using now, so it's not working. If needed, login to " + localStorage.getItem("iOuser") + ", or unregister it by registering " + localuser + " instead.
";}}

function keyWasChanged() {
    console.error("isOnline error: Key was changed");
    document.getElementById("alert-view").innerHTML="
×Whoops! isOnline isn't working. This may ocurr if you installed iO on another computer. iO can only work at one computer at the same time. You can use isOnline on this computer by re-validating.
";}

function isBot() {
    console.error("isOnline error: User has been marked as a bot");
    document.getElementById("alert-view").innerHTML="
×Whoops! It looks like you've been marked as a bot by the isOnline server. isOnline isn't working. Please contact chooper100 to unblock your account.
";}

function iOlog(x) {
    if (localStorage.getItem("isonline_logs") === undefined) {return;}
    console.log("isOnline log @ " + new Date().toLocaleTimeString() + ": " + x);}

function setOnline() {
    iOlog("Sent online request");
    onlinerequest = new XMLHttpRequest();
    onlinerequest.open("POST", 'https://scratchtools.tk/isonline/api/v1/' + localuser + '/' + key + '/set/online', true);
    onlinerequest.send();
    localStorage.setItem("iOlastOn", time());}

function updateStatus(color) {
    try {document.getElementsByClassName("user-name dropdown-toggle")[0].style.backgroundColor=color;}
    catch(err) {document.getElementsByClassName("link right account-nav")[0].style.backgroundColor=color;}
    color = color === "" ? "green" : color;
    if(isOwnAccount && document.getElementById("ioselect").style.color !== color){
        document.getElementById("ioselect").selectedIndex = opt.findIndex(k => k.color === color);
        document.getElementById("ioselect").style.color = color;
        document.getElementById("iostatusimage").src = "https://scratchtools.tk/isonline/assets/" + opt.find(k => k.color === color).value + ".svg";}
}

function localstatus(){if(localStorage.getItem("iOstatus")!==null){return localStorage.getItem("iOstatus");}else{return "online";}}

function time() {return Math.floor(Date.now() / 1000);}

function iOcrown() {try{if(document.getElementsByClassName("overview")[0].innerHTML.toLowerCase().includes("isonline.tk") || document.getElementsByClassName("overview")[1].innerHTML.toLowerCase().includes("isonline.tk")) {document.getElementsByClassName("header-text")[0].innerHTML = document.getElementsByClassName("header-text")[0].innerHTML.replace('
', ' 👑
').replace('
', '
');document.getElementsByClassName("box-head")[0].style.backgroundColor="black";document.getElementsByClassName("header-text")[0].style.backgroundColor="black";document.getElementsByClassName("group")[0].style.color="white";document.getElementsByClassName("profile-details")[0].style.color="white";document.getElementById("iOstatustext").style.color="white";}}catch(err) {if (document.getElementById("user-details").innerHTML.toLowerCase().includes("isonline.tk")) {document.getElementsByClassName("header-text")[0].innerHTML = document.getElementsByClassName("header-text")[0].innerHTML.replace('
', ' 👑
').replace('
', '
');document.getElementsByClassName("box-head")[0].style.backgroundColor="black";document.getElementsByClassName("header-text")[0].style.backgroundColor="black";document.getElementsByClassName("group")[0].style.color="white";document.getElementsByClassName("profile-details")[0].style.color="white";document.getElementById("iOstatustext").style.color="white";}}}

var openregister = false;
if (!localStorage['iO.was.installed']) {openregister = true; localStorage['iO.was.installed'] = '1'; localStorage['iO.version'] = "1.1";}
if (openregister) window.location="https://scratchtools.tk/isonline/register";

var openupdate = false;
if (localStorage['iO.version'] !== "1.1" && localStorage['iO.was.installed']!==null) {openupdate = true; localStorage['iO.version'] = "1.1";}
if (openupdate) window.location="https://isonlineupdate.blogspot.com";
<|endoftext|>


<commit_before>let gridSize = 32
let grid

function setup() {
  grid = makeGrid(gridSize, gridSize)
  createCanvas(512, 512)
  drawGrid(grid)
}

function makeGrid(x, y) {
  let g = new Array(x)
  for (var i = 0; i < g.length; i++) {
    g[i] = new Array(y)
  }

  return g
}

function drawGrid(grid, xoff = 0, yoff = 0) {
  if (xoff >= gridSize) {
    xoff = gridSize
  } else if (yoff >= gridSize) {
    yoff = gridSize
  }

  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      if (grid[i][j] === undefined) {
        fill(51)
        stroke(0)
      } else {
        noStroke()
        fill(grid[i][j])
      }
      x = map(i + xoff, 0, gridSize, 0, width)
      y = map(j + yoff, 0, gridSize, 0, height)
      rect(x, y, tileSize, tileSize)
    }
  }
}

class Cat {
  constructor() {
    console.log("Everything is under control")
  }

  makePaw() {
    // generate variables that describe the paw
    let length = parseInt(random(5, 14))
    let thickness = parseInt(random(1, 3))
    let pawHeight = parseInt(random(1, 2))

    // make grid that will contain paw infos
    let paw = makeGrid(thickness + 1, length)

    // fill the grid with paw
    for (var x = 0; x < paw.length; x++) {
      for (var y = 0; y < paw[x].length; y++) {
        if (x === 0 && y < paw[x].length - pawHeight) {
          continue
        }
        paw[x][y] = color(255)
      }
    }

    return paw
  }
}
<commit_msg>double grid resolution, update paw variables<commit_after>let gridSize = 64
let grid

function setup() {
  grid = makeGrid(gridSize, gridSize)
  createCanvas(512, 512)
  drawGrid(grid)

  let cat = new Cat()
  drawGrid(cat.makePaw())
}

function makeGrid(x, y) {
  let g = new Array(x)
  for (var i = 0; i < g.length; i++) {
    g[i] = new Array(y)
  }

  return g
}

function drawGrid(grid, xoff = 0, yoff = 0) {
  if (xoff >= gridSize) {
    xoff = gridSize
  } else if (yoff >= gridSize) {
    yoff = gridSize
  }

  tileSize = floor(width / gridSize)

  for (var i = 0; i < grid.length; i++) {
    for (var j = 0; j < grid[i].length; j++) {
      if (grid[i][j] === undefined) {
        fill(51)
        stroke(0)
      } else {
        noStroke()
        fill(grid[i][j])
      }
      x = map(i + xoff, 0, gridSize, 0, width)
      y = map(j + yoff, 0, gridSize, 0, height)
      rect(x, y, tileSize, tileSize)
    }
  }
}

class Cat {
  constructor() {
    console.log("Everything is under control")
  }

  makePaw() {
    // generate variables that describe the paw
    let length = parseInt(random(6, 24))
    let thickness = parseInt(random(2, 6))
    let pawHeight = parseInt(random(1, 4))

    // make grid that will contain paw infos
    let paw = makeGrid(thickness + 2, length)

    // fill the grid with paw
    for (var x = 0; x < paw.length; x++) {
      for (var y = 0; y < paw[x].length; y++) {
        if (x === 0 && y < paw[x].length - pawHeight) {
          continue
        }
        paw[x][y] = color(255)
      }
    }

    return paw
  }
}
<|endoftext|>


<commit_before>var input;
var output;

function setup() {
  noCanvas();

  input = select('#search');
  output = select('#date');
  var button = select('#submit');
  button.mousePressed(search);
}

function search() {
  var term = input.value();
  var url = 'https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=0&format=json' + '&titles=' + term;
  loadJSON(url, gotData, 'jsonp');
}

function gotData(data) {
  for (key in data.query.pages) {

    var birthdeath = (data.query.pages[key].revisions[0]["*"]);

    if (birthdeath.indexOf("|df=yes|") > 0) {
      var deathdateA = (birthdeath.split("{{Death date and age|df=yes|")[1].split("}}")[0].split("|"));
      createP(input.value() + ":" + deathdateA[3] + "-" + deathdateA[0]);

    }
    if ((birthdeath.indexOf("df=y}}") > 0) || (birthdeath.indexOf("mf=y") > 0)) {
      var deathdateB = (birthdeath.split("{{death date and age|")[1].split("}}")[0].split("|"));
      createP(input.value() + ":" + deathdateB[3] + "-" + deathdateB[0]);

    }
  }
}
<commit_msg>update sketch<commit_after>var input;
var output;

function setup() {
  noCanvas();

  input = select('#search');
  output = select('#date');
  var button = select('#submit');
  button.mousePressed(search);
}

function search() {
  var term = input.value();
  //var url = 'https://en.wikipedia.org/w/api.php?action=query&prop=revisions&rvprop=content&rvsection=0&format=json' + '&titles=' + term;
  var url = 'https://www.wikidata.org/w/api.php?action=wbgetentities&sites=enwiki&languages=en&format=json' + '&titles=' + term;
  loadJSON(url, gotData, 'jsonp');
}

function gotData(data) {
  entity = data.entities
  birthdate = entity.claims.P569[0].mainsnak.datavalue.value.time
  deathdate = entity.claims.P570[0].mainsnak.datavalue.value.time
  createP(input.value() + ":" + birthdate + "-" + deathdate);

}
<|endoftext|>


<commit_before>d3.timeSlider = function module() {
    "use strict";

    var FROM = 'from', UNTIL = 'until', MIN = 60, HOUR = 60 * MIN, DAY = 24 * HOUR;

    var CONF = {
        axis: {
            height: 30
        }
    };

    // Public variables
    var axis = true,
        value,
        handles = {from: undefined, until: undefined},
        active = FROM,

        /**
         * The scale of the slider, it transforms the domain [0, 1] (a percentage of the slider) to the range of time
         * Is really a polylinear scale, so the domain is not just [0, 1] but a serie of intermediate numbers, as well as the range
         */
        scale;

    // Private variables
    var dispatch = d3.dispatch("slide", "slideend"),
        pctFormat = d3.format(".2%"),
        tickFormat = d3.format(".0"),
        width,
        axisScale,
        axisSvg,
        axisContainer;

    function timeSlider(selection)
    {
        selection.each(function() {

            var timeSteps = _([
                0,
                10 * MIN,
                30 * MIN,
                1 * HOUR,
                3 * HOUR,
                12 * HOUR,
                1 * DAY,
                7 * DAY,
                30 * DAY]
            ).sortBy().value();

            // working on a simplified range for now
            var range = [timeSteps[0], timeSteps[1]];

            // working on a simplyfied scale for now
            // var domain = _.map(range, function (val, ind, range) { return ind ? ind/(range.length - 1) : 0; } )
            var domain = [0, 1];

                scale = d3.scale.linear()
                    .range( range )
                    .domain( domain );

            console.debug("domain", domain);
            console.debug("range", range);

            // Start value
            value = value || {from: range[1], until: range[0]};
            console.debug("initial value", value);

            // DIV container
            var container = d3.select(this).classed("time-slider", true);

            // cache the slider width
            width = parseInt(container.style("width"), 10);

            var drag = d3.behavior.drag();
            drag.on('dragend', function () {
                dispatch.slideend(d3.event, value);
            });

            // from slider handle
            handles[FROM] = container.append("a")
                .attr("class", "time-slider-handle handle-from")
                .attr("xlink:href", "#")
                .on("click", stopPropagation)
                .call(drag);

            // until slider handle
            handles[UNTIL] = container.append("a")
                .attr("class", "time-slider-handle handle-until")
                .attr("xlink:href", "#")
                .on("click", stopPropagation)
                .call(drag);

            // interval marker
            var slice = d3.select(this).append('div').classed("time-slider-range", true);

            // position the left handler
            handles[FROM].style("right", pctFormat(scale.invert(value[ FROM ])));

            // position the right handler
            handles[UNTIL].style("right", pctFormat(scale.invert(value[ UNTIL ])));

            // position the range rectangle
            slice.style({
                left: (100 - parseFloat(pctFormat(scale.invert(value[ FROM ])))) + "%",
                right: pctFormat(scale(value[ UNTIL ]))
            });

            createAxis(container);

            drag.on("drag", onDrag);

            container.on("click", onClick);

            // Adjust all things after a window resize
            d3.select(window).on('resize', function () {
                width = parseInt(container.style("width"), 10);
                axisScale.range([width, 0]);
                d3.rebind(timeSlider, dispatch, "on");
                axisSvg.attr("width", width);
                axisContainer.transition().call(axis);
            });

            // ----

            function createAxis(container)
            {
                axis = d3.svg.axis()
                    .ticks(Math.round(width / 100))
                    .tickFormat(tickFormat)
                    .orient("bottom");

                var axis_range = [width, 0];
                // var axis_range = _.map(scale.domain(), function (val, ind, domain) { return ind ? (width / domain.length) * ind : 0; });

                axisScale = scale.copy()
                    .domain([range[0], range[range.length - 1]])
                    .range(axis_range);
                axis.scale(axisScale);

                // Create SVG axis container
                axisSvg = container.append("svg")
                    .classed("time-slider-axis time-slider-axis-" + axis.orient(), true)
                    .on("click", stopPropagation);

                axisContainer = axisSvg.append("g");

                // axis

                axisSvg.attr({
                    width: width,
                    height: CONF.axis.height
                });

                if (axis.orient() === "top")
                {
                    axisSvg.style("top", "-" + CONF.axis.height + "px");
                } else { // bottom
                }

                axisContainer.call(axis);
            }

            function interpolator (oldVal, newVal)
            {
                return function () {
                    return d3.interpolate(oldVal, newVal);
                };
            }

            function val2left (val) {
                return (1 - val2pct(val)) * width;
            }

            function val2right (val) {
                return val2pct(val) * 100 / width;
            }

            function val2pct (val) {
                return scale.invert(val);
            }

            function pos2val (pos) {
                return scale((width - pos) / width);
            }

            // Move slider handle on click/drag
            function moveHandle(pos)
            {
                var newValue = pos2val(pos),
                    currentValue = value[active];
                console.debug('clicked position: %f/%2f, value: %f', pos, (width - pos) / width, newValue);

                if (currentValue !== newValue) {
                    var oldPos = pctFormat(val2pct(currentValue)),
                        newPos = pctFormat(val2pct(newValue));

                    value[active] = newValue;
                    console.log("New value {from:%s, until:%s} %s changed", value.from, value.until, active);
                    console.log("New pos %s", newPos);
                    dispatch.slide(d3.event, value );

                    if ( value[ FROM ] <= value[ UNTIL ] ) { console.warn('problem', value); return; }

                    if ( UNTIL === active )
                    {
                        slice.transition().styleTween("right", interpolator(oldPos, newPos))
                    }

                    if (FROM === active)
                    {
                        var newRight = 100 - parseFloat(newPos) + "%";
                        var oldRight = 100 - parseFloat(oldPos) + "%";

                        slice.transition().styleTween("left", interpolator(oldRight, newRight));
                    }

                    handles[active].transition().styleTween("right", interpolator(oldPos, newPos));
                }
            }

            function onClick()
            {
                var pos = d3.event.offsetX || d3.event.layerX,
                    leftPos = val2left(value[FROM]);

                active = UNTIL;

                if (pos < leftPos){
                    active = FROM;
                }

                console.debug("Decided active=%s. pos=%f %f->leftPos=%f", active, pos, value[FROM], leftPos);
                moveHandle(pos);
            }

            function onDrag()
            {
                var target = d3.select(d3.event.sourceEvent.target);

                if ( target.classed('handle-from') ) {
                    active = FROM;

                } else if ( target.classed('handle-until') ) {
                    active = UNTIL;

                }

                moveHandle(Math.max(0, Math.min(width, d3.event.x)));
            }

            function stopPropagation()
            {
                d3.event.stopPropagation();
            }

        });

    }

    timeSlider.value = function(set) {
        if (!arguments.length) return value;
        value = set;
        return timeSlider;
    };

    d3.rebind(timeSlider, dispatch, "on");

    return timeSlider;

};
<commit_msg>onClick moving the closest handler<commit_after>d3.timeSlider = function module() {
    "use strict";

    var FROM = 'from', UNTIL = 'until', MIN = 60, HOUR = 60 * MIN, DAY = 24 * HOUR;

    var CONF = {
        axis: {
            height: 30
        }
    };

    // Public variables
    var axis = true,
        value,
        handles = {from: undefined, until: undefined},
        active = FROM,

        /**
         * The scale of the slider, it transforms the domain [0, 1] (a percentage of the slider) to the range of time
         * Is really a polylinear scale, so the domain is not just [0, 1] but a serie of intermediate numbers, as well as the range
         */
        scale;

    // Private variables
    var container,
        dispatch = d3.dispatch("slide", "slideend"),
        pctFormat = d3.format(".2%"),
        tickFormat = d3.format(".0"),
        width,
        axisScale,
        axisSvg,
        axisContainer;

    function timeSlider(selection)
    {
        selection.each(function() {

            var timeSteps = _([
                0,
                10 * MIN,
                30 * MIN,
                1 * HOUR,
                3 * HOUR,
                12 * HOUR,
                1 * DAY,
                7 * DAY,
                30 * DAY]
            ).sortBy().value();

            // working on a simplified range for now
            var range = [timeSteps[0], timeSteps[1]];

            // working on a simplyfied scale for now
            // var domain = _.map(range, function (val, ind, range) { return ind ? ind/(range.length - 1) : 0; } )
            var domain = [0, 1];

                scale = d3.scale.linear()
                    .range( range )
                    .domain( domain );

            console.debug("domain", domain);
            console.debug("range", range);

            // Start value
            value = value || {from: range[1], until: range[0]};
            console.debug("initial value", value);

            // DIV container
            container = d3.select(this).classed("time-slider", true);

            // cache the slider width
            width = parseInt(container.style("width"), 10);

            var drag = d3.behavior.drag();
            drag.on('dragend', function () {
                dispatch.slideend(d3.event, value);
            });

            // from slider handle
            handles[FROM] = container.append("a")
                .attr("class", "time-slider-handle handle-from")
                .attr("xlink:href", "#")
                .on("click", stopPropagation)
                .call(drag);

            // until slider handle
            handles[UNTIL] = container.append("a")
                .attr("class", "time-slider-handle handle-until")
                .attr("xlink:href", "#")
                .on("click", stopPropagation)
                .call(drag);

            // interval marker
            var slice = d3.select(this).append('div').classed("time-slider-range", true);

            // position the left handler
            handles[FROM].style("right", pctFormat(scale.invert(value[ FROM ])));

            // position the right handler
            handles[UNTIL].style("right", pctFormat(scale.invert(value[ UNTIL ])));

            // position the range rectangle
            slice.style({
                left: (100 - parseFloat(pctFormat(scale.invert(value[ FROM ])))) + "%",
                right: pctFormat(scale(value[ UNTIL ]))
            });

            createAxis(container);

            drag.on("drag", onDrag);

            container.on("click", onClick);

            // Adjust all things after a window resize
            d3.select(window).on('resize', function () {
                width = parseInt(container.style("width"), 10);
                axisScale.range([width, 0]);
                d3.rebind(timeSlider, dispatch, "on");
                axisSvg.attr("width", width);
                axisContainer.transition().call(axis);
            });

            // ----

            function createAxis(container)
            {
                axis = d3.svg.axis()
                    .ticks(Math.round(width / 100))
                    .tickFormat(tickFormat)
                    .orient("bottom");

                var axis_range = [width, 0];
                // var axis_range = _.map(scale.domain(), function (val, ind, domain) { return ind ? (width / domain.length) * ind : 0; });

                axisScale = scale.copy()
                    .domain([range[0], range[range.length - 1]])
                    .range(axis_range);
                axis.scale(axisScale);

                // Create SVG axis container
                axisSvg = container.append("svg")
                    .classed("time-slider-axis time-slider-axis-" + axis.orient(), true)
                    .on("click", stopPropagation);

                axisContainer = axisSvg.append("g");

                // axis

                axisSvg.attr({
                    width: width,
                    height: CONF.axis.height
                });

                if (axis.orient() === "top")
                {
                    axisSvg.style("top", "-" + CONF.axis.height + "px");
                } else { // bottom
                }

                axisContainer.call(axis);
            }

            function interpolator (oldVal, newVal)
            {
                return function () {
                    return d3.interpolate(oldVal, newVal);
                };
            }

            function val2left (val) {
                return (1 - val2pct(val)) * width;
            }

            function val2right (val) {
                return val2pct(val) * 100 / width;
            }

            function val2pct (val) {
                return scale.invert(val);
            }

            function pos2val (pos) {
                return scale((width - pos) / width);
            }

            // Move slider handle on click/drag
            function moveHandle(pos)
            {
                var newValue = pos2val(pos),
                    currentValue = value[active];
                console.debug('clicked position: %f/%2f, value: %f', pos, (width - pos) / width, newValue);

                if (currentValue !== newValue) {
                    var oldPos = pctFormat(val2pct(currentValue)),
                        newPos = pctFormat(val2pct(newValue));

                    value[active] = newValue;
                    console.log("New value {from:%s, until:%s} %s changed", value.from, value.until, active);
                    console.log("New pos %s", newPos);
                    dispatch.slide(d3.event, value );

                    if ( value[ FROM ] <= value[ UNTIL ] ) { console.warn('problem', value); return; }

                    if ( UNTIL === active )
                    {
                        slice.transition().styleTween("right", interpolator(oldPos, newPos))
                    }

                    if (FROM === active)
                    {
                        var newRight = 100 - parseFloat(newPos) + "%";
                        var oldRight = 100 - parseFloat(oldPos) + "%";

                        slice.transition().styleTween("left", interpolator(oldRight, newRight));
                    }

                    handles[active].transition().styleTween("right", interpolator(oldPos, newPos));
                }
            }

            function onClick()
            {
                var pos = d3.event.offsetX || d3.event.layerX,
                    currLpos = val2left(value[FROM]),
                    currRpos = val2left(value[UNTIL]);

                // moving the closest handler
                active = UNTIL;
                if (Math.abs(pos - currLpos) < Math.abs(pos - currRpos)){
                    active = FROM;
                }

                moveHandle(pos);
            }

            function onDrag()
            {
                var target = d3.select(d3.event.sourceEvent.target);

                if ( target.classed('handle-from') ) {
                    active = FROM;

                } else if ( target.classed('handle-until') ) {
                    active = UNTIL;

                }

                moveHandle(Math.max(0, Math.min(width, d3.event.x)));
            }

            function stopPropagation()
            {
                d3.event.stopPropagation();
            }

        });

    }

    timeSlider.value = function(set) {
        if (!arguments.length) return value;
        value = set;
        return timeSlider;
    };

    d3.rebind(timeSlider, dispatch, "on");

    return timeSlider;

};
<|endoftext|>