<commit_before>const push = require('push.js');

angular.module('opentok-meet').factory('Push', () => push);

angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push',
  function NotificationService($window, OTSession, Push) {
    let focused = true;

    $window.addEventListener('blur', () => {
      focused = false;
    });

    $window.addEventListener('focus', () => {
      focused = true;
    });

    const notifyOnConnectionCreated = () => {
      if (!OTSession.session) {
        OTSession.on('init', notifyOnConnectionCreated);
      } else {
        OTSession.session.on('connectionCreated', (event) => {
          if (!focused &&
              event.connection.connectionId !== OTSession.session.connection.connectionId) {
            Push.create('New Participant', {
              body: 'Someone joined your meeting',
              icon: '/icon.png',
              tag: 'new-participant',
              timeout: 5000,
              onClick() {
                $window.focus();
                this.close();
              },
            });
          }
        });
      }
    };
    return {
      init() {
        if (Push.Permission.has()) {
          notifyOnConnectionCreated();
        } else {
          try {
            Push.Permission.request(() => {
              notifyOnConnectionCreated();
            }, (err) => {
              console.warn(err);
            });
          } catch (err) {
            console.warn(err);
          }
        }
      },
    };
  },
]);
<commit_msg>Add extra condition to show "user joined" notification<commit_after>const push = require('push.js');

angular.module('opentok-meet').factory('Push', () => push);

angular.module('opentok-meet').factory('NotificationService', ['$window', 'OTSession', 'Push',
  function NotificationService($window, OTSession, Push) {
    let focused = true;

    $window.addEventListener('blur', () => {
      focused = false;
    });

    $window.addEventListener('focus', () => {
      focused = true;
    });

    const notifyOnConnectionCreated = () => {
      if (!OTSession.session) {
        OTSession.on('init', notifyOnConnectionCreated);
      } else {
        OTSession.session.on('connectionCreated', (event) => {
          const visible = $window.document.visibilityState === 'visible';
          if ((!focused || !visible) &&
              event.connection.connectionId !== OTSession.session.connection.connectionId) {
            Push.create('New Participant', {
              body: 'Someone joined your meeting',
              icon: '/icon.png',
              tag: 'new-participant',
              timeout: 5000,
              onClick() {
                $window.focus();
                this.close();
              },
            });
          }
        });
      }
    };
    return {
      init() {
        if (Push.Permission.has()) {
          notifyOnConnectionCreated();
        } else {
          try {
            Push.Permission.request(() => {
              notifyOnConnectionCreated();
            }, (err) => {
              console.warn(err);
            });
          } catch (err) {
            console.warn(err);
          }
        }
      },
    };
  },
]);
<|endoftext|>


<commit_before>const { mergeChildConfig } = require('../../../config');
const { extractAndUpdate } = require('./extract-update');

module.exports = {
  processRepo,
};

async function processRepo(config) {
  logger.debug('processRepo()');
  if (config.baseBranches && config.baseBranches.length) {
    logger.info({ baseBranches: config.baseBranches }, 'baseBranches');
    let res;
    let branches = [];
    let branchList = [];
    for (const baseBranch of config.baseBranches) {
      logger.debug(`baseBranch: ${baseBranch}`);
      const baseBranchConfig = mergeChildConfig(config, { baseBranch });
      baseBranchConfig.branchPrefix += `${baseBranch}-`;
      baseBranchConfig.hasBaseBranches = true;
      platform.setBaseBranch(baseBranch);
      const baseBranchRes = await extractAndUpdate(baseBranchConfig);
      ({ res } = baseBranchRes);
      branches = branches.concat(baseBranchRes.branches);
      branchList = branchList.concat(baseBranchRes.branchList);
    }
    return { res, branches, branchList };
  }
  logger.debug('No baseBranches');
  return extractAndUpdate(config);
}
<commit_msg>fix(baseBranches): apply special branch and PR naming only when multiple<commit_after>const { mergeChildConfig } = require('../../../config');
const { extractAndUpdate } = require('./extract-update');

module.exports = {
  processRepo,
};

async function processRepo(config) {
  logger.debug('processRepo()');
  if (config.baseBranches && config.baseBranches.length) {
    logger.info({ baseBranches: config.baseBranches }, 'baseBranches');
    let res;
    let branches = [];
    let branchList = [];
    for (const baseBranch of config.baseBranches) {
      logger.debug(`baseBranch: ${baseBranch}`);
      const baseBranchConfig = mergeChildConfig(config, { baseBranch });
      if (config.baseBranches.length > 1) {
        baseBranchConfig.branchPrefix += `${baseBranch}-`;
        baseBranchConfig.hasBaseBranches = true;
      }
      platform.setBaseBranch(baseBranch);
      const baseBranchRes = await extractAndUpdate(baseBranchConfig);
      ({ res } = baseBranchRes);
      branches = branches.concat(baseBranchRes.branches);
      branchList = branchList.concat(baseBranchRes.branchList);
    }
    return { res, branches, branchList };
  }
  logger.debug('No baseBranches');
  return extractAndUpdate(config);
}
<|endoftext|>


<commit_before>var fs = require('fs');

module.exports = {

  VERSION: "Crazy All In Bot",

  bet_request: function(game_state) {
    //return 50;
    //return bet_plus_blind(game_state, 2);
    return bet_strategy_by_score(game_state);
  },

  showdown: function(game_state) {
    try {
      fs.writeFile(game_state.game_id + '.game_state.json', JSON.stringify(game_state, null, 2), function (err) {
        //pass;
      });
    } catch (e) {
      //pass;
    }
  }

};

function bet_plus_blind(game_state, blinds) {
  var maxBet = game_state.small_blind * 2;
  game_state.players.forEach(function (p) {
    maxBet = Math.max(p.bet, maxBet);
  });
  return maxBet + game_state.small_blind * blinds - maxBet % game_state.small_blind;
}

RANK_SCORE = {
  "2": 1,
  "3": 2,
  "4": 3,
  "5": 4,
  "6": 5,
  "7": 6,
  "8": 7,
  "9": 8,
  "10": 9,
  "J": 10,
  "Q": 11,
  "K": 12,
  "A": 13
};

function bet_strategy_by_score(game_state) {
  try {
    players = game_state.players;
    sevenbits_bot = players.filter(function (player) {
      return player.name == 'sevenbits';
    })[0];
    our_cards = sevenbits_bot.hole_cards;
    score = score_cards(our_cards[0], our_cards[1]);
    if (score > 95) {
      return calculate_allowed_bet(game_state, sevenbits_bot, score);
    } else {
      return 0;
    }
  } catch (e) {
    console.log(e);
    return 0;
  }
}

function score_cards(card1, card2) {
  score = RANK_SCORE[card1['rank']] * RANK_SCORE[card2['rank']];
  if (card1['rank'] == card2['rank']) {
    score = Math.max(score, 100);
  }
  if (card1['rank'] == "A" || card2['rank'] == "A") {
    score = Math.max(score, 100);
  }
  return score;
}

function calculate_allowed_bet(game_state, our_player, cards_score) {
  suggested_bet = bet_plus_blind(game_state, 3);
  our_stack = our_player.stack;
  pot = game_state.pot;
  if ((((suggested_bet/our_stack) - (cards_score / 169)) > 0.05) && (pot < our_stack * 0.66)) {
    return 0;
  } else {
    return suggested_bet;
  }
}
<commit_msg>Changed filename for stats file.<commit_after>var fs = require('fs');

module.exports = {

  VERSION: "Crazy All In Bot",

  bet_request: function(game_state) {
    //return 50;
    //return bet_plus_blind(game_state, 2);
    return bet_strategy_by_score(game_state);
  },

  showdown: function(game_state) {
    try {
      fs.writeFile(game_state.game_id + '.' + game_state.round + '.game_state.json', JSON.stringify(game_state, null, 2), function (err) {
        //pass;
      });
    } catch (e) {
      //pass;
    }
  }

};

function bet_plus_blind(game_state, blinds) {
  var maxBet = game_state.small_blind * 2;
  game_state.players.forEach(function (p) {
    maxBet = Math.max(p.bet, maxBet);
  });
  return maxBet + game_state.small_blind * blinds - maxBet % game_state.small_blind;
}

RANK_SCORE = {
  "2": 1,
  "3": 2,
  "4": 3,
  "5": 4,
  "6": 5,
  "7": 6,
  "8": 7,
  "9": 8,
  "10": 9,
  "J": 10,
  "Q": 11,
  "K": 12,
  "A": 13
};

function bet_strategy_by_score(game_state) {
  try {
    players = game_state.players;
    sevenbits_bot = players.filter(function (player) {
      return player.name == 'sevenbits';
    })[0];
    our_cards = sevenbits_bot.hole_cards;
    score = score_cards(our_cards[0], our_cards[1]);
    if (score > 95) {
      return calculate_allowed_bet(game_state, sevenbits_bot, score);
    } else {
      return 0;
    }
  } catch (e) {
    console.log(e);
    return 0;
  }
}

function score_cards(card1, card2) {
  score = RANK_SCORE[card1['rank']] * RANK_SCORE[card2['rank']];
  if (card1['rank'] == card2['rank']) {
    score = Math.max(score, 100);
  }
  if (card1['rank'] == "A" || card2['rank'] == "A") {
    score = Math.max(score, 100);
  }
  return score;
}

function calculate_allowed_bet(game_state, our_player, cards_score) {
  suggested_bet = bet_plus_blind(game_state, 3);
  our_stack = our_player.stack;
  pot = game_state.pot;
  if ((((suggested_bet/our_stack) - (cards_score / 169)) > 0.05) && (pot < our_stack * 0.66)) {
    return 0;
  } else {
    return suggested_bet;
  }
}
<|endoftext|>


<commit_before>// Copyright Peter Širka, Web Site Design s.r.o. (www.petersirka.sk)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var fs = require('fs');
var ph = require('path');
var zlib = require('zlib');

function Backup() {
	this.file = [];
	this.directory = [];
	this.path = '';
	this.fileName = '';

	this.read = { key: '', value: '', status: 0 };

	this.complete = function() {};
	this.filter = function(path) {
		return true;
	};
};

function Walker() {
	this.pending = [];
	this.pendingDirectory = [];
	this.directory = [];
	this.file = [];
	this.complete = null;
};

Walker.prototype.walk = function(path) {
	var self = this;
	fs.readdir(path, function(err, arr) {

		if (err)
			return self.next();

		if (arr.length === 0)
			self.directory.push(path);

		arr.forEach(function(o) {
			self.pending.push(ph.join(path, o));
		});

		self.next();
	});
};

Walker.prototype.stat = function(path) {
	var self = this;

	fs.stat(path, function(err, stats) {

		if (err)
			return self.next();

		if (stats.isDirectory())
			self.pendingDirectory.push(path);
		else
			self.file.push(path);

		self.next();
	});
};

Walker.prototype.next = function() {
	var self = this;

	if (self.pending.length > 0) {
		var item = self.pending.shift();
		self.stat(item);
		return;
	}

	if (self.pendingDirectory.length > 0) {
		var directory = self.pendingDirectory.shift();
		self.walk(directory);
		return;
	}

	self.file.sort(function(a, b) {
		return a.localeCompare(b);
	});

	self.complete(self.directory, self.file);
};

Backup.prototype.backup = function(path, fileName, callback, filter) {

	if (fs.existsSync(fileName))
		fs.unlinkSync(fileName);

	var walker = new Walker();
	var self = this;

	self.fileName = fileName;
	self.path = path;

	if (callback)
		self.complete = callback;

	if (filter)
		self.filter = filter;

	walker.complete = function(directory, files) {
		self.directory = directory;
		self.file = files;
		self.$compress();
	};

	walker.walk(path);
};

Backup.prototype.$compress = function() {

	var self = this;
	var length = self.path.length;

	if (self.directory.length > 0) {

		self.directory.forEach(function(o) {
			if (self.filter(o.substring(length)))
				fs.appendFileSync(self.fileName, (o.replace(self.path, '') + '/').padRight(100) + ':#\n');
		});

		self.directory = [];
	}

	var fileName = self.file.shift();

	if (typeof(fileName) === 'undefined') {
		self.complete(null, self.fileName);
		return;
	}

	if (!self.filter(fileName.substring(length))) {
		self.$compress();
		return;
	}

	var buffer = '';

	fs.readFile(fileName, function(err, data) {
		zlib.gzip(data, function(err, data) {

			if (err)
				return;

			var name = fileName.replace(self.path, '');
			fs.appendFile(self.fileName, name.padRight(100) + ':' + data.toString('base64') + '\n', function(err) {
				self.$compress();
			});
		});
	});
};

Backup.prototype.restoreKey = function(data) {

	var self = this;
	var read = self.read;

	if (read.status === 1) {
		self.restoreValue(data);
		return;
	}

	var index = data.indexOf(':');

	if (index === -1) {
		read.key += data;
		return;
	}

	read.status = 1;
	read.key = data.substring(0, index);
	self.restoreValue(data.substring(index + 1));
};

Backup.prototype.restoreValue = function(data) {

	var self = this;
	var read = self.read;

	if (read.status !== 1) {
		self.restoreKey(data);
		return;
	}

	var index = data.indexOf('\n');
	if (index === -1) {
		read.value += data;
		return;
	}

	read.value += data.substring(0, index);

	self.restoreFile(read.key.replace(/\s/g, ''), read.value.replace(/\s/g, ''));

	read.status = 0;
	read.value = '';
	read.key = '';

	self.restoreKey(data.substring(index + 1));
};

Backup.prototype.restore = function(fileName, path, callback, filter) {

	if (!fs.existsSync(fileName)) {
		if (callback)
			callback(new Error('Backup file not found.'), path);
		return;
	}

	var self = this;
	self.createDirectory(path, true);

	var stream = fs.createReadStream(fileName);
	var key = '';
	var value = '';
	var status = 0;

	self.path = path;

	stream.on('data', function(buffer) {

		var data = buffer.toString('utf8');
		self.restoreKey(data);

	});

	if (callback) {
		stream.on('end', function() {
			callback(null, path);
		});
	}

	stream.resume();
};

Backup.prototype.restoreFile = function(key, value) {
	var self = this;

	if (!self.filter(key))
		return;

	if (value === '#') {
		self.createDirectory(key);
		return;
	}

	var path = key;
	var index = key.lastIndexOf('/');

	if (index !== -1) {
		path = key.substring(0, index).trim();
		if (path.length > 0)
			self.createDirectory(path);
	}

	zlib.gunzip(new Buffer(value, 'base64'), function(err, data) {
		fs.writeFileSync(ph.join(self.path, key), data);
	});
};

Backup.prototype.createDirectory = function(path, root) {

	if (path[0] === '/')
		path = path.substring(1);

	if (path[path.length - 1] === '/')
		path = path.substring(0, path.length - 1);

	var arr = path.split('/');
	var directory = '';
	var self = this;

	arr.forEach(function(name) {

		directory += (directory.length > 0 ? '/' : '') + name;

		var dir = ph.join(self.path, directory);

		if (root)
			dir = '/' + dir;

		if (fs.existsSync(dir))
			return;

		fs.mkdirSync(dir);
	});
};

/*
	@max {Number}
	@c {String} :: optional
	return {String}
*/
String.prototype.padLeft = function(max, c) {
	var self = this.toString();
	return Array(Math.max(0, max - self.length + 1)).join(c || ' ') + self;
};

/*
	@max {Number}
	@c {String} :: optional
	return {String}
*/
String.prototype.padRight = function(max, c) {
	var self = this.toString();
	return self + Array(Math.max(0, max - self.length + 1)).join(c || ' ');
};

String.prototype.trim = function() {
	return this.replace(/^[\s]+|[\s]+$/g, '');
};

// ===========================================================================
// EXPORTS
// ===========================================================================

exports.backup = function(path, fileName, callback, filter) {
	var backup = new Backup();
	backup.backup(path, fileName, callback, filter);
};

exports.restore = function(fileName, path, callback, filter) {
	var backup = new Backup();
	backup.restore(fileName, path, callback, filter);
};

exports.Backup = Backup;<commit_msg>fixed problem with Windows path<commit_after>// Copyright Peter Širka, Web Site Design s.r.o. (www.petersirka.sk)
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.

var fs = require('fs');
var ph = require('path');
var zlib = require('zlib');
var padding = 120;

function Backup() {
	this.file = [];
	this.directory = [];
	this.path = '';
	this.fileName = '';

	this.read = { key: '', value: '', status: 0 };

	this.complete = function() {};
	this.filter = function(path) {
		return true;
	};
};

function Walker() {
	this.pending = [];
	this.pendingDirectory = [];
	this.directory = [];
	this.file = [];
	this.complete = null;
};

Walker.prototype.walk = function(path) {
	var self = this;
	fs.readdir(path, function(err, arr) {

		if (err)
			return self.next();

		if (arr.length === 0)
			self.directory.push(path);

		arr.forEach(function(o) {
			self.pending.push(ph.join(path, o));
		});

		self.next();
	});
};

Walker.prototype.stat = function(path) {
	var self = this;

	fs.stat(path, function(err, stats) {

		if (err)
			return self.next();

		if (stats.isDirectory())
			self.pendingDirectory.push(path);
		else
			self.file.push(path);

		self.next();
	});
};

Walker.prototype.next = function() {
	var self = this;

	if (self.pending.length > 0) {
		var item = self.pending.shift();
		self.stat(item);
		return;
	}

	if (self.pendingDirectory.length > 0) {
		var directory = self.pendingDirectory.shift();
		self.walk(directory);
		return;
	}

	self.file.sort(function(a, b) {
		return a.localeCompare(b);
	});

	self.complete(self.directory, self.file);
};

Backup.prototype.backup = function(path, fileName, callback, filter) {

	if (fs.existsSync(fileName))
		fs.unlinkSync(fileName);

	var walker = new Walker();
	var self = this;

	self.fileName = fileName;
	self.path = path;

	if (callback)
		self.complete = callback;

	if (filter)
		self.filter = filter;

	walker.complete = function(directory, files) {
		self.directory = directory;
		self.file = files;
		self.$compress();
	};

	walker.walk(path);
};

Backup.prototype.$compress = function() {

	var self = this;
	var length = self.path.length;

	if (self.directory.length > 0) {

		self.directory.forEach(function(o) {
			if (self.filter(o.substring(length)))
				fs.appendFileSync(self.fileName, (o.replace(self.path, '').replace(/\\/g, '/') + '/').padRight(padding) + ':#\n');
		});

		self.directory = [];
	}

	var fileName = self.file.shift();

	if (typeof(fileName) === 'undefined') {
		self.complete(null, self.fileName);
		return;
	}

	if (!self.filter(fileName.substring(length))) {
		self.$compress();
		return;
	}

	var buffer = '';

	fs.readFile(fileName, function(err, data) {
		zlib.gzip(data, function(err, data) {

			if (err)
				return;

			var name = fileName.replace(self.path, '').replace(/\\/g, '/');
			fs.appendFile(self.fileName, name.padRight(padding) + ':' + data.toString('base64') + '\n', function(err) {
				self.$compress();
			});
		});
	});
};

Backup.prototype.restoreKey = function(data) {

	var self = this;
	var read = self.read;

	if (read.status === 1) {
		self.restoreValue(data);
		return;
	}

	var index = data.indexOf(':');

	if (index === -1) {
		read.key += data;
		return;
	}

	read.status = 1;
	read.key = data.substring(0, index);
	self.restoreValue(data.substring(index + 1));
};

Backup.prototype.restoreValue = function(data) {

	var self = this;
	var read = self.read;

	if (read.status !== 1) {
		self.restoreKey(data);
		return;
	}

	var index = data.indexOf('\n');
	if (index === -1) {
		read.value += data;
		return;
	}

	read.value += data.substring(0, index);

	self.restoreFile(read.key.replace(/\s/g, ''), read.value.replace(/\s/g, ''));

	read.status = 0;
	read.value = '';
	read.key = '';

	self.restoreKey(data.substring(index + 1));
};

Backup.prototype.restore = function(fileName, path, callback, filter) {

	if (!fs.existsSync(fileName)) {
		if (callback)
			callback(new Error('Backup file not found.'), path);
		return;
	}

	var self = this;
	self.createDirectory(path, true);

	var stream = fs.createReadStream(fileName);
	var key = '';
	var value = '';
	var status = 0;

	self.path = path;

	stream.on('data', function(buffer) {

		var data = buffer.toString('utf8');
		self.restoreKey(data);

	});

	if (callback) {
		stream.on('end', function() {
			callback(null, path);
		});
	}

	stream.resume();
};

Backup.prototype.restoreFile = function(key, value) {
	var self = this;

	if (!self.filter(key))
		return;

	if (value === '#') {
		self.createDirectory(key);
		return;
	}

	var path = key;
	var index = key.lastIndexOf('/');

	if (index !== -1) {
		path = key.substring(0, index).trim();
		if (path.length > 0)
			self.createDirectory(path);
	}

	zlib.gunzip(new Buffer(value, 'base64'), function(err, data) {
		fs.writeFileSync(ph.join(self.path, key), data);
	});
};

Backup.prototype.createDirectory = function(path, root) {

	if (path[0] === '/')
		path = path.substring(1);

	if (path[path.length - 1] === '/')
		path = path.substring(0, path.length - 1);

	var arr = path.split('/');
	var directory = '';
	var self = this;

	arr.forEach(function(name) {

		directory += (directory.length > 0 ? '/' : '') + name;

		var dir = ph.join(self.path, directory);

		if (root)
			dir = '/' + dir;

		if (fs.existsSync(dir))
			return;

		fs.mkdirSync(dir);
	});
};

/*
	@max {Number}
	@c {String} :: optional
	return {String}
*/
String.prototype.padLeft = function(max, c) {
	var self = this.toString();
	return Array(Math.max(0, max - self.length + 1)).join(c || ' ') + self;
};

/*
	@max {Number}
	@c {String} :: optional
	return {String}
*/
String.prototype.padRight = function(max, c) {
	var self = this.toString();
	return self + Array(Math.max(0, max - self.length + 1)).join(c || ' ');
};

String.prototype.trim = function() {
	return this.replace(/^[\s]+|[\s]+$/g, '');
};

// ===========================================================================
// EXPORTS
// ===========================================================================

exports.backup = function(path, fileName, callback, filter) {
	var backup = new Backup();
	backup.backup(path, fileName, callback, filter);
};

exports.restore = function(fileName, path, callback, filter) {
	var backup = new Backup();
	backup.restore(fileName, path, callback, filter);
};

exports.Backup = Backup;<|endoftext|>


<commit_before>import { a, div, br, label, input, p, button, code, pre } from '@cycle/dom'
import xs from 'xstream'
import isolate from '@cycle/isolate'
import { mergeWith, merge } from 'ramda'
import { clone, equal, equals, mergeAll } from 'ramda';
import dropRepeats from 'xstream/extra/dropRepeats'

// Components
import { SignatureForm, formLens } from '../components/SignatureForm'
import { BinnedPlots, plotsLens } from '../components/BinnedPlots/BinnedPlots'
import { makeTable, headTableLens, tailTableLens } from '../components/Table'
import { initSettings } from './settings'
import { Filter, compoundFilterLens } from '../components/Filter'
import { loggerFactory } from '~/../../src/js/utils/logger'
import { SampleTable, sampleTableLens } from '../components/SampleTable/SampleTable'

// Support for ghost mode
import { scenario } from '../scenarios/diseaseScenario'
import { runScenario } from '../utils/scenario'

function DiseaseWorkflow(sources) {

    const logger = loggerFactory('signature', sources.onion.state$, 'settings.common.debug')

    const state$ = sources.onion.state$

    // Scenario for ghost mode
    const scenarioReducer$ =
        sources.onion.state$.take(1)
        .filter(state => state.settings.common.ghostMode)
        .mapTo(runScenario(scenario).scenarioReducer$)
        .flatten()
        .startWith(prevState => prevState)
    const scenarioPopup$ =
        sources.onion.state$.take(1)
        .filter(state => state.settings.common.ghostMode)
        .mapTo(runScenario(scenario).scenarioPopup$)
        .flatten()
        .startWith({ text: 'Welcome to Disease Workflow', duration: 4000 })

    /**
     * Parse feedback from vega components. Not used yet...
     */
    // const feedback$ = sources.vega.map(item => item).startWith(null).debug();
    // const feedback$ = domSource$.select('.SignatureCheck').events('click').mapTo('click !').startWith(null);

    const signatureForm = isolate(SignatureForm, { onion: formLens })(sources)
    const signature$ = signatureForm.output

    // Filter Form
    const filterForm = isolate(Filter, { onion: compoundFilterLens })({...sources, input: signature$ })
    const filter$ = filterForm.output.remember()

    // default Reducer, initialization
    const defaultReducer$ = xs.of(prevState => {
        // disease -- defaultReducer
        if (typeof prevState === 'undefined') {
            return ({
                settings: initSettings,
                form: {},
            })
        } else {
            return ({
                ...prevState,
                settings: prevState.settings,
                form: {},
            })
        }
    })

    // Binned Plots
    const binnedPlots = isolate(BinnedPlots, { onion: plotsLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ signature: s, filter: f })).remember() });

    // Histogram plot component
    // const histogram = isolate(Histogram, { onion: histLens })
    //     ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ signature: s, filter: f })).remember() });

    const headTableContainer = makeTable(SampleTable, sampleTableLens)

    // tables: Join settings from api and sourire into props
    const headTable = isolate(headTableContainer, { onion: headTableLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ query: s, filter: f })).remember() });

    const tailTableContainer = makeTable(SampleTable, sampleTableLens)

    // tables: Join settings from api and sourire into props
    const tailTable = isolate(tailTableContainer, { onion: tailTableLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ query: s, filter: f })).remember() });

    const pageStyle = {
        style: {
            fontSize: '14px',
            opacity: '0',
            transition: 'opacity 1s',
            delayed: { opacity: '1' },
            destroy: { opacity: '0' },
        }
    }

    const vdom$ = xs.combine(
            signatureForm.DOM,
            filterForm.DOM,
            binnedPlots.DOM,
            headTable.DOM,
            tailTable.DOM,
            // feedback$
        )
        .map(([
                form,
                filter,
                plots,
                headTable,
                tailTable,
                // feedback
            ]) =>
            div('.row .disease', { style: { margin: '0px 0px 0px 0px' } }, [
                form,
                div('.col .s10 .offset-s1', pageStyle, [
                    div('.row', [filter]),
                    div('.row', [plots]),
                    div('.row', []),
                    div('.col .s12', [headTable]),
                    div('.row', []),
                    div('.col .s12', [tailTable]),
                    div('.row', [])
                ])
            ])
        );

    return {
        log: xs.merge(
            logger(state$, 'state$'),
            binnedPlots.log,
            signatureForm.log
        ),
        DOM: vdom$,
        onion: xs.merge(
            defaultReducer$,
            signatureForm.onion,
            filterForm.onion,
            binnedPlots.onion,
            headTable.onion,
            tailTable.onion,
            scenarioReducer$
        ),
        vega: xs.merge(
            binnedPlots.vega
        ),
        HTTP: xs.merge(
            signatureForm.HTTP,
            binnedPlots.HTTP,
            headTable.HTTP,
            tailTable.HTTP
        ),
        popup: scenarioPopup$
    };
}

export default DiseaseWorkflow;<commit_msg>Cleanup<commit_after>import { a, div, br, label, input, p, button, code, pre } from '@cycle/dom'
import xs from 'xstream'
import isolate from '@cycle/isolate'
import { mergeWith, merge } from 'ramda'
import { clone, equal, equals, mergeAll } from 'ramda';
import dropRepeats from 'xstream/extra/dropRepeats'

// Components
import { SignatureForm, formLens } from '../components/SignatureForm'
import { BinnedPlots, plotsLens } from '../components/BinnedPlots/BinnedPlots'
import { makeTable, headTableLens, tailTableLens } from '../components/Table'
import { initSettings } from './settings'
import { Filter, compoundFilterLens } from '../components/Filter'
import { loggerFactory } from '~/../../src/js/utils/logger'
import { SampleTable, sampleTableLens } from '../components/SampleTable/SampleTable'

// Support for ghost mode
import { scenario } from '../scenarios/diseaseScenario'
import { runScenario } from '../utils/scenario'

function DiseaseWorkflow(sources) {

    const logger = loggerFactory('signature', sources.onion.state$, 'settings.common.debug')

    const state$ = sources.onion.state$

    // Scenario for ghost mode
    const scenarioReducer$ =
        sources.onion.state$.take(1)
        .filter(state => state.settings.common.ghostMode)
        .mapTo(runScenario(scenario).scenarioReducer$)
        .flatten()
        .startWith(prevState => prevState)
    const scenarioPopup$ =
        sources.onion.state$.take(1)
        .filter(state => state.settings.common.ghostMode)
        .mapTo(runScenario(scenario).scenarioPopup$)
        .flatten()
        .startWith({ text: 'Welcome to Disease Workflow', duration: 4000 })

    /**
     * Parse feedback from vega components. Not used yet...
     */
    // const feedback$ = sources.vega.map(item => item).startWith(null).debug();
    // const feedback$ = domSource$.select('.SignatureCheck').events('click').mapTo('click !').startWith(null);

    const signatureForm = isolate(SignatureForm, { onion: formLens })(sources)
    const signature$ = signatureForm.output

    // Filter Form
    const filterForm = isolate(Filter, { onion: compoundFilterLens })({...sources, input: signature$ })
    const filter$ = filterForm.output.remember()

    // default Reducer, initialization
    const defaultReducer$ = xs.of(prevState => {
        // disease -- defaultReducer
        if (typeof prevState === 'undefined') {
            return ({
                settings: initSettings,
                form: {},
            })
        } else {
            return ({
                ...prevState,
                settings: prevState.settings,
                form: {},
            })
        }
    })

    // Binned Plots Component
    const binnedPlots = isolate(BinnedPlots, { onion: plotsLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ signature: s, filter: f })).remember() });

    // tables
    const headTableContainer = makeTable(SampleTable, sampleTableLens)
    const tailTableContainer = makeTable(SampleTable, sampleTableLens)

    // Join settings from api and sourire into props
    const headTable = isolate(headTableContainer, { onion: headTableLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ query: s, filter: f })).remember() });
    const tailTable = isolate(tailTableContainer, { onion: tailTableLens })
        ({...sources, input: xs.combine(signature$, filter$).map(([s, f]) => ({ query: s, filter: f })).remember() });

    const pageStyle = {
        style: {
            fontSize: '14px',
            opacity: '0',
            transition: 'opacity 1s',
            delayed: { opacity: '1' },
            destroy: { opacity: '0' },
        }
    }

    const vdom$ = xs.combine(
            signatureForm.DOM,
            filterForm.DOM,
            binnedPlots.DOM,
            headTable.DOM,
            tailTable.DOM,
            // feedback$
        )
        .map(([
                form,
                filter,
                plots,
                headTable,
                tailTable,
                // feedback
            ]) =>
            div('.row .disease', { style: { margin: '0px 0px 0px 0px' } }, [
                form,
                div('.col .s10 .offset-s1', pageStyle, [
                    div('.row', [filter]),
                    div('.row', [plots]),
                    div('.row', []),
                    div('.col .s12', [headTable]),
                    div('.row', []),
                    div('.col .s12', [tailTable]),
                    div('.row', [])
                ])
            ])
        );

    return {
        log: xs.merge(
            logger(state$, 'state$'),
            binnedPlots.log,
            signatureForm.log
        ),
        DOM: vdom$,
        onion: xs.merge(
            defaultReducer$,
            signatureForm.onion,
            filterForm.onion,
            binnedPlots.onion,
            headTable.onion,
            tailTable.onion,
            scenarioReducer$
        ),
        vega: xs.merge(
            binnedPlots.vega
        ),
        HTTP: xs.merge(
            signatureForm.HTTP,
            binnedPlots.HTTP,
            headTable.HTTP,
            tailTable.HTTP
        ),
        popup: scenarioPopup$
    };
}

export default DiseaseWorkflow;<|endoftext|>


<commit_before>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    bet(1000);
  },

  showdown: function(game_state) {

  }
};
<commit_msg>all iN<commit_after>
module.exports = {

  VERSION: "Default JavaScript folding player",

  bet_request: function(game_state, bet) {
    //bet(1000);
    Math.floor((Math.random() * 100) + 300);

  },

  showdown: function(game_state) {

  }
};
<|endoftext|>


<commit_before>"use strict;"

var options = {
  "todoist_token": "",
  "ifttt_token": "",
  "ifttt_event": "",
  "start_fmt": "%Y-%m-%dT%H:%M:%S%Z",
  "end_fmt": "%Y-%m-%dT%H:%M:%S%Z"
}

var todoist_endpoint = 'https://todoist.com/API/v6/sync';
var ifttt_endpoint = 'https://maker.ifttt.com/trigger/';

// some modification from public domain software http://dren.ch/strftime/
Number.prototype.pad = function (n,p) {
	var s = '' + this;
	p = p || '0';
	while (s.length < n) s = p + s;
	return s;
};
Date.prototype.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Date.prototype.weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
Date.prototype.dpm = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
Date.prototype.strftime_f = {
	A: function (d) { return d.weekdays[d.getDay()] },
	a: function (d) { return d.weekdays[d.getDay()].substring(0,3) },
	B: function (d) { return d.months[d.getMonth()] },
	b: function (d) { return d.months[d.getMonth()].substring(0,3) },
	C: function (d) { return Math.floor(d.getFullYear()/100); },
	c: function (d) { return d.toString() },
	D: function (d) { return d.strftime_f.m(d) + '/' + d.strftime_f.d(d) + '/' + d.strftime_f.y(d); },
	d: function (d) { return d.getDate().pad(2,'0') },
	e: function (d) { return d.getDate().pad(2,' ') },
	F: function (d) { return d.strftime_f.Y(d) + '-' + d.strftime_f.m(d) + '-' + d.strftime_f.d(d); },
	H: function (d) { return d.getHours().pad(2,'0') },
	I: function (d) { return ((d.getHours() % 12 || 12).pad(2)) },
	j: function (d) {
		var t = d.getDate();
		var m = d.getMonth() - 1;
		if (m > 1) {
			var y = d.getYear();
			if (((y % 100) == 0) && ((y % 400) == 0)) ++t;
			else if ((y % 4) == 0) ++t;
		}
		while (m > -1) t += d.dpm[m--];
		return t.pad(3,'0');
	},
	k: function (d) { return d.getHours().pad(2,' ') },
	l: function (d) { return ((d.getHours() % 12 || 12).pad(2,' ')) },
	M: function (d) { return d.getMinutes().pad(2,'0') },
	m: function (d) { return (d.getMonth()+1).pad(2,'0') },
	n: function (d) { return "\n" },
	p: function (d) { return (d.getHours() > 11) ? 'PM' : 'AM' },
	R: function (d) { return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) },
	r: function (d) { return d.strftime_f.I(d) + ':' + d.strftime_f.M(d) + ':' + d.strftime_f.S(d) + ' ' + d.strftime_f.p(d); },
	S: function (d) { return d.getSeconds().pad(2,'0') },
	s: function (d) { return Math.floor(d.getTime()/1000) },
	T: function (d) { return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) + ':' + d.strftime_f.S(d); },
	t: function (d) { return "\t" },
	u: function (d) { return(d.getDay() || 7) },
	v: function (d) { return d.strftime_f.e(d) + '-' + d.strftime_f.b(d) + '-' + d.strftime_f.Y(d); },
	w: function (d) { return d.getDay() },
	X: function (d) { return d.toTimeString() }, // wrong?
	x: function (d) { return d.toDateString() }, // wrong?
	Y: function (d) { return d.getFullYear() },
	y: function (d) { return (d.getYear() % 100).pad(2) },
  z: function (d) {
    var t = d.getTimezoneOffset();
    var s = t > 0 ? '-' : '+';
    t = t < 0 ? -t : t;
    return s + (t / 60).pad(2,'0') + ':' + (t % 60).pad(2,'0');
  },
	'%': function (d) { return '%' }
};
Date.prototype.strftime_f['+'] = Date.prototype.strftime_f.c;
Date.prototype.strftime_f.h = Date.prototype.strftime_f.b;
Date.prototype.strftime = function (fmt) {
	var r = '';
	var n = 0;
	while(n < fmt.length) {
		var c = fmt.substring(n, n+1);
		if (c == '%') {
			c = fmt.substring(++n, n+1);
			r += (this.strftime_f[c]) ? this.strftime_f[c](this) : c;
		} else r += c;
		++n;
	}
	return r;
};

function post(payload) {
  var req = new XMLHttpRequest();
  req.open('POST', ifttt_endpoint + options.ifttt_event + '/with/key/' + options.ifttt_token, true);
  req.setRequestHeader("Content-Type", "application/json");
  var started = new Date(payload.STARTED * 1000);
  var ended = new Date(payload.ENDED * 1000);
  var data = {"value1": payload.TITLE, "value2": started.strftime(options.start_fmt), "value3": ended.strftime(options.end_fmt)};
  req.send(JSON.stringify(data));
}

function fetch() {
  var req = new XMLHttpRequest();
  req.open('GET', todoist_endpoint + '?token=' + options.todoist_token + '&seq_no=0' + '&resource_types=' + encodeURIComponent('["items"]'), true);
  req.onload = function () {
    if (req.readyState === 4 && req.status === 200) {
      var response = JSON.parse(req.responseText);
      var elements = response.Items.sort(function(a, b) {
        return a.item_order < b.item_order ? -1 : 1;
      });
      var tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      elements.forEach(function(e, i, a) {
        if (e.checked === 1 || e.is_archived === 1 || e.is_deleted === 1)
          return;
        if (e.due_date != null && new Date(e.due_date) <= tomorrow) {
          var id = e.id;
          var name = e.content;
          Pebble.sendAppMessage({
            'ITEM_ID': id,
            'ITEM_NAME': name
          });
        }
      });
    }
    else {
      console.log("fetch failed with " + req.status + ": " + req.statusText);
    }
  };
  req.send(null);
}

Pebble.addEventListener('ready', function (e) {
  console.log('connected! ' + e.ready);
});

Pebble.addEventListener('appmessage', function (e) {
  console.log("message:" + JSON.stringify(e.payload));
  if (e.payload.hasOwnProperty("FETCH_ITEMS")) {
    fetch();
  }
  if (e.payload.hasOwnProperty("TITLE")) {
    post(e.payload);
  }
});

Pebble.addEventListener("showConfiguration", function() {
  console.log("showing configuration");
  Pebble.openURL('http://pebble.turbare.net/limone-watchapp/configurable.html');
});

Pebble.addEventListener("webviewclosed", function(e) {
  console.log("configuration closed");
  options = JSON.parse(decodeURIComponent(e.response));
  console.log('Config window returned: ', JSON.stringify(options));
});
<commit_msg>skip if required variables are not available<commit_after>"use strict;"

var options = {
  "todoist_token": "",
  "ifttt_token": "",
  "ifttt_event": "",
  "start_fmt": "%Y-%m-%dT%H:%M:%S%Z",
  "end_fmt": "%Y-%m-%dT%H:%M:%S%Z"
}

var todoist_endpoint = 'https://todoist.com/API/v6/sync';
var ifttt_endpoint = 'https://maker.ifttt.com/trigger/';

// some modification from public domain software http://dren.ch/strftime/
Number.prototype.pad = function (n,p) {
	var s = '' + this;
	p = p || '0';
	while (s.length < n) s = p + s;
	return s;
};
Date.prototype.months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
Date.prototype.weekdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
Date.prototype.dpm = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
Date.prototype.strftime_f = {
	A: function (d) { return d.weekdays[d.getDay()] },
	a: function (d) { return d.weekdays[d.getDay()].substring(0,3) },
	B: function (d) { return d.months[d.getMonth()] },
	b: function (d) { return d.months[d.getMonth()].substring(0,3) },
	C: function (d) { return Math.floor(d.getFullYear()/100); },
	c: function (d) { return d.toString() },
	D: function (d) { return d.strftime_f.m(d) + '/' + d.strftime_f.d(d) + '/' + d.strftime_f.y(d); },
	d: function (d) { return d.getDate().pad(2,'0') },
	e: function (d) { return d.getDate().pad(2,' ') },
	F: function (d) { return d.strftime_f.Y(d) + '-' + d.strftime_f.m(d) + '-' + d.strftime_f.d(d); },
	H: function (d) { return d.getHours().pad(2,'0') },
	I: function (d) { return ((d.getHours() % 12 || 12).pad(2)) },
	j: function (d) {
		var t = d.getDate();
		var m = d.getMonth() - 1;
		if (m > 1) {
			var y = d.getYear();
			if (((y % 100) == 0) && ((y % 400) == 0)) ++t;
			else if ((y % 4) == 0) ++t;
		}
		while (m > -1) t += d.dpm[m--];
		return t.pad(3,'0');
	},
	k: function (d) { return d.getHours().pad(2,' ') },
	l: function (d) { return ((d.getHours() % 12 || 12).pad(2,' ')) },
	M: function (d) { return d.getMinutes().pad(2,'0') },
	m: function (d) { return (d.getMonth()+1).pad(2,'0') },
	n: function (d) { return "\n" },
	p: function (d) { return (d.getHours() > 11) ? 'PM' : 'AM' },
	R: function (d) { return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) },
	r: function (d) { return d.strftime_f.I(d) + ':' + d.strftime_f.M(d) + ':' + d.strftime_f.S(d) + ' ' + d.strftime_f.p(d); },
	S: function (d) { return d.getSeconds().pad(2,'0') },
	s: function (d) { return Math.floor(d.getTime()/1000) },
	T: function (d) { return d.strftime_f.H(d) + ':' + d.strftime_f.M(d) + ':' + d.strftime_f.S(d); },
	t: function (d) { return "\t" },
	u: function (d) { return(d.getDay() || 7) },
	v: function (d) { return d.strftime_f.e(d) + '-' + d.strftime_f.b(d) + '-' + d.strftime_f.Y(d); },
	w: function (d) { return d.getDay() },
	X: function (d) { return d.toTimeString() }, // wrong?
	x: function (d) { return d.toDateString() }, // wrong?
	Y: function (d) { return d.getFullYear() },
	y: function (d) { return (d.getYear() % 100).pad(2) },
  z: function (d) {
    var t = d.getTimezoneOffset();
    var s = t > 0 ? '-' : '+';
    t = t < 0 ? -t : t;
    return s + (t / 60).pad(2,'0') + ':' + (t % 60).pad(2,'0');
  },
	'%': function (d) { return '%' }
};
Date.prototype.strftime_f['+'] = Date.prototype.strftime_f.c;
Date.prototype.strftime_f.h = Date.prototype.strftime_f.b;
Date.prototype.strftime = function (fmt) {
	var r = '';
	var n = 0;
	while(n < fmt.length) {
		var c = fmt.substring(n, n+1);
		if (c == '%') {
			c = fmt.substring(++n, n+1);
			r += (this.strftime_f[c]) ? this.strftime_f[c](this) : c;
		} else r += c;
		++n;
	}
	return r;
};

function post(payload) {
  if (options.ifttt_token === '') {
    console.log("IFTTT Maker token is not available");
    return;
  }
  if (options.ifttt_event === '') {
    console.log("IFTTT Make event name is not available");
    return;
  }
  var req = new XMLHttpRequest();
  req.open('POST', ifttt_endpoint + options.ifttt_event + '/with/key/' + options.ifttt_token, true);
  req.setRequestHeader("Content-Type", "application/json");
  var started = new Date(payload.STARTED * 1000);
  var ended = new Date(payload.ENDED * 1000);
  var data = {"value1": payload.TITLE, "value2": started.strftime(options.start_fmt), "value3": ended.strftime(options.end_fmt)};
  req.send(JSON.stringify(data));
}

function fetch() {
  if (options.todoist_token === '') {
    console.log("Todoist API token is not available");
    return;
  }
  var req = new XMLHttpRequest();
  req.open('GET', todoist_endpoint + '?token=' + options.todoist_token + '&seq_no=0' + '&resource_types=' + encodeURIComponent('["items"]'), true);
  req.onload = function () {
    if (req.readyState === 4 && req.status === 200) {
      var response = JSON.parse(req.responseText);
      var elements = response.Items.sort(function(a, b) {
        return a.item_order < b.item_order ? -1 : 1;
      });
      var tomorrow = new Date();
      tomorrow.setDate(tomorrow.getDate() + 1);
      elements.forEach(function(e, i, a) {
        if (e.checked === 1 || e.is_archived === 1 || e.is_deleted === 1)
          return;
        if (e.due_date != null && new Date(e.due_date) <= tomorrow) {
          var id = e.id;
          var name = e.content;
          Pebble.sendAppMessage({
            'ITEM_ID': id,
            'ITEM_NAME': name
          });
        }
      });
    }
    else {
      console.log("fetch failed with " + req.status + ": " + req.statusText);
    }
  };
  req.send(null);
}

Pebble.addEventListener('ready', function (e) {
  console.log('connected! ' + e.ready);
});

Pebble.addEventListener('appmessage', function (e) {
  console.log("message:" + JSON.stringify(e.payload));
  if (e.payload.hasOwnProperty("FETCH_ITEMS")) {
    fetch();
  }
  if (e.payload.hasOwnProperty("TITLE")) {
    post(e.payload);
  }
});

Pebble.addEventListener("showConfiguration", function() {
  console.log("showing configuration");
  Pebble.openURL('http://pebble.turbare.net/limone-watchapp/configurable.html');
});

Pebble.addEventListener("webviewclosed", function(e) {
  console.log("configuration closed");
  options = JSON.parse(decodeURIComponent(e.response));
  console.log('Config window returned: ', JSON.stringify(options));
});
<|endoftext|>


<commit_before>'use strict';

const CARD_RANKS = {
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    '10': 11,
    'J': 12,
    'Q': 13,
    'K': 14,
    'A': 16
};

const HIGH = 0;
const PAIR = 1;
const TWOPAIRS = 2;
const THREE = 3;

const GAME_CASES = [
    (c1, c2) => c1.rank === c2.rank ? 10 : 0,
    (c1, c2) => c1.suit === c2.suit ? 4 : 0,
    (c1, c2) => {
        let points = {1: 3, 2: 2, 3: 1};
        let distance = Math.abs(c1.rank - c2.rank);
        return points[distance] || 0;
    }
];

const HUTCHINSON_CONST = 30;
// const HUTCHINSON_CONST = 34;

function raiseCheck(cards) {
    for (let card of cards) {
        card.rank = CARD_RANKS[card.rank];
    }
    let points = cards[0].rank + cards[1].rank;
    for (let gameCaseFunc of GAME_CASES) {
        points += gameCaseFunc(cards[0], cards[1]) || 0;
    }
    if (points >= HUTCHINSON_CONST) {
        return true;
    }
    return false;
}

var countItems = function(arr, what) {
    var count = 0;
    var i;
    while ((i = arr.indexOf(what, i)) !== -1) {
        ++count;
        ++i;
    }
    return count;
};

var get_hands = function(player_hand, cards) {
    var all = player_hand.concat(cards);
    all = all.map((el) => {
        el.rank = CARD_RANKS[el.rank];
        return el;
    });
    all = all.sort((a, b) => a.rank - b.rank);
    console.log(all);
    let combs = combinations(all);
    console.log(combs);
    return combs;
};

var combinations = function(cards) {
    var combs = [];
    var types = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
    var values = cards.map(e => e.rank);
    var counts = types.map(c => countItems(values, c));
    var max = Math.max.apply(Math, counts);
    if (max === 2) {
        combs.push(PAIR);
    } else if (max === 3) {
        combs.push(THREE);
    }
    return combs;
};

module.exports = {

    VERSION: 'I LOVE UNICODE',

    // утилиты
    raiseCheck: raiseCheck,

    bet_request: function(game_state, bet) {
        try {
            let player = game_state.players.find((p) => {
                return p.hole_cards && p.hole_cards.length > 0;
            });
            let myCards = player.hole_cards;
            let communityCards = game_state.community_cards
            get_hands(myCards, communityCards);
            let iCanRaise = raiseCheck(myCards);
            if (iCanRaise) {
                return bet(10000);
            }
            return bet(0);
        } catch (e) {
            bet(10000);
        }
    },

    showdown: function(game_state) {

    }
};
<commit_msg>не идём в оллвин по первому случаю<commit_after>'use strict';

const CARD_RANKS = {
    '1': 1,
    '2': 2,
    '3': 3,
    '4': 4,
    '5': 5,
    '6': 6,
    '7': 7,
    '8': 8,
    '9': 9,
    '10': 11,
    'J': 12,
    'Q': 13,
    'K': 14,
    'A': 16
};

const HIGH = 0;
const PAIR = 1;
const TWOPAIRS = 2;
const THREE = 3;

const GAME_CASES = [
    (c1, c2) => c1.rank === c2.rank ? 10 : 0,
    (c1, c2) => c1.suit === c2.suit ? 4 : 0,
    (c1, c2) => {
        let points = {1: 3, 2: 2, 3: 1};
        let distance = Math.abs(c1.rank - c2.rank);
        return points[distance] || 0;
    }
];

const HUTCHINSON_CONST = 30;
// const HUTCHINSON_CONST = 34;

function raiseCheck(cards) {
    for (let card of cards) {
        card.rank = CARD_RANKS[card.rank];
    }
    let points = cards[0].rank + cards[1].rank;
    for (let gameCaseFunc of GAME_CASES) {
        points += gameCaseFunc(cards[0], cards[1]) || 0;
    }
    if (points >= HUTCHINSON_CONST) {
        return true;
    }
    return false;
}

var countItems = function(arr, what) {
    var count = 0;
    var i;
    while ((i = arr.indexOf(what, i)) !== -1) {
        ++count;
        ++i;
    }
    return count;
};

var get_hands = function(player_hand, cards) {
    var all = player_hand.concat(cards);
    all = all.map((el) => {
        el.rank = CARD_RANKS[el.rank];
        return el;
    });
    all = all.sort((a, b) => a.rank - b.rank);
    console.log(all);
    let combs = combinations(all);
    console.log(combs);
    return combs;
};

var combinations = function(cards) {
    var combs = [];
    var types = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
    var values = cards.map(e => e.rank);
    var counts = types.map(c => countItems(values, c));
    var max = Math.max.apply(Math, counts);
    if (max === 2) {
        combs.push(PAIR);
    } else if (max === 3) {
        combs.push(THREE);
    }
    return combs;
};

module.exports = {

    VERSION: 'I LOVE UNICODE',

    // утилиты
    raiseCheck: raiseCheck,

    bet_request: function(game_state, bet) {
        try {
            const players = game_state.players;
            const in_action = game_state.in_action;
            const bet = game_state.bet;
            const minimum_raise = game_state.minimum_raise;
            const current_buy_in = game_state.current_buy_in;
            const my_bet = players[in_action][bet];
            const player = players.players.find((p) => {
                return p.hole_cards && p.hole_cards.length > 0;
            });

            let minitmutRauseAmount = current_buy_in - my_bet + minimum_raise;

            let myCards = player.hole_cards;
            let communityCards = game_state.community_cards
            get_hands(myCards, communityCards);
            let iCanRaise = raiseCheck(myCards);
            if (iCanRaise) {
                return bet(minitmutRauseAmount);
            }
            return bet(0);
        } catch (e) {
            bet(10000);
        }
    },

    showdown: function(game_state) {

    }
};
<|endoftext|>


<commit_before>var schema = require('./lib/scheam/schema');

module.exports = (() => {
	'use strict';

	return schema;
})();<commit_msg>Fix spelling mistake<commit_after>var schema = require('./lib/schema/schema');

module.exports = (() => {
	'use strict';

	return schema;
})();<|endoftext|>


<commit_before>var map = require('level-map')
var reduce = require('level-reduce')

module.exports = function (db) {

  if(db.mapReduce) return

  map(db)
  reduce(db)

  db.mapReduce = {}
  db.mapReduce.add = function (view) {
    db.map.add(view)
    db.reduce.add(view)
  }

  db.mapReduce.start = function (name, done) {
    if(!name) {
      var started = 0
      for(var name in db.map.views) {
        started ++
        db.map.start(name, next)
      }
      function next() {
        if(!--started) done && done()
      }
    }
    else
      db.map.start(name, done)
  }
  db.mapReduce.view = db.reduce.view
}
<commit_msg>map and reduce are optional<commit_after>var map = require('level-map')
var reduce = require('level-reduce')

module.exports = function (db) {

  if(db.mapReduce) return

  map(db)
  reduce(db)

  db.mapReduce = {}
  db.mapReduce.add = function (view) {
    view.map = view.map || function (key, value, emit) {
      emit([], value)
    }
    db.map.add(view)
    if(view.reduce)
      db.reduce.add(view)
  }

  db.mapReduce.start = function (name, done) {
    if(!name) {
      var started = 0
      for(var name in db.map.views) {
        started ++
        db.map.start(name, next)
      }
      function next() {
        if(!--started) done && done()
      }
    }
    else
      db.map.start(name, done)
  }
  db.mapReduce.view = db.reduce.view
}
<|endoftext|>


<commit_before>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2018 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

ui.formWidget('PanelJson', {
  showTitle: false,
  transclude: true,
  template: "

"
});

ui.formInput('JsonField', 'String', {
  showTitle: false,
  link: function (scope, element, attrs, model) {
    var field = scope.field;
    var jsonFields = field.jsonFields || [];
    var jsonNames = _.pluck(jsonFields, 'name');
    var jsonFix = {};

    jsonFields.forEach(function (item) {
      if (item.widget && item.showTitle === undefined) {
        var widget = ui.getWidgetDef(item.widget);
        if (widget) {
          item.showTitle = widget.showTitle;
        }
      }
    });

    var defaultValues = {};
    var parentUnwatch = null;
    var selfUnwatch = null;

    scope.formPath = scope.formPath ? scope.formPath + "." + field.name : field.name;
    scope.record = {};

    jsonFields.forEach(function (item) {
      if (item.target === 'com.axelor.meta.db.MetaJsonRecord' &&
        item.targetName && item.targetName.indexOf('attrs.') === 0) {
        jsonFix[item.name] = function (v) {
          if (v) {
            v[item.targetName.substring(6)] = v[item.targetName];
          }
          return v;
        }
      }
      if (item.contextField && item.contextFieldValue) {
        var condition = "($record." + item.contextField + ".id === " + item.contextFieldValue + ")";
        if (item.showIf) condition += " && (" + item.showIf + ")";
        if (item.hideIf) condition += " && !(" + item.hideIf + ")";
        item.showIf = condition;
        item.hideIf = null;
      }
    });

    function getDefaultValues() {
      jsonFields.forEach(function (item) {
        if (item.defaultValue === undefined) return;
        var value = item.defaultValue;
        switch(item.type) {
        case 'integer':
          value = +(value);
          break;
        case 'date':
        case 'datetime':
          value = value === 'now' ? new Date() : moment(value).toDate();
          break;
        }
        defaultValues[item.name] = value;
      });
      return angular.copy(defaultValues);
    }

    function unwatchParent() {
      if (parentUnwatch) {
        parentUnwatch();
        parentUnwatch = null;
      }
    }

    function unwatchSelf() {
      if (selfUnwatch) {
        selfUnwatch();
        selfUnwatch = null;
      }
    }

    function watchParent() {
      unwatchParent();
      parentUnwatch = scope.$watch('$parent.record.' + field.name, function jsonParentWatch(value, old) {
        if (value === old) return;
        onRender();
      });
    }

    function watchSelf() {
      unwatchSelf();
      selfUnwatch = scope.$watch('record', function jsonRecordWatch(record, old) {
        if (record !== old) {
          onUpdate();
        }
      }, true);
    }

    function format(name, value) {
      var func = jsonFix[name];
      return func ? func(value) : value;
    }

    function onUpdate() {
      var rec = null;
      _.each(scope.record, function (v, k) {
        if (k.indexOf('$') === 0 || v === null || v === undefined) return;
        if (_.isArray(v)) {
          if (v.length == 0) return;
          v = v.map(function (x) {
            return x.id ? { id: x.id } : x;
          });
        }
        if (rec === null) {
          rec = {};
        }
        rec[k] = format(k, v);
      });
      unwatchParent();
      if (scope.$parent.record[field.name] || rec) {
        scope.$parent.record[field.name] = rec ? angular.toJson(rec) : rec;
      }
      watchParent();
    }

    function onRender() {
      var record = scope.$parent.record || {};
      var value = record[field.name];
      unwatchSelf();
      scope.record = value ? angular.fromJson(value) : getDefaultValues();
      scope._jsonContext = { '$record': record };
      record['$' + field.name] = scope.record;
      watchSelf();
    }

    scope.$on('on:new', onRender);
    scope.$on('on:edit', function () {
      if (scope.viewType === 'form' || (!scope.viewType && scope._isPopup)) onRender();
    });

    scope.updateJsonValues = function (values) {
      var rec = null;
      _.each(values, function (v, k) {
        if (jsonNames.indexOf(k) === -1 && scope.fields[k]) {
          scope.$parent.record[k] = v;
        } else {
          if (rec === null) {
            rec = {};
          }
          rec[k] = v;
        }
      });
      if (rec) {
        scope.record = _.extend({}, scope.record, rec);
      }
    }

    watchParent();

    // hide parent panel if no jsonFields defined
    scope.$evalAsync(function () {
      var parent = scope.$parent.field || {};
      if (parent.type === 'panel' && _.size(parent.items) === 1 && _.isEmpty(field.jsonFields)) {
        element.parents('.panel:first').addClass('hide').hide();
      }
    });

    scope.$on('on:update-context', function (e, context) {
      if (context && !context[field.name]) {
        context[field.name] = angular.toJson(scope.record || {});
      }
    });
  }
});

ui.formInput('JsonRaw', 'String', {
  showTitle: false,
  link: function (scope, element, attrs, model) {

    scope.placeHolderKey = _t('name');
    scope.placeHolderVal = _t('value');

    scope.items = [];

    scope.onAdd = function () {
      var last = _.last(scope.items);
      if (last && !(_.trim(last.name) && _.trim(last.value))) return;
      scope.items.push({});
    };

    scope.onRemove = function (index) {
      if (scope.items.length > 0) {
        scope.items.splice(index, 1);
      }
    };

    var unwatch = null;

    function doWatch () {
      if (unwatch) {
        unwatch();
      }
      unwatch = scope.$watch('items', function jsonItemsWatch(items, old) {
        if (items === old) return;
        var record = null;
        _.each(items, function (item) {
          if (!_.trim(item.name) || !_.trim(item.value)) return;
          if (record === null) {
            record = {};
          }
          record[item.name] = item.value;
        });
        model.$setViewValue(record ? angular.toJson(record) : null);
      }, true);
    }

    model.$render = function () {
      var value = model.$viewValue;
      if (value) {
        value = angular.fromJson(value);
      } else {
        value = {};
      }
      scope.items = _.map(_.keys(value), function (name) {
        return { name: name, value: value[name] || '' };
      });
      doWatch();
    };
  },
  template_readonly:
    "
" +
      "
" +
        "
" +
          "" +
            "{{item.name}}:" +
          "	" +
          "" +
            "{{item.value}}" +
          "	" +
        "
" +
      "
" +
    "
",
  template_editable:
    "
" +
      "
" +
        "
" +
          "" +
            "<input type='text' placeholder='{{placeHolderKey}}' ng-model='item.name'>" +
          "	" +
          "" +
            "<input type='text' placeholder='{{placeHolderVal}}' ng-model='item.value'>" +
          "	" +
          "	" +
        "
" +
      "
" +
      "" +
    "
"
});

ui.formInput('JsonRefSelect', {

  css: 'multi-object-select',

  controller: ['$scope', 'ViewService', function($scope, ViewService) {

    $scope.createElement = function(id, name, selectionList) {

      var elemGroup = $('

');
      var elemSelect = $('<input ui-select showTitle="false">')
        .attr("name", name + "$model")
        .attr("x-for-widget", id)
        .attr("ng-model", "record." + name + ".model");

      var elemSelects = $('

').attr('ng-switch', "record." + name + ".model");
      var elemItems = _.map(selectionList, function(s) {
        return $('<input ui-json-ref-item ng-switch-when="' + s.value +'">')
          .attr('ng-model', 'record.' + name)
          .attr('name', name)
          .attr('x-target', s.value);
      });

      elemGroup
        .append($('

').append(elemSelect))
        .append(elemSelects.append(elemItems));

      return ViewService.compile(elemGroup)($scope);
    };
  }],

  link: function(scope, element, attrs, model) {
    this._super.apply(this, arguments);

    var name = scope.field.name;
    var selectionList = scope.field.selectionList;

    scope.fieldsCache = {};

    scope.refFireEvent = function (name) {
      var handler = scope.$events[name];
      if (handler) {
        return handler();
      }
    };

    var elem = scope.createElement(element.attr('id'), name, selectionList);
    setTimeout(function() {
      element.append(elem);
    });

    scope.$watch("record." + name + ".model", function jsonModelWatch(value, old) {
      if (value === old || old === undefined) return;
      if (scope.record && scope.record[name]) {
        scope.record[name] = _.pick(scope.record[name], 'model');
        if (!scope.record[name].model) {
          delete scope.record[name];
        }
      }
    });
  },
  template_editable: null,
  template_readonly: null
});

ui.formInput('JsonRefItem', 'ManyToOne', {

  showTitle: false,

  link: function(scope, element, attrs, model) {
    this._super.apply(this, arguments);

    if (scope.field.targetName) {
      return this._link.apply(this, arguments);
    }

    var self = this;
    var target = element.attr('x-target');
    var data = (_.findWhere(scope.$parent.field.selectionList, {value: target})||{}).data || {};

    function doLink(fields) {
      var name = false,
        search = [];

      _.each(fields, function(f) {
        if (f.nameColumn) name = f.name;
        if (f.name === "name") search.push("name");
        if (f.name === "code") search.push("code");
      });

      if (!name && _.contains(search, "name")) {
        name = "name";
      }

      _.extend(scope.field, {
        target: scope._model,
        targetName: name,
        targetSearch: search,
        domain: data.domain
      });

      self._link(scope, element, attrs, model);
    }

    if (scope.fieldsCache[scope._model]) {
      doLink(scope.fieldsCache[scope._model]);
    } else {
      scope.loadFields().success(function (fields) {
        scope.fieldsCache[scope._model] = fields;
        doLink(fields);
      });
    }
  },

  _link: function(scope, element, attrs, model) {
    var name = element.attr('name');

    scope.getValue = function () {
      return scope.record[name];
    }

    var __setValue = scope.setValue;

    scope.setValue = function (value) {
      var val = _.pick(scope.record[name], 'model');
      val = _.extend(val, value);
      __setValue.call(scope, val);
    }

    function doSelect() {
      var value = (scope.record || {})[name];
      scope.select(value);
    }

    scope.$watch("record", doSelect);
  }
});

})();
<commit_msg>Fix contextual custom field with hidden=true<commit_after>/*
 * Axelor Business Solutions
 *
 * Copyright (C) 2005-2018 Axelor (<http://axelor.com>).
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License, version 3,
 * as published by the Free Software Foundation.
 *
 * 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
(function() {

"use strict";

var ui = angular.module('axelor.ui');

ui.formWidget('PanelJson', {
  showTitle: false,
  transclude: true,
  template: "

"
});

ui.formInput('JsonField', 'String', {
  showTitle: false,
  link: function (scope, element, attrs, model) {
    var field = scope.field;
    var jsonFields = field.jsonFields || [];
    var jsonNames = _.pluck(jsonFields, 'name');
    var jsonFix = {};

    jsonFields.forEach(function (item) {
      if (item.widget && item.showTitle === undefined) {
        var widget = ui.getWidgetDef(item.widget);
        if (widget) {
          item.showTitle = widget.showTitle;
        }
      }
    });

    var defaultValues = {};
    var parentUnwatch = null;
    var selfUnwatch = null;

    scope.formPath = scope.formPath ? scope.formPath + "." + field.name : field.name;
    scope.record = {};

    jsonFields.forEach(function (item) {
      if (item.target === 'com.axelor.meta.db.MetaJsonRecord' &&
        item.targetName && item.targetName.indexOf('attrs.') === 0) {
        jsonFix[item.name] = function (v) {
          if (v) {
            v[item.targetName.substring(6)] = v[item.targetName];
          }
          return v;
        }
      }
      if (item.contextField && item.contextFieldValue) {
        if (item.showIf === undefined && item.hideIf === undefined && item.hidden) {
          return;
        }
        var condition = "($record." + item.contextField + ".id === " + item.contextFieldValue + ")";
        if (item.showIf) condition += " && (" + item.showIf + ")";
        if (item.hideIf) condition += " && !(" + item.hideIf + ")";
        item.showIf = condition;
        item.hideIf = null;
      }
    });

    function getDefaultValues() {
      jsonFields.forEach(function (item) {
        if (item.defaultValue === undefined) return;
        var value = item.defaultValue;
        switch(item.type) {
        case 'integer':
          value = +(value);
          break;
        case 'date':
        case 'datetime':
          value = value === 'now' ? new Date() : moment(value).toDate();
          break;
        }
        defaultValues[item.name] = value;
      });
      return angular.copy(defaultValues);
    }

    function unwatchParent() {
      if (parentUnwatch) {
        parentUnwatch();
        parentUnwatch = null;
      }
    }

    function unwatchSelf() {
      if (selfUnwatch) {
        selfUnwatch();
        selfUnwatch = null;
      }
    }

    function watchParent() {
      unwatchParent();
      parentUnwatch = scope.$watch('$parent.record.' + field.name, function jsonParentWatch(value, old) {
        if (value === old) return;
        onRender();
      });
    }

    function watchSelf() {
      unwatchSelf();
      selfUnwatch = scope.$watch('record', function jsonRecordWatch(record, old) {
        if (record !== old) {
          onUpdate();
        }
      }, true);
    }

    function format(name, value) {
      var func = jsonFix[name];
      return func ? func(value) : value;
    }

    function onUpdate() {
      var rec = null;
      _.each(scope.record, function (v, k) {
        if (k.indexOf('$') === 0 || v === null || v === undefined) return;
        if (_.isArray(v)) {
          if (v.length == 0) return;
          v = v.map(function (x) {
            return x.id ? { id: x.id } : x;
          });
        }
        if (rec === null) {
          rec = {};
        }
        rec[k] = format(k, v);
      });
      unwatchParent();
      if (scope.$parent.record[field.name] || rec) {
        scope.$parent.record[field.name] = rec ? angular.toJson(rec) : rec;
      }
      watchParent();
    }

    function onRender() {
      var record = scope.$parent.record || {};
      var value = record[field.name];
      unwatchSelf();
      scope.record = value ? angular.fromJson(value) : getDefaultValues();
      scope._jsonContext = { '$record': record };
      record['$' + field.name] = scope.record;
      watchSelf();
    }

    scope.$on('on:new', onRender);
    scope.$on('on:edit', function () {
      if (scope.viewType === 'form' || (!scope.viewType && scope._isPopup)) onRender();
    });

    scope.updateJsonValues = function (values) {
      var rec = null;
      _.each(values, function (v, k) {
        if (jsonNames.indexOf(k) === -1 && scope.fields[k]) {
          scope.$parent.record[k] = v;
        } else {
          if (rec === null) {
            rec = {};
          }
          rec[k] = v;
        }
      });
      if (rec) {
        scope.record = _.extend({}, scope.record, rec);
      }
    }

    watchParent();

    // hide parent panel if no jsonFields defined
    scope.$evalAsync(function () {
      var parent = scope.$parent.field || {};
      if (parent.type === 'panel' && _.size(parent.items) === 1 && _.isEmpty(field.jsonFields)) {
        element.parents('.panel:first').addClass('hide').hide();
      }
    });

    scope.$on('on:update-context', function (e, context) {
      if (context && !context[field.name]) {
        context[field.name] = angular.toJson(scope.record || {});
      }
    });
  }
});

ui.formInput('JsonRaw', 'String', {
  showTitle: false,
  link: function (scope, element, attrs, model) {

    scope.placeHolderKey = _t('name');
    scope.placeHolderVal = _t('value');

    scope.items = [];

    scope.onAdd = function () {
      var last = _.last(scope.items);
      if (last && !(_.trim(last.name) && _.trim(last.value))) return;
      scope.items.push({});
    };

    scope.onRemove = function (index) {
      if (scope.items.length > 0) {
        scope.items.splice(index, 1);
      }
    };

    var unwatch = null;

    function doWatch () {
      if (unwatch) {
        unwatch();
      }
      unwatch = scope.$watch('items', function jsonItemsWatch(items, old) {
        if (items === old) return;
        var record = null;
        _.each(items, function (item) {
          if (!_.trim(item.name) || !_.trim(item.value)) return;
          if (record === null) {
            record = {};
          }
          record[item.name] = item.value;
        });
        model.$setViewValue(record ? angular.toJson(record) : null);
      }, true);
    }

    model.$render = function () {
      var value = model.$viewValue;
      if (value) {
        value = angular.fromJson(value);
      } else {
        value = {};
      }
      scope.items = _.map(_.keys(value), function (name) {
        return { name: name, value: value[name] || '' };
      });
      doWatch();
    };
  },
  template_readonly:
    "
" +
      "
" +
        "
" +
          "" +
            "{{item.name}}:" +
          "	" +
          "" +
            "{{item.value}}" +
          "	" +
        "
" +
      "
" +
    "
",
  template_editable:
    "
" +
      "
" +
        "
" +
          "" +
            "<input type='text' placeholder='{{placeHolderKey}}' ng-model='item.name'>" +
          "	" +
          "" +
            "<input type='text' placeholder='{{placeHolderVal}}' ng-model='item.value'>" +
          "	" +
          "	" +
        "
" +
      "
" +
      "" +
    "
"
});

ui.formInput('JsonRefSelect', {

  css: 'multi-object-select',

  controller: ['$scope', 'ViewService', function($scope, ViewService) {

    $scope.createElement = function(id, name, selectionList) {

      var elemGroup = $('

');
      var elemSelect = $('<input ui-select showTitle="false">')
        .attr("name", name + "$model")
        .attr("x-for-widget", id)
        .attr("ng-model", "record." + name + ".model");

      var elemSelects = $('

').attr('ng-switch', "record." + name + ".model");
      var elemItems = _.map(selectionList, function(s) {
        return $('<input ui-json-ref-item ng-switch-when="' + s.value +'">')
          .attr('ng-model', 'record.' + name)
          .attr('name', name)
          .attr('x-target', s.value);
      });

      elemGroup
        .append($('

').append(elemSelect))
        .append(elemSelects.append(elemItems));

      return ViewService.compile(elemGroup)($scope);
    };
  }],

  link: function(scope, element, attrs, model) {
    this._super.apply(this, arguments);

    var name = scope.field.name;
    var selectionList = scope.field.selectionList;

    scope.fieldsCache = {};

    scope.refFireEvent = function (name) {
      var handler = scope.$events[name];
      if (handler) {
        return handler();
      }
    };

    var elem = scope.createElement(element.attr('id'), name, selectionList);
    setTimeout(function() {
      element.append(elem);
    });

    scope.$watch("record." + name + ".model", function jsonModelWatch(value, old) {
      if (value === old || old === undefined) return;
      if (scope.record && scope.record[name]) {
        scope.record[name] = _.pick(scope.record[name], 'model');
        if (!scope.record[name].model) {
          delete scope.record[name];
        }
      }
    });
  },
  template_editable: null,
  template_readonly: null
});

ui.formInput('JsonRefItem', 'ManyToOne', {

  showTitle: false,

  link: function(scope, element, attrs, model) {
    this._super.apply(this, arguments);

    if (scope.field.targetName) {
      return this._link.apply(this, arguments);
    }

    var self = this;
    var target = element.attr('x-target');
    var data = (_.findWhere(scope.$parent.field.selectionList, {value: target})||{}).data || {};

    function doLink(fields) {
      var name = false,
        search = [];

      _.each(fields, function(f) {
        if (f.nameColumn) name = f.name;
        if (f.name === "name") search.push("name");
        if (f.name === "code") search.push("code");
      });

      if (!name && _.contains(search, "name")) {
        name = "name";
      }

      _.extend(scope.field, {
        target: scope._model,
        targetName: name,
        targetSearch: search,
        domain: data.domain
      });

      self._link(scope, element, attrs, model);
    }

    if (scope.fieldsCache[scope._model]) {
      doLink(scope.fieldsCache[scope._model]);
    } else {
      scope.loadFields().success(function (fields) {
        scope.fieldsCache[scope._model] = fields;
        doLink(fields);
      });
    }
  },

  _link: function(scope, element, attrs, model) {
    var name = element.attr('name');

    scope.getValue = function () {
      return scope.record[name];
    }

    var __setValue = scope.setValue;

    scope.setValue = function (value) {
      var val = _.pick(scope.record[name], 'model');
      val = _.extend(val, value);
      __setValue.call(scope, val);
    }

    function doSelect() {
      var value = (scope.record || {})[name];
      scope.select(value);
    }

    scope.$watch("record", doSelect);
  }
});

})();
<|endoftext|>


<commit_before>Pebble.addEventListener("ready",
  function(e) {
  }
);
Pebble.addEventListener('showConfiguration',
  function(e) {
    Pebble.openURL('http://scootaloo.com/pebble_pony_config.html');
  }
);
Pebble.addEventListener('webviewclosed',
  function(e) {
    if (e.response == "true") {
      Pebble.sendAppMessage({"0": 1});
    } else {
      Pebble.sendAppMessage({"0": 0});
    }
  }
);
<commit_msg>fix for settings not working<commit_after>Pebble.addEventListener("ready",
  function(e) {
  }
);
Pebble.addEventListener('showConfiguration',
  function(e) {
    Pebble.openURL('http://scootaloo.com/pebble_pony_config.html');
  }
);
Pebble.addEventListener('webviewclosed',
  function(e) {
    if (e.response.substr(-4) == "true") {
      Pebble.sendAppMessage({"0": 1});
    } else {
      Pebble.sendAppMessage({"0": 0});
    }
  }
);
<|endoftext|>