text:
'use strict';

Object.defineProperty(exports, "__esModule", {
	value: true
});

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

exports.confirmTimeZoneExistsThenStartPingFlow = confirmTimeZoneExistsThenStartPingFlow;
exports.askForPingTime = askForPingTime;
exports.queuePing = queuePing;
exports.sendGroupPings = sendGroupPings;

var _index = require('../index');

var _momentTimezone = require('moment-timezone');

var _momentTimezone2 = _interopRequireDefault(_momentTimezone);

var _models = require('../../../app/models');

var _models2 = _interopRequireDefault(_models);

var _lodash = require('lodash');

var _lodash2 = _interopRequireDefault(_lodash);

var _constants = require('../../lib/constants');

var _messageHelpers = require('../../lib/messageHelpers');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

/**
 * 		PING CONVERSATION FLOW FUNCTIONS
 */

function confirmTimeZoneExistsThenStartPingFlow(convo) {
	var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'One more thing! Since I help you make time for your priorities, I need to know your *timezone* before we set our first focus session';
	var _convo$pingObject = convo.pingObject;
	var SlackUserId = _convo$pingObject.SlackUserId;
	var UserId = _convo$pingObject.UserId;
	var tz = _convo$pingObject.tz;

	if (tz) {
		// user has tz config'd
		startPingFlow(convo); // entry point
		convo.next();
	} else {
		// user needs tz config'd!
		convo.ask({
			text: text,
			attachments: _constants.timeZoneAttachments
		}, function (response, convo) {
			var text = response.text;

			var timeZoneObject = false;
			switch (text) {
				case (text.match(_constants.utterances.eastern) || {}).input:
					timeZoneObject = _constants.timeZones.eastern;
					break;
				case (text.match(_constants.utterances.central) || {}).input:
					timeZoneObject = _constants.timeZones.central;
					break;
				case (text.match(_constants.utterances.mountain) || {}).input:
					timeZoneObject = _constants.timeZones.mountain;
					break;
				case (text.match(_constants.utterances.pacific) || {}).input:
					timeZoneObject = _constants.timeZones.pacific;
					break;
				case (text.match(_constants.utterances.other) || {}).input:
					timeZoneObject = _constants.timeZones.other;
					break;
				default:
					break;
			}

			if (!timeZoneObject) {
				convo.say("I didn't get that :thinking_face:");
				confirmTimeZoneExistsThenStartPingFlow(convo, 'Which timezone are you in?');
				convo.next();
			} else if (timeZoneObject == _constants.timeZones.other) {
				convo.say('Sorry!');
				convo.say("Right now I'm only able to work in these timezones. If you want to demo Toki, just pick one of these timezones for now. I'll try to get your timezone included as soon as possible!");
				confirmTimeZoneExistsThenStartPingFlow(convo, 'Which timezone do you want to go with for now?');
				convo.next();
			} else {
				(function () {
					// success!!

					var _timeZoneObject = timeZoneObject;
					var tz = _timeZoneObject.tz;

					console.log(timeZoneObject);
					_models2.default.User.update({
						tz: tz
					}, {
						where: { id: UserId }
					}).then(function (user) {
						convo.say('Great! If this ever changes, you can always `update settings`');
						convo.pingObject.tz = tz;
						startPingFlow(convo); // entry point
						convo.next();
					});
				})();
			}
		});
	}
}

function startPingFlow(convo) {
	var _convo$pingObject2 = convo.pingObject;
	var SlackUserId = _convo$pingObject2.SlackUserId;
	var tz = _convo$pingObject2.tz;
	var pingSlackUserIds = _convo$pingObject2.pingSlackUserIds;

	if (pingSlackUserIds) {
		handlePingSlackUserIds(convo);
	} else {
		askWhoToPing(convo);
	}
}

function askWhoToPing(convo) {
	var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Who would you like to ping? You can type their username, like `@emily`';
	var _convo$pingObject3 = convo.pingObject;
	var SlackUserId = _convo$pingObject3.SlackUserId;
	var tz = _convo$pingObject3.tz;
	var pingSlackUserIds = _convo$pingObject3.pingSlackUserIds;

	var attachments = [{
		attachment_type: 'default',
		callback_id: "WHO_TO_PING",
		fallback: "Who would you like to ping?",
		actions: [{
			name: _constants.buttonValues.neverMind.name,
			text: 'Never Mind!',
			value: _constants.buttonValues.neverMind.value,
			type: 'button'
		}]
	}];

	convo.ask({
		text: text,
		attachments: attachments
	}, [{
		pattern: _constants.utterances.noAndNeverMind,
		callback: function callback(response, convo) {
			convo.say('Ok! Just let me know if you want to ping someone on your team'); // in future check if in session
			convo.pingObject.neverMind = true;
			convo.next();
		}
	}, {
		default: true,
		callback: function callback(response, convo) {
			var text = response.text;

			var pingSlackUserIds = (0, _messageHelpers.getUniqueSlackUsersFromString)(text);

			if (pingSlackUserIds.length > 0) {

				convo.pingObject.pingSlackUserIds = pingSlackUserIds;
				handlePingSlackUserIds(convo);
			} else {
				askWhoToPing(convo, 'Whoops! Try *typing @ + the first few letters of the intended recipient\u2019s first name*, like `@matt` , then clicking on the correct recipient');
			}

			convo.next();
		}
	}]);
}

function handlePingSlackUserIds(convo) {
	var _convo$pingObject4 = convo.pingObject;
	var SlackUserId = _convo$pingObject4.SlackUserId;
	var tz = _convo$pingObject4.tz;
	var bot = _convo$pingObject4.bot;
	var pingSlackUserIds = _convo$pingObject4.pingSlackUserIds;

	if (pingSlackUserIds) {
		(function () {

			var pingSlackUserId = pingSlackUserIds[0];
			convo.pingObject.pingSlackUserId = pingSlackUserId;

			_models2.default.User.find({
				where: { SlackUserId: pingSlackUserId }
			}).then(function (user) {

				if (user) {
					var SlackName = user.SlackName;
					var _id = user.id;

					convo.pingObject.pingUserId = _id;

					// we will only handle 1
					if (pingSlackUserIds.length > 1) {
						convo.say('Hey! Right now I only handle one recipient DM, so I\'ll be helping you with <@' + user.dataValues.SlackUserId + '>. Feel free to queue another message right after this!');
					}

					// user found, handle the ping flow!
					user.getSessions({
						where: ['"open" = ?', true],
						order: '"Session"."createdAt" DESC'
					}).then(function (sessions) {

						var session = sessions[0];

						if (session) {
							// queue the message
							var _session$dataValues = session.dataValues;
							var content = _session$dataValues.content;
							var endTime = _session$dataValues.endTime;

							var now = (0, _momentTimezone2.default)().tz(tz);
							var endTimeObject = (0, _momentTimezone2.default)(endTime).tz(tz);
							var endTimeString = endTimeObject.format("h:mma");
							var minutesLeft = Math.round(_momentTimezone2.default.duration(endTimeObject.diff(now)).asMinutes());

							convo.say('<@' + user.dataValues.SlackUserId + '> is working on `' + content + '` until *' + endTimeString + '*');
							convo.pingObject.userInSession = {
								user: user,
								endTimeObject: endTimeObject
							};
							askForQueuedPingMessages(convo);
						} else {
							// send the message
							convo.pingObject.deliveryType = _constants.constants.pingDeliveryTypes.sessionNotIn;
							// let's just not ping here
							convo.say(' ');
							convo.next();
						}
					});
				} else {
					// could not find user

					bot.api.users.info({ user: pingSlackUserId }, function (err, response) {
						if (!err) {
							var _response$user = response.user;
							var _id2 = _response$user.id;
							var team_id = _response$user.team_id;
							var name = _response$user.name;
							var _tz = _response$user.tz;

							var email = user.profile && user.profile.email ? user.profile.email : '';
							_models2.default.User.create({
								TeamId: team_id,
								email: email,
								tz: _tz,
								SlackUserId: _id2,
								SlackName: name
							}).then(function () {
								handlePingSlackUserIds(convo);
							});
						} else {
							convo.say('Sorry, I can\'t recognize that user!');
							askWhoToPing(convo);
						}
					});
				}

				convo.next();
			});
		})();
	} else {
		startPingFlow(convo);
	}
}

function askForQueuedPingMessages(convo) {
	var _convo$pingObject5 = convo.pingObject;
	var SlackUserId = _convo$pingObject5.SlackUserId;
	var bot = _convo$pingObject5.bot;
	var tz = _convo$pingObject5.tz;
	var userInSession = _convo$pingObject5.userInSession;
	var pingMessages = _convo$pingObject5.pingMessages;

	if (userInSession) {
		(function () {
			// we gathered appropriate info about user
			var user = userInSession.user;
			var endTimeObject = userInSession.endTimeObject;

			var endTimeString = endTimeObject.format("h:mma");
			var now = (0, _momentTimezone2.default)().tz(tz);
			var minutesLeft = Math.round(_momentTimezone2.default.duration(endTimeObject.diff(now)).asMinutes());

			var askMessage = 'What would you like me to send <@' + user.dataValues.SlackUserId + '> at ' + endTimeString + '?';

			var attachments = [{
				text: "Enter as many lines as you'd like to include in the message then choose one of the send options when your message is ready to go\n(These few lines will delete after you type your first line and hit Enter :wink:)",
				attachment_type: 'default',
				callback_id: "PING_MESSAGE_LIST",
				mrkdwn_in: ["text"],
				fallback: "What is the message you want to queue up?"
			}];
			var fullAttachmentActions = [{
				name: _constants.buttonValues.sendAtEndOfSession.name,
				text: 'Send at ' + endTimeString,
				value: 'Send at ' + endTimeString,
				type: 'button'
			}, {
				name: _constants.buttonValues.sendSooner.name,
				text: 'Send sooner :bomb:',
				value: _constants.buttonValues.sendSooner.value,
				type: 'button'
			}, {
				name: _constants.buttonValues.neverMind.name,
				text: 'Never mind!',
				value: _constants.buttonValues.neverMind.value,
				type: 'button'
			}];

			var actions = void 0;
			if (pingMessages && pingMessages.length > 0) {
				attachments[0].text = pingMessages[0];
				attachments[0].color = _constants.colorsHash.toki_purple.hex;
				askMessage = 'What else would you like to send to <@' + user.dataValues.SlackUserId + '> at *' + endTimeString + '*? When done, press one of the buttons!';
				actions = fullAttachmentActions;
			} else {
				actions = [{
					name: _constants.buttonValues.neverMind.name,
					text: 'Never mind!',
					value: _constants.buttonValues.neverMind.value,
					type: 'button'
				}];
			}

			var actionsAttachment = {
				attachment_type: 'default',
				callback_id: "SEND_PING_TO_USER",
				fallback: 'When do you want to send this ping?',
				actions: actions
			};
			attachments.push(actionsAttachment);

			convo.ask({
				text: askMessage,
				attachments: attachments
			}, [{
				pattern: _constants.utterances.noAndNeverMind,
				callback: function callback(response, convo) {
					convo.pingObject.neverMind = true;
					convo.say('Okay! I didn\'t deliver that message');
					convo.next();
				}
			}, {
				pattern: _constants.utterances.containsSendAt,
				callback: function callback(response, convo) {

					convo.pingObject.pingMessages = pingMessages;

					var text = '';

					// if date here, pre-fill it
					var customTimeObject = (0, _messageHelpers.witTimeResponseToTimeZoneObject)(response, tz);
					if (customTimeObject) {

						// equal times
						var customTimeString = customTimeObject.format("h:mma");

						if (customTimeString == endTimeString) {
							// sessionEnd ping
							convo.pingObject.deliveryType = _constants.constants.pingDeliveryTypes.sessionEnd;
							convo.say('Thank you for being mindful of <@' + user.dataValues.SlackUserId + '>\u2019s attention :raised_hands:');
							convo.say('I\u2019ll send your message at *' + customTimeString + '*! :mailbox_with_mail:');
							convo.next();
						} else {

							if (now < customTimeObject && customTimeObject < endTimeObject) {
								// grenade ping
								convo.pingObject.pingTimeObject = customTimeObject;
								convo.pingObject.deliveryType = _constants.constants.pingDeliveryTypes.grenade;
								convo.say('Excellent! I\u2019ll be sending your message to <@' + user.dataValues.SlackUserId + '> at *' + customTimeObject.format("h:mma") + '* :mailbox_with_mail:');
							} else {
								// invalid time for grenade ping
								var minutesBuffer = Math.round(minutesLeft / 4);
								now = (0, _momentTimezone2.default)().tz(tz);
								var exampleEndTimeObjectOne = now.add(minutesBuffer, 'minutes');
								now = (0, _momentTimezone2.default)().tz(tz);
								var exampleEndTimeObjectTwo = now.add(minutesLeft - minutesBuffer, 'minutes');
								convo.say('The time has to be between now and ' + endTimeString + '. You can input times like `' + exampleEndTimeObjectOne.format("h:mma") + '` or `' + exampleEndTimeObjectTwo.format("h:mma") + '`');
								text = "When would you like to send your urgent message?";
							}

							askForPingTime(convo, text);
							convo.next();
						}
					}
				}
			}, {
				pattern: _constants.utterances.sendSooner,
				callback: function callback(response, convo) {

					convo.pingObject.pingMessages = pingMessages;

					askForPingTime(convo);
					convo.next();
				}
			}, {
				default: true,
				callback: function callback(response, convo) {

					pingMessages.push(response.text);

					var pingMessageListUpdate = (0, _messageHelpers.getMostRecentMessageToUpdate)(response.channel, bot, "PING_MESSAGE_LIST");
					if (pingMessageListUpdate) {

						attachments[0].pretext = askMessage;
						attachments[0].text = pingMessages.length == 1 ? '' + response.text : attachments[0].text + '\n' + response.text;
						attachments[0].color = _constants.colorsHash.toki_purple.hex;
						attachments[attachments.length - 1].actions = fullAttachmentActions;

						pingMessageListUpdate.attachments = JSON.stringify(attachments);
						bot.api.chat.update(pingMessageListUpdate);
					}
				}
			}]);
		})();
	} else {
		startPingFlow(convo);
	}
}

function askForPingTime(convo) {
	var text = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
	var _convo$pingObject6 = convo.pingObject;
	var SlackUserId = _convo$pingObject6.SlackUserId;
	var bot = _convo$pingObject6.bot;
	var tz = _convo$pingObject6.tz;
	var pingTimeObject = _convo$pingObject6.pingTimeObject;
	var pingSlackUserId = _convo$pingObject6.pingSlackUserId;
	var userInSession = _convo$pingObject6.userInSession;

	// if user is in a session and you have not set what time you want to ping yet

	if (!pingTimeObject && userInSession) {
		(function () {
			var user = userInSession.user;
			var endTimeObject = userInSession.endTimeObject;

			var now = (0, _momentTimezone2.default)().tz(tz);
			var minutesLeft = Math.round(_momentTimezone2.default.duration(endTimeObject.diff(now)).asMinutes());
			var exampleEndTimeObject = void 0;
			if (minutesLeft > 10) {
				exampleEndTimeObject = now.add(minutesLeft - 10, 'minutes');
			} else {
				exampleEndTimeObject = now.add(Math.round(minutesLeft / 2), 'minutes');
			}

			var exampleEndTimeString = exampleEndTimeObject.format("h:mma");
			var endTimeString = endTimeObject.format("h:mma");

			if (text == '') {
				text = 'Would you like to send this urgent message now, or at a specific time before ' + endTimeString + '? If it\u2019s the latter, just tell me the time, like `' + exampleEndTimeString + '`';
			}

			var attachments = [{
				attachment_type: 'default',
				callback_id: "PING_GRENADE",
				fallback: "When do you want to ping?",
				actions: [{
					name: _constants.buttonValues.now.name,
					text: 'Now :bomb:',
					value: _constants.buttonValues.now.value,
					type: 'button'
				}]
			}];

			convo.ask({
				text: text,
				attachments: attachments
			}, [{
				pattern: _constants.utterances.containsNow,
				callback: function callback(response, convo) {
					// send now
					convo.pingObject.deliveryType = _constants.constants.pingDeliveryTypes.bomb;
					convo.say(':point_left: Got it! I\'ll send your message to <@' + user.dataValues.SlackUserId + '> :runner: :pencil:');
					convo.next();
				}
			}, {
				default: true,
				callback: function callback(response, convo) {

					var customTimeObject = (0, _messageHelpers.witTimeResponseToTimeZoneObject)(response, tz);
					if (customTimeObject) {
						now = (0, _momentTimezone2.default)().tz(tz);
						if (now < customTimeObject && customTimeObject < endTimeObject) {
							// success!
							convo.pingObject.pingTimeObject = customTimeObject;
							convo.pingObject.deliveryType = _constants.constants.pingDeliveryTypes.grenade;
							convo.say('Excellent! I\u2019ll be sending your message to <@' + user.dataValues.SlackUserId + '> at *' + customTimeObject.format("h:mma") + '* :mailbox_with_mail:');
						} else {
							// has to be less than or equal to end time
							var minutesBuffer = Math.round(minutesLeft / 4);
							now = (0, _momentTimezone2.default)().tz(tz);
							var exampleEndTimeObjectOne = now.add(minutesBuffer, 'minutes');
							now = (0, _momentTimezone2.default)().tz(tz);
							var exampleEndTimeObjectTwo = now.add(minutesLeft - minutesBuffer, 'minutes');
							convo.say('The time has to be between now and ' + endTimeString + '. You can input times like `' + exampleEndTimeObjectOne.format("h:mma") + '` or `' + exampleEndTimeObjectTwo.format("h:mma") + '`');
							askForPingTime(convo, "When would you like to send your urgent message?");
						}
					} else {

						convo.say('I didn\'t quite get that :thinking_face:');
						convo.repeat();
					}

					convo.next();
				}
			}]);
		})();
	}

	convo.next();
}

/**
 *
 * This handles logic of queueing ping depending on session info
 * if no session, then this will not store ping in DB and will just immediately send over
 *
 * @param  {bot} bot      requires bot of TeamId
 * @param  {UserId, SlackUserId} fromUserConfig
 * @param  {UserId, SlackUserId} toUserConfig
 * @param  {deliveryType, pingTimeObject, pingMessages } config   [description]
 */
function queuePing(bot, fromUserConfig, toUserConfig, config) {
	var pingTimeObject = config.pingTimeObject;
	var pingMessages = config.pingMessages;
	var deliveryType = config.deliveryType;

	if (!deliveryType) deliveryType = _constants.constants.pingDeliveryTypes.sessionEnd; // default to sessionEnd ping

	var SlackUserIds = fromUserConfig.SlackUserId + ',' + toUserConfig.SlackUserId;

	_models2.default.User.find({
		where: { SlackUserId: toUserConfig.SlackUserId }
	}).then(function (toUser) {

		if (toUser) {

			// user found, handle the ping flow!
			toUser.getSessions({
				where: ['"open" = ?', true],
				order: '"Session"."createdAt" DESC'
			}).then(function (sessions) {

				var session = sessions[0];

				if (session) {

					_models2.default.Ping.create({
						FromUserId: fromUserConfig.UserId,
						ToUserId: toUserConfig.UserId,
						deliveryType: deliveryType,
						pingTime: pingTimeObject
					}).then(function (ping) {
						if (pingMessages) {
							pingMessages.forEach(function (pingMessage) {
								_models2.default.PingMessage.create({
									PingId: ping.id,
									content: pingMessage
								});
							});
						}
					});
				} else {

					// user is not in a session!
					deliveryType = _constants.constants.pingDeliveryTypes.sessionNotIn;
					_models2.default.Ping.create({
						FromUserId: fromUserConfig.UserId,
						ToUserId: toUserConfig.UserId,
						deliveryType: deliveryType,
						pingTime: pingTimeObject
					}).then(function (ping) {
						if (pingMessages) {
							pingMessages.forEach(function (pingMessage) {
								_models2.default.PingMessage.create({
									PingId: ping.id,
									content: pingMessage
								});
							});
						}
					});
				}
			});
		} else {

			bot.startPrivateConversation({ user: fromUserConfig.SlackUserId }, function (err, convo) {

				// could not find user, let's create
				bot.api.users.info({ user: toUserConfig.SlackUserId }, function (err, response) {

					if (!err) {
						(function () {
							var _response$user2 = response.user;
							var id = _response$user2.id;
							var team_id = _response$user2.team_id;
							var name = _response$user2.name;
							var tz = _response$user2.tz;

							var email = user.profile && user.profile.email ? user.profile.email : '';
							_models2.default.User.create({
								TeamId: team_id,
								email: email,
								tz: tz,
								SlackUserId: id,
								SlackName: name
							}).then(function () {
								convo.say('For some reason, i didn\'t have <@' + id + '> in my database, but now I do! Thank you. Try sending this ping again :pray:');
							});
						})();
					} else {
						convo.say('Sorry, I can\'t recognize <@' + id + '>!');
					}
				});

				convo.next();
			});
		}
	});
}

// handle batch of pings with specific FromUser ToUser combination
function sendGroupPings(pings, deliveryType) {

	// first fill up both configs and make sure it is valid
	var config = fillPingUserConfig(pings);
	var handleNow = false;
	var now = (0, _momentTimezone2.default)();

	pings.some(function (ping) {
		var _ping$dataValues = ping.dataValues;
		var FromUserId = _ping$dataValues.FromUserId;
		var ToUserId = _ping$dataValues.ToUserId;
		var deliveryType = _ping$dataValues.deliveryType;
		var pingTime = _ping$dataValues.pingTime;

		if (pingTime) {
			var pingTimeObject = (0, _momentTimezone2.default)(pingTime);
			if (pingTimeObject < now) {
				handleNow = true;
				return handleNow;
			}
		} else {
			handleNow = true;
		}
	});

	// this means pings are valid
	if (handleNow && config) {
		var _ret6 = function () {

			var fromUserConfig = config.fromUser;
			var toUserConfig = config.toUser;

			var SlackUserIds = fromUserConfig.SlackUserId + ',' + toUserConfig.SlackUserId;

			_models2.default.Team.find({
				where: { TeamId: fromUserConfig.TeamId }
			}).then(function (team) {
				var token = team.token;

				var bot = _index.bots[token];

				if (bot) {
					bot.api.mpim.open({
						users: SlackUserIds
					}, function (err, response) {

						if (!err) {
							var _id3 = response.group.id;

							bot.startConversation({ channel: _id3 }, function (err, convo) {

								var initialMessage = 'Hey <@' + toUserConfig.SlackUserId + '>! <@' + fromUserConfig.SlackUserId + '> wanted to reach out';
								switch (deliveryType) {
									case _constants.constants.pingDeliveryTypes.bomb:
										initialMessage = 'Hey <@' + toUserConfig.SlackUserId + '>! <@' + fromUserConfig.SlackUserId + '> has an urgent message for you:';
										break;
									case _constants.constants.pingDeliveryTypes.grenade:
										initialMessage = 'Hey <@' + toUserConfig.SlackUserId + '>! <@' + fromUserConfig.SlackUserId + '> has an urgent message for you:';
										break;
									case _constants.constants.pingDeliveryTypes.sessionNotIn:
										initialMessage = 'Hey <@' + toUserConfig.SlackUserId + '>! You\'re not in a session and <@' + fromUserConfig.SlackUserId + '> wanted to reach out :raised_hands:';
									default:
										break;
								}

								// IM channel successfully opened with these 2 users
								if (pings.length == 1) {

									var ping = pings[0];

									initialMessage = '*' + initialMessage + '*';
									var pingMessagesContentAttachment = (0, _messageHelpers.getPingMessageContentAsAttachment)(ping);

									convo.say({
										text: initialMessage,
										attachments: pingMessagesContentAttachment
									});
								} else {

									// these need to happen one at a time

									var groupedPingMessagesAttachment = (0, _messageHelpers.getGroupedPingMessagesAsAttachment)(pings);

									convo.say({
										text: initialMessage,
										attachments: groupedPingMessagesAttachment
									});
								}
							});
						}
					});
				}
			});
			return {
				v: true
			};
		}();

		if ((typeof _ret6 === 'undefined' ? 'undefined' : _typeof(_ret6)) === "object") return _ret6.v;
	} else {
		return false;
	}
}

// this fills up fromUserConfig and toUserConfig based on batched pings
// if it is invalid, returns false
// invalid if: FromUserId is inconsistent, ToUserId is inconsistent, TeamId does not match
function fillPingUserConfig(pings) {

	var config = { fromUser: {}, toUser: {} };

	var valid = true;
	pings.forEach(function (ping) {
		var _ping$dataValues2 = ping.dataValues;
		var FromUser = _ping$dataValues2.FromUser;
		var ToUser = _ping$dataValues2.ToUser;

		var FromUserId = FromUser.dataValues.id;
		var FromUserSlackUserId = FromUser.dataValues.SlackUserId;
		var FromUserTeamId = FromUser.dataValues.TeamId;

		var ToUserId = ToUser.dataValues.id;
		var ToUserSlackUserId = ToUser.dataValues.SlackUserId;
		var ToUserTeamId = ToUser.dataValues.TeamId;

		/*
   *  Fill UserIds
   */
		if (!config.fromUser.UserId) {
			config.fromUser.UserId = FromUserId;
		} else if (config.fromUser.UserId != FromUserId) {
			valid = false;
		}

		if (!config.toUser.UserId) {
			config.toUser.UserId = ToUserId;
		} else if (config.toUser.UserId != ToUserId) {
			valid = false;
		}

		/*
   *  Fill SlackUserIds
   */
		if (!config.fromUser.SlackUserId) {
			config.fromUser.SlackUserId = FromUserSlackUserId;
		} else if (config.fromUser.SlackUserId != FromUserSlackUserId) {
			valid = false;
		}

		if (!config.toUser.SlackUserId) {
			config.toUser.SlackUserId = ToUserSlackUserId;
		} else if (config.toUser.SlackUserId != ToUserSlackUserId) {
			valid = false;
		}

		/*
   *  Fill TeamIds
   */
		if (!config.fromUser.TeamId) {
			config.fromUser.TeamId = FromUserTeamId;
		} else if (config.fromUser.TeamId != FromUserTeamId) {
			valid = false;
		}

		if (!config.toUser.TeamId) {
			config.toUser.TeamId = ToUserTeamId;
		} else if (config.toUser.TeamId != ToUserTeamId) {
			valid = false;
		}

		if (config.fromUser.TeamId != config.toUser.TeamId) {
			valid = false;
		}
	});

	if (pings.length == 0) {
		valid = false;
	}

	if (valid) {
		return config;
	} else {
		return false;
	}
}
//# sourceMappingURL=pingFunctions.js.map


text:
+ (className *)shared##className;

// @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [super allocWithZone:zone]; \
    }); \
    return _instance; \
} \
+ (className *)shared##className \
{ \
    static dispatch_once_t onceToken; \
    dispatch_once(&onceToken, ^{ \
        _instance = [[self alloc] init]; \
    }); \
    return _instance; \
}
//@interface
//#define singleton_iterface(classname)\
//+(className *)shared##className;
////@implementation
//#define sigleton_implementation(className)\
//static className *_instance;\
//+(id)allocWithZone:(NSZone*)zone\
//{\
//     static dispatch_once_t onceToken;\
//      dispatch_once(&onceToken,^{\
//          })\;
//        \
//}\

redpajama_set_name: RedPajamaGithub


text:
'use strict';

/**
 * Includes Universal Analytics tracking code and provides method for sending data
 *
 * Does not track anything automatically
 */
define(function() {

	// formatted GA isogram
	(function(i, s, o, g, r, a, m) {
		i.GoogleAnalyticsObject = r;
		i[r] = i[r] || function() {
			(i[r].q = i[r].q || []).push(arguments);
		};
		i[r].l = 1 * new Date();
		a = s.createElement(o);
		m = s.getElementsByTagName(o)[0];
		a.async = 1;
		a.src = g;
		m.parentNode.insertBefore(a, m);
	})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');

	window.ga('create', 'UA-16968457-1', 'auto');
	window.ga('set', 'checkProtocolTask', function(){});

	/**
	 * @param {...*}
	 */
	function send() {
		if (localStorage.disableGa == 1) {
			return;
		}

		var args = Array.prototype.slice.call(arguments, 0);
		args.unshift('send');
		window.ga.apply(window, args);
	}

	/**
	 * @param {...*}
	 */
	function event() {
		if (localStorage.disableGa == 1) {
			return;
		}

		var args = Array.prototype.slice.call(arguments, 0);
		args.unshift('event');
		send.apply(window, args);
	}

	return {
		send: send,
		event: event
	};
});


text:
<?php
namespace app\web\util\Codes;
        /**
         *@AUTHOR: Prachi
         *@REASON: use code instead of id
         */
class LookupTypeCodes{
CONST LT_USER_ROLES = 1;
CONST LT_USER_TYPE = 2;
CONST LT_APP_CONFIGURATIONS = 3;
CONST LT_SYSTEM_OPERATIONS = 4;
CONST LT_DEVICETYPE = 5;
CONST LT_SOCIAL_LOGINS = 6;
CONST LT_EMAIL_STATUS = 7;
CONST LT_GENDER = 8;
CONST LT_MARITAL_STATUS = 9;
CONST LT_COMMON_STATUS = 10;
CONST LT_PERMISSION_TYPES = 11;
CONST LT_TEST1 = 12;
CONST LT_TEST2 = 13;
CONST LT_AUTO_GENERATE = 14;
CONST LT_CONFIGURATION_SECTION = 15;
CONST LT_MAIL_METHOD = 16;
CONST LT_DEVICE_TOKEN_OPTIONS = 17;
CONST LT_EMAIL_TEMPLATES = 18;
CONST LT_USER_STATUS = 19;
CONST LT_LANGUGAGE = 20;
CONST LT_DISPLAY_DATE_FORMAT = 21;
CONST LT_MULTIPLE_DEVICE_OPTIONS = 22;
CONST LT_CMS_CATEGORY = 23;
CONST LT_CMS_SUB_CATEGORY = 24;
CONST LT_CMS_LAYOUT = 25;
CONST LT_CMS_CHILD_CATEGORY = 26;
CONST LT_CMS_FOURTH_SUB_CAT = 27;
CONST LT_PERMISSION_DISPLAY_OPTIONS = 28;
CONST LT_E_MAIL_SENDER = 29;
CONST LT_PUSH_NOTIFICATION_SCREEN = 30;
}
?>


text:
<?php

namespace Drupal\contact;

use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Language\LanguageManagerInterface;
use Drupal\Core\Mail\MailManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a class for handling assembly and dispatch of contact mail messages.
 */
class MailHandler implements MailHandlerInterface {

  use StringTranslationTrait;

  /**
   * Language manager service.
   *
   * @var \Drupal\Core\Language\LanguageManagerInterface
   */
  protected $languageManager;

  /**
   * Logger service.
   *
   * @var \Drupal\Core\Logger\LoggerChannelInterface
   */
  protected $logger;

  /**
   * Mail manager service.
   *
   * @var \Drupal\Core\Mail\MailManagerInterface
   */
  protected $mailManager;

  /**
   * The user entity storage handler.
   *
   * @var \Drupal\Core\Entity\EntityStorageInterface
   */
  protected $userStorage;

  /**
   * Constructs a new \Drupal\contact\MailHandler object.
   *
   * @param \Drupal\Core\Mail\MailManagerInterface $mail_manager
   *   Mail manager service.
   * @param \Drupal\Core\Language\LanguageManagerInterface $language_manager
   *   Language manager service.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
   *   String translation service.
   * @param \Drupal\Core\Entity\EntityManagerInterface $entity_manager
   *   Entity manager service.
   */
  public function __construct(MailManagerInterface $mail_manager, LanguageManagerInterface $language_manager, LoggerInterface $logger, TranslationInterface $string_translation, EntityManagerInterface $entity_manager) {
    $this->languageManager = $language_manager;
    $this->mailManager = $mail_manager;
    $this->logger = $logger;
    $this->stringTranslation = $string_translation;
    $this->userStorage = $entity_manager->getStorage('user');
  }

  /**
   * {@inheritdoc}
   */
  public function sendMailMessages(MessageInterface $message, AccountInterface $sender) {
    // Clone the sender, as we make changes to mail and name properties.
    $sender_cloned = clone $this->userStorage->load($sender->id());
    $params = [];
    $current_langcode = $this->languageManager->getCurrentLanguage()->getId();
    $recipient_langcode = $this->languageManager->getDefaultLanguage()->getId();
    $contact_form = $message->getContactForm();

    if ($sender_cloned->isAnonymous()) {
      // At this point, $sender contains an anonymous user, so we need to take
      // over the submitted form values.
      $sender_cloned->name = $message->getSenderName();
      $sender_cloned->mail = $message->getSenderMail();

      // For the email message, clarify that the sender name is not verified; it
      // could potentially clash with a username on this site.
      $sender_cloned->name = $this->t('@name (not verified)', ['@name' => $message->getSenderName()]);
    }

    // Build email parameters.
    $params['contact_message'] = $message;
    $params['sender'] = $sender_cloned;

    if (!$message->isPersonal()) {
      // Send to the form recipient(s), using the site's default language.
      $params['contact_form'] = $contact_form;

      $to = implode(', ', $contact_form->getRecipients());
    }
    elseif ($recipient = $message->getPersonalRecipient()) {
      // Send to the user in the user's preferred language.
      $to = $recipient->getEmail();
      $recipient_langcode = $recipient->getPreferredLangcode();
      $params['recipient'] = $recipient;
    }
    else {
      throw new MailHandlerException('Unable to determine message recipient');
    }

    // Send email to the recipient(s).
    $key_prefix = $message->isPersonal() ? 'user' : 'page';
    $this->mailManager->mail('contact', $key_prefix . '_mail', $to, $recipient_langcode, $params, $sender_cloned->getEmail());

    // If requested, send a copy to the user, using the current language.
    if ($message->copySender()) {
      $this->mailManager->mail('contact', $key_prefix . '_copy', $sender_cloned->getEmail(), $current_langcode, $params, $sender_cloned->getEmail());
    }

    // If configured, send an auto-reply, using the current language.
    if (!$message->isPersonal() && $contact_form->getReply()) {
      // User contact forms do not support an auto-reply message, so this
      // message always originates from the site.
      if (!$sender_cloned->getEmail()) {
        $this->logger->error('Error sending auto-reply, missing sender e-mail address in %contact_form', [
          '%contact_form' => $contact_form->label(),
        ]);
      }
      else {
        $this->mailManager->mail('contact', 'page_autoreply', $sender_cloned->getEmail(), $current_langcode, $params);
      }
    }

    if (!$message->isPersonal()) {
      $this->logger->notice('%sender-name (@sender-from) sent an email regarding %contact_form.', [
        '%sender-name' => $sender_cloned->getUsername(),
        '@sender-from' => $sender_cloned->getEmail(),
        '%contact_form' => $contact_form->label(),
      ]);
    }
    else {
      $this->logger->notice('%sender-name (@sender-from) sent %recipient-name an email.', [
        '%sender-name' => $sender_cloned->getUsername(),
        '@sender-from' => $sender_cloned->getEmail(),
        '%recipient-name' => $message->getPersonalRecipient()->getUsername(),
      ]);
    }
  }

}


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--
    Licensed to the Apache Software Foundation (ASF) under one or more
    contributor license agreements.  See the NOTICE file distributed with
    this work for additional information regarding copyright ownership.
    The ASF licenses this file to You under the Apache License, Version 2.0
    (the "License"); you may not use this file except in compliance with
    the License.  You may obtain a copy of the License at

         http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-->

<!--
    Ignite Spring configuration file to startup grid cache.
-->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">
    <bean id="grid.cfg" class="org.apache.ignite.configuration.IgniteConfiguration">
        <property name="localHost" value="127.0.0.1"/>
        <property name="connectorConfiguration"><null/></property>

        <property name="cacheConfiguration">
            <list>
                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="QueryPerson"/>
                    <property name="cacheMode" value="PARTITIONED"/>
                    <property name="atomicityMode" value="TRANSACTIONAL"/>
                    <property name="writeSynchronizationMode" value="FULL_SYNC"/>

                    <property name="affinity">
                        <bean class="org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction">
                            <property name="partitions" value="256"/>
                        </bean>
                    </property>

                    <property name="typeMetadata">
                        <list>
                            <bean class="org.apache.ignite.cache.CacheTypeMetadata">
                                <property name="valueType" value="QueryPerson"/>
                                <property name="ascendingFields">
                                    <map>
                                        <entry key="age" value="java.lang.Integer"/>
                                    </map>
                                </property>
                                <property name="queryFields">
                                    <map>
                                        <entry key="name" value="java.lang.String"/>
                                        <entry key="age" value="java.lang.Integer"/>
                                        <entry key="birthday" value="java.util.Date"/>
                                        <entry key="recordCreated" value="java.sql.Timestamp"/>
                                    </map>
                                </property>
                                <property name="textFields">
                                    <list>
                                        <value>name</value>
                                    </list>
                                </property>
                            </bean>

                            <bean class="org.apache.ignite.cache.CacheTypeMetadata">
                                <property name="valueType" value="QueryRelation"/>
                                <property name="queryFields">
                                    <map>
                                        <entry key="personId" value="java.lang.Integer"/>
                                        <entry key="someVal" value="java.lang.Integer"/>
                                    </map>
                                </property>
                            </bean>
                        </list>
                    </property>
                </bean>

                <bean class="org.apache.ignite.configuration.CacheConfiguration">
                    <property name="name" value="QueryRelation"/>
                    <property name="cacheMode" value="PARTITIONED"/>
                    <property name="atomicityMode" value="TRANSACTIONAL"/>
                    <property name="writeSynchronizationMode" value="FULL_SYNC"/>

                    <property name="affinity">
                        <bean class="org.apache.ignite.cache.affinity.rendezvous.RendezvousAffinityFunction">
                            <property name="partitions" value="256"/>
                        </bean>
                    </property>

                    <property name="typeMetadata">
                        <list>
                            <bean class="org.apache.ignite.cache.CacheTypeMetadata">
                                <property name="valueType" value="QueryRelation"/>
                                <property name="queryFields">
                                    <map>
                                        <entry key="personId" value="java.lang.Integer"/>
                                        <entry key="someVal" value="java.lang.Integer"/>
                                    </map>
                                </property>
                            </bean>
                        </list>
                    </property>
                </bean>
            </list>
        </property>

        <property name="discoverySpi">
            <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
                <property name="ipFinder">
                    <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
                        <property name="addresses">
                            <list>
                                <!-- In distributed environment, replace with actual host IP address. -->
                                <value>127.0.0.1:47500</value>
                            </list>
                        </property>
                    </bean>
                </property>
                <property name="socketTimeout" value="300" />
            </bean>
        </property>
    </bean>
</beans>


text:
package net.firejack.platform.core.config.meta.diff;

import net.firejack.platform.core.config.meta.IEntityElement;
import net.firejack.platform.core.config.meta.IIndexElement;

public class IndexesDiff extends PackageDescriptorElementDiff<IEntityElement, IIndexElement> {

    /**
     * @param type
     * @param targetParent
     * @param upgradeTarget
     */
    public IndexesDiff(DifferenceType type, IEntityElement targetParent, IIndexElement upgradeTarget) {
        super(type, targetParent, upgradeTarget);
    }

    /**
     * @param targetParent
     * @param oldIndex
     * @param newIndex
     */
    public IndexesDiff(IEntityElement targetParent, IIndexElement oldIndex, IIndexElement newIndex) {
        super(DifferenceType.UPDATED, targetParent, oldIndex, newIndex);
    }

}


text:
import React from 'react';
import Message from './Message';

const Messages = props => {
  return (
    <div className="Messages">
      {props.messages.map(
        (msg, idx) =>
          props.hideVoted && msg.voted
            ? ''
            : <Message
                showVote={props.showVote}
                key={msg.user['tmi-sent-ts'] + msg.user['user-id']}
                message={msg.text}
                user={msg.user}
                channel={msg.channel}
                onLikeMsg={msg => props.onLikeMsg(msg, idx)}
                onDislikeMsg={msg => props.onDislikeMsg(msg, idx)}
              />
      )}
    </div>
  );
};

export default Messages;


text:
<?php
namespace Bootstrap\Console\Make;

use Bootstrap\Console\SlayerCommand;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class ConsoleCommand extends SlayerCommand
{
    protected $name = 'make:console';

    protected $description = 'Generate a new console';

    public function slash()
    {
        $arg_name = ucfirst($this->input->getArgument('name'));

        $stub = file_get_contents(__DIR__ . '/stubs/makeConsole.stub');
        $stub = str_replace('{consoleName}', $arg_name, $stub);

        $file_name = $arg_name . 'Command.php';
        chdir(config()->path->console);
        $this->comment('Crafting Console...');

        if (file_exists($file_name)) {
            $this->error('   Console already exists!');
        } else {
            file_put_contents($file_name, $stub);
            $this->info('   Console has been created!');
        }
    }

    protected function arguments()
    {
        return [
            ['name', InputArgument::REQUIRED, 'Console name to be used'],
        ];
    }

}


text:
<?php

namespace SF;

/*
 * This file is part of the SimpleFramework
 *
 * (c) Jules Boussekeyt <jules.boussekeyt@gmail.com>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

class Logger
{
    const DEBUG     = 'debug';
    const WARNING   = 'warn';
    const ERROR     = 'error';
    const CRITICAL  = 'crit';

    private $logFile;

    public function __construct($logFile)
    {
        if (!file_exists($logFile)) {
            touch($logFile);
        }

        $this->logFile = $logFile;
    }

    public function log($message, $type = self::DEBUG)
    {
        $f = fopen($this->logFile, 'a');
        fwrite($f, static::format($message, $type));
        fclose($f);
    }

    protected static function format($message, $type)
    {
        return sprintf("[%s](%s) %s\n", date('Y/m/d H:i:s'), $type, $message);
    }
}


text:
import * as Lint from "../../index";

// tslint:disable: object-literal-sort-keys
export const codeExamples = [
    {
        description: "Check that referenced variables are declared beforehand (default)",
        config: Lint.Utils.dedent`
            "rules": { "no-use-before-declare": true }
        `,
        pass: Lint.Utils.dedent`
            var hello = 'world';
            var foo;

            console.log(hello, foo, capitalize(hello));
            // 'world', undefined, 'WORLD'

            function capitalize(val) {
                return val.toUpperCase();
            }

            import { default as foo1 } from "./lib";
            import foo2 from "./lib";
            import _, { map, foldl } from "./underscore";
            import * as foo3 from "./lib";
            import "./lib";

            function declaredImports() {
                console.log(foo1);
                console.log(foo2);
                console.log(foo3);
                map([], (x) => x);
            }
        `,
        fail: Lint.Utils.dedent`
            console.log(hello, foo);

            var hello = 'world';
            var foo;

            function undeclaredImports() {
                console.log(foo1);
                console.log(foo2);
                console.log(foo3);
                map([], (x) => x);
            }

            import { default as foo1 } from "./lib";
            import foo2 from "./lib";
            import _, { map, foldl } from "./underscore";
            import * as foo3 from "./lib";
            import "./lib";
        `,
    },
];


text:
var number_types = ["bigint", "int8", "bigserial", "serial8", "double precision", "float8",
        "integer", "int", "int4", "real", "float4", "smallint", "int2", "serial", "serial4"];

var PostgresTypes = function() {
  var that = {};
  that.is_numeric = function(type) {
    return number_types.indexOf(type) !== -1;
  };

  that.can_apply = function(agg, type) {
    agg = agg.toLowerCase();
    if (agg === "sum" || agg === "avg") {
      return that.is_numeric(type);
    }
    return true;
  };
  return that;
};

module.exports = PostgresTypes;


text:
package org.terasology.logic.audio;

import org.lwjgl.openal.AL10;
import org.lwjgl.openal.AL11;
import org.terasology.game.Terasology;
import org.terasology.logic.manager.AudioManager;

import javax.vecmath.Vector3d;

import static org.lwjgl.openal.AL10.*;

public class BasicSoundSource implements SoundSource {

    protected AbstractSound audio;
    protected int sourceId;

    protected float srcGain = 1.0f;
    protected float targetGain = 1.0f;
    protected boolean fade = false;

    protected Vector3d position = new Vector3d();
    protected Vector3d velocity = new Vector3d();
    protected Vector3d direction = new Vector3d();

    protected boolean absolutePosition = false;

    protected boolean _playing = false;

    public BasicSoundSource() {
        this.sourceId = alGenSources();
        OpenALException.checkState("Creating sound source");

        this.reset();
    }

    public BasicSoundSource(AbstractSound audio) {
        this();

        this.setAudio(audio);
    }

    public SoundSource play() {
        if (!isPlaying()) {
            AL10.alSourcePlay(this.getSourceId());
            _playing = true;
        }

        return this;
    }

    public SoundSource stop() {
        if (this.audio != null) {
            this.audio.reset();
        }

        alSourceStop(this.getSourceId());

        OpenALException.checkState("Rewind");

        alSourceRewind(this.getSourceId());

        OpenALException.checkState("Stop playback");

        _playing = false;

        return this;
    }

    public SoundSource pause() {
        if (isPlaying()) {
            AL10.alSourcePause(this.getSourceId());

            OpenALException.checkState("Pause playback");

            _playing = false;
        }

        return this;
    }

    public boolean isPlaying() {
        return (alGetSourcei(this.sourceId, AL_SOURCE_STATE) == AL_PLAYING) || _playing;
    }

    public void update() {
        this.updateFade();

        if (this.absolutePosition) {
            updatePosition(this.position);
        }

        this.updateState();
    }

    protected void updateState() {
        if (_playing && alGetSourcei(this.sourceId, AL_SOURCE_STATE) != AL_PLAYING) {
            _playing = false; // sound stop playing
        }
    }

    public SoundSource reset() {
        this.setPitch(1.0f);
        this.setLooping(false);
        this.setGain(1.0f);
        this.setAbsolute(false);

        Vector3d zeroVector = new Vector3d();
        this.setPosition(zeroVector);
        this.setVelocity(zeroVector);
        this.setDirection(zeroVector);

        // some additional settings
        alSourcef(this.getSourceId(), AL_MAX_DISTANCE, AudioManager.MAX_DISTANCE);
        alSourcef(this.getSourceId(), AL_REFERENCE_DISTANCE, 0.1f);

        this.fade = false;
        this.srcGain = 1.0f;
        this.targetGain = 1.0f;

        return this;
    }

    public int getLength() {
        return audio.getLength();
    }

    public SoundSource setPlaybackPosition(int position) {
        boolean playing = isPlaying();
        if (playing) {
            AL10.alSourceStop(this.getSourceId());
        }

        AL10.alSourceRewind(this.getSourceId());
        AL10.alSourcei(this.getSourceId(), AL11.AL_SAMPLE_OFFSET, (this.audio.getSamplingRate() * position));

        OpenALException.checkState("Setting sound playback absolute position");

        if (playing) {
            this.play();
        }

        return this;
    }

    public int getPlaybackPosition() {
        return AL10.alGetSourcei(this.getSourceId(), AL11.AL_SAMPLE_OFFSET) / this.audio.getSamplingRate();
    }

    public SoundSource setPlaybackPosition(float position) {
        boolean playing = isPlaying();
        if (playing) {
            AL10.alSourceStop(this.getSourceId());
        }

        AL10.alSourceRewind(this.getSourceId());
        AL10.alSourcei(this.getSourceId(), AL11.AL_BYTE_OFFSET, (int) (this.audio.getBufferSize() * position));

        OpenALException.checkState("Setting sound playback relaive position");

        if (playing) {
            this.play();
        }

        return this;
    }

    public float getPlaybackPositionf() {
        return AL10.alGetSourcei(this.getSourceId(), AL11.AL_BYTE_OFFSET) / this.audio.getBufferSize();
    }

    public SoundSource setAbsolute(boolean absolute) {
        this.absolutePosition = absolute;

        return this;
    }

    public boolean isAbsolute() {
        return this.absolutePosition;
    }

    public Vector3d getVelocity() {
        return velocity;
    }

    public SoundSource setVelocity(Vector3d velocity) {
        if (velocity == null || this.velocity.equals(velocity)) {
            return this;
        }

        this.velocity.set(velocity);

        AL10.alSource3f(this.getSourceId(), AL10.AL_VELOCITY, (float) velocity.x, (float) velocity.y, (float) velocity.z);

        OpenALException.checkState("Setting sound source velocity");

        return this;
    }

    public Vector3d getPosition() {
        return position;
    }

    public SoundSource setPosition(Vector3d position) {
        if (position == null || this.position.equals(position)) {
            return this;
        }

        this.position.set(position);

        updatePosition(position);

        return this;
    }

    public SoundSource setDirection(Vector3d direction) {
        if (direction == null || this.direction.equals(direction)) {
            return this;
        }

        AL10.alSource3f(this.getSourceId(), AL10.AL_DIRECTION, (float) direction.x, (float) direction.y, (float) direction.z);

        OpenALException.checkState("Setting sound source direction");

        this.direction.set(direction);

        return this;
    }

    public Vector3d getDirection() {
        return direction;
    }

    public float getPitch() {
        return AL10.alGetSourcef(this.getSourceId(), AL10.AL_PITCH);
    }

    public SoundSource setPitch(float pitch) {
        AL10.alSourcef(this.getSourceId(), AL10.AL_PITCH, pitch);

        OpenALException.checkState("Setting sound pitch");

        return this;
    }

    public float getGain() {
        return alGetSourcef(this.getSourceId(), AL_GAIN);
    }

    public SoundSource setGain(float gain) {
        alSourcef(this.getSourceId(), AL_GAIN, gain);

        OpenALException.checkState("Setting sound gain");

        return this;
    }

    public boolean isLooping() {
        return alGetSourcei(this.getSourceId(), AL_LOOPING) == AL_TRUE;
    }

    public SoundSource setLooping(boolean looping) {
        alSourcei(this.getSourceId(), AL_LOOPING, looping ? AL_TRUE : AL_FALSE);

        OpenALException.checkState("Setting sound looping");

        return this;
    }

    public SoundSource setAudio(Sound sound) {
        boolean playing = isPlaying();
        if (playing) {
            this.stop();
        }

        this.reset();

        if (sound instanceof AbstractSound) {
            this.audio = (AbstractSound) sound;
            AL10.alSourcei(this.getSourceId(), AL10.AL_BUFFER, this.audio.getBufferId());

            OpenALException.checkState("Assigning buffer to source");
        } else {
            throw new IllegalArgumentException("Unsupported sound object!");
        }

        if (playing) {
            this.play();
        }

        return this;
    }

    public Sound getAudio() {
        return audio;
    }

    public SoundSource fade(float targetGain) {
        this.srcGain = this.getGain();
        this.targetGain = targetGain;
        this.fade = true;

        return this;
    }

    public int getSourceId() {
        return this.sourceId;
    }

    protected void updatePosition(Vector3d position) {
        float[] pos = new float[]{(float) position.x, (float) position.y, (float) position.z};

        if (this.isAbsolute()) {
            Vector3d cameraPos = this.getCameraPosition();
            pos[0] -= cameraPos.x;
            pos[1] -= cameraPos.y;
            pos[2] -= cameraPos.z;
        }

        alSource3f(this.getSourceId(), AL10.AL_POSITION, pos[0], pos[1], pos[2]);

        OpenALException.checkState("Changing sound position");
    }

    private void updateFade() {
        if (!fade) {
            return;
        }

        float delta = (this.srcGain - this.targetGain) / 100;
        this.setGain(this.getGain() - delta);

        if (this.getGain() >= this.targetGain) {
            if (this.targetGain == 0.0f) {
                this.stop();
            }

            fade = false;
        }
    }

    private Vector3d getCameraPosition() {
        return Terasology.getInstance().getActiveCamera().getPosition();
    }

    @Override
    // TODO: This is no guaranteed to be executed at all – move to a safer place
    protected void finalize() throws Throwable {
        if (this.sourceId != 0) {
            AL10.alDeleteSources(this.sourceId);
        }
        super.finalize();
    }

    @Override
    public int hashCode() {
        return this.getSourceId();
    }

}


text:
// Helper functions to run 3d pooling on GPU using CuDNN.

#ifndef TENSORFLOW_KERNELS_CUDNN_POOLING_GPU_H_
#define TENSORFLOW_KERNELS_CUDNN_POOLING_GPU_H_

#include <array>

#include "tensorflow/core/framework/op_kernel.h"

#if GOOGLE_CUDA
#include "tensorflow/core/platform/stream_executor.h"
#endif

#include "tensorflow/core/util/padding.h"

namespace tensorflow {

#if GOOGLE_CUDA

// Runs (avg/max)pooling on GPU.
// Dimension order for all array arguments is: x, y, z.
template <typename T>
class DnnPooling3dOp {
 public:
  static void Compute(OpKernelContext* context,
                      se::dnn::PoolingMode pooling_mode,
                      const std::array<int64, 3>& size,
                      const std::array<int64, 3>& stride,
                      const std::array<int64, 3>& padding,
                      TensorFormat data_format, const Tensor& tensor_in,
                      Tensor* output);
};

// Computes the gradient of (avg/max)pooling on GPU.
// Dimension order for all array arguments is: x, y, z.
template <typename T>
class DnnPooling3dGradOp {
 public:
  static void Compute(OpKernelContext* context,
                      se::dnn::PoolingMode pooling_mode,
                      const std::array<int64, 3>& window,
                      const std::array<int64, 3>& stride,
                      const std::array<int64, 3>& padding,
                      const std::array<int64, 3>& output_size,
                      TensorFormat data_format, const Tensor& out_backprop,
                      const TensorShape& tensor_in_shape,
                      const Tensor* tensor_in, const Tensor* tensor_out,
                      Tensor* input_backprop);
};

#endif

}  // namespace tensorflow

#endif  // TENSORFLOW_KERNELS_CUDNN_POOLING_GPU_H_


text:
import store from 'fluxed/store';

export default store('repo', {
  active: { owner: null, name: null },
  on: {
    'active-repo-change'(msg) {
      this.setState({ active: msg.repo });
    }
  }
});


text:
package com.wt.studio.plugin.pagedesigner.gef.command;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.ColorConstants;
import org.eclipse.gef.commands.Command;

import com.wt.studio.plugin.pagedesigner.gef.editpart.ColumnConnectionEditPart;
import com.wt.studio.plugin.pagedesigner.gef.editpart.FunctionColumnModelEditPart;
import com.wt.studio.plugin.pagedesigner.gef.figure.FunctionColumnModelFigure;
import com.wt.studio.plugin.pagedesigner.gef.model.ColumnConnection;
import com.wt.studio.plugin.pagedesigner.gef.model.FunctionColumnModel;
import com.wt.studio.plugin.pagedesigner.gef.model.FunctionModel;

public class DeleteConnectionCommand extends Command {

	private FunctionColumnModel source;

	private FunctionColumnModel target;

    private ColumnConnection connection;

	private ColumnConnectionEditPart editPart;

    //Setters
    public void setConnection(ColumnConnection connection) {
        this.connection = connection;
    }

    public void setSource(FunctionColumnModel source) {
        this.source = source;
    }

    public void setTarget(FunctionColumnModel target) {
        this.target = target;
    }

    public void execute() {
    	 FunctionColumnModelEditPart sourcePart=(FunctionColumnModelEditPart) this.editPart.getSource();
         sourcePart.getFigure().setBackgroundColor(ColorConstants.white);
         FunctionColumnModelEditPart targetPart=(FunctionColumnModelEditPart) this.editPart.getTarget();
         targetPart.getFigure().setBackgroundColor(ColorConstants.white);
        source.removeOutput(connection);
        target.removeInput(connection);
        connection.setSource(null);
        connection.setTarget(null);

        }

    public String getLabel() {
        return "Delete Connection";
    }

    public void redo() {
        execute();
    }

    public void undo() {
        connection.setSource(source);
        connection.setTarget(target);
        source.addOutput(connection);
        target.addInput(connection);
    }

	public void setEditPart(ColumnConnectionEditPart part)
	{
		// TODO Auto-generated method stub
		this.editPart=part;
	}
}


text:
class DefaultRequestAccessGroups < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers
  DOWNTIME = false

  def up
    change_column_default :namespaces, :request_access_enabled, false
  end

  def down
    change_column_default :namespaces, :request_access_enabled, true
  end
end


text:
/**
 * Kicks everything off.
 *
 * Created by mjbrooks on 3/15/14.
 */
(function (win) {
    var tf = win.namespace.get('twitter_feels');
    tf.TwitterFeels.initialize();
})(window);


text:
namespace Security.HMAC
{
    using System.Threading.Tasks;
    using Microsoft.Owin;

    public class HmacMiddleware : OwinMiddleware
    {
        private readonly HmacMiddlewareOptions options;

        public HmacMiddleware(OwinMiddleware next, HmacMiddlewareOptions options)
            : base(next)
        {
            this.options = options;
        }

        public override Task Invoke(IOwinContext context)
        {
            if (!RequestTools.Validate(
                context.Request,
                options.Algorithm,
                options.SecretRepository,
                options.Time,
                options.ClockSkew))
            {
                var res = context.Response;
                res.StatusCode = 401;
                res.Headers.Append(Headers.WWWAuthenticate, Schemas.Bearer);

                return Task.CompletedTask;
            }

            return Next.Invoke(context);
        }
    }
}


text:
Some macros and helpers for Clojure protocols and records.

## Maturity

"A work in progress"

## Artifacts

None yet.

### The Most Recent Release

None yet.

## Documentation & Examples

None yet.

## Testing

None yet

## License

Copyright (C) 2014 Ian Rumford.

Licensed under [MIT](http://opensource.org/licenses/MIT)


text:
Check out Carbon (http://get-carbon.org/) for a much more capable powershell automation libary.

Install via nuget (http://nuget.org/List/Packages/PSHostsFile).  Or run .\build.ps1 and use the PSHostsFile.dll.

Powershell:

    import-module .\PSHostsFile.dll

    get-HostsFileEntry
    remove-HostsFileEntry <hostName>
    set-HostsFileEntry <hostName> <Address>

C#:

    using PSHostsFile;

    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                foreach (var hostsEntry in HostsFile.Get())
                {
                    System.Console.WriteLine("Have host {0} - {1}.", hostsEntry.Hostname, hostsEntry.Address);
                }

                HostsFile.Set("foo.example.com", "127.0.0.1");  //  Add or update the hosts file entry for foo.example.com
                HostsFile.Set("another.example.com", "127.0.0.1");
                HostsFile.Remove("another.example.com");  //  Remove a hosts file entry
            }
        }
    }


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
  ~ Copyright (C) 2022 The Android Open Source Project
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~      http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
-->
<resources xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
  <string name="material_timepicker_pm">du.</string>
  <string name="material_timepicker_am">de.</string>
  <string name="material_timepicker_select_time">Időpont kiválasztása</string>
  <string name="material_timepicker_minute">Perc</string>
  <string name="material_timepicker_hour">Óra</string>
  <string name="material_hour_suffix">%1$s óra</string>
  <string name="material_hour_24h_suffix">%1$s óra</string>
  <string name="material_minute_suffix">%1$s perc</string>
  <string name="material_hour_selection">Óra kiválasztása</string>
  <string name="material_minute_selection">Perc kiválasztása</string>
  <string name="material_clock_toggle_content_description">Válassza ki, hogy délelőtt vagy délután</string>
  <string name="mtrl_timepicker_confirm">OK</string>
  <string name="mtrl_timepicker_cancel">Mégse</string>
  <string name="material_timepicker_text_input_mode_description">Időbevitelhez váltson szövegbeviteli módba.</string>
  <string name="material_timepicker_clock_mode_description">Időbevitelhez váltson óramódba.</string>
</resources>


text:
if [ ! -e SheetJSNS ]; then
	tns create SheetJSNS --template nativescript-template-ng-tutorial
	cd SheetJSNS
	tns plugin add nativescript-nodeify
	npm install xlsx
	cd app
	npm install xlsx
	cd ../..
fi

cp ../../dist/xlsx.full.min.js SheetJSNS/
cp ../../dist/xlsx.full.min.js SheetJSNS/app/
cp nsmain.ts  SheetJSNS/app/main.ts
cp nscript.ts SheetJSNS/app/app.component.ts


text:
'use strict';

angular

    .module('softvApp')
    .factory('CatalogosRedIPFactory', function($http, $q, globalService, $localStorage){

        var factory = {};
        var paths = {
            GetCatalogo_IpsList: '/Catalogo_Ips/GetCatalogo_IpsList',
            GetListCatalogo_Ips: '/Catalogo_Ips/GetListCatalogo_Ips',
            GetDeepCatalogo_Ips: '/Catalogo_Ips/GetDeepCatalogo_Ips',
            GetcatalogoIps_dosList: '/catalogoIps_dos/GetcatalogoIps_dosList',
            UpdatecatalogoIps_dos: '/catalogoIps_dos/UpdatecatalogoIps_dos',
            GetDeepcatalogoIps_dos: '/catalogoIps_dos/GetDeepcatalogoIps_dos',
            GetListCombo: '/catalogoIps_dos/GetListCombo',
            GetGeneral_Sistema_II: '/General_Sistema_II/GetGeneral_Sistema_II',
            GetRelRedPlazaList: '/RelRedPlaza/GetRelRedPlazaList',
            GetRelRedPlaza_Inc: '/RelRedPlaza/GetRelRedPlaza_Inc',
            UpdateRelRedPlaza: '/RelRedPlaza/UpdateRelRedPlaza',
            GetRelRedCompaniaList: '/RelRedCompania/GetRelRedCompaniaList',
            GetRelRedCompania_Inc: '/RelRedCompania/GetRelRedCompania_Inc',
            UpdateRelRedCompania: '/RelRedCompania/UpdateRelRedCompania',
            GetRelRedEstado_Dis: '/RelRedEstado/GetRelRedEstado_Dis',
            GetRelRedEstadoList: '/RelRedEstado/GetRelRedEstadoList',
            UpdateRelRedEstado: '/RelRedEstado/UpdateRelRedEstado',
            GetRelRedCiudad_Dis: '/RelRedCiudad/GetRelRedCiudad_Dis',
            GetRelRedCiudadList: '/RelRedCiudad/GetRelRedCiudadList',
            UpdateRelRedCiudad: '/RelRedCiudad/UpdateRelRedCiudad',
            GetRelRedLocalidadList: '/RelRedLocalidad/GetRelRedLocalidadList',
            GetRelRedLocalidad_inc: '/RelRedLocalidad/GetRelRedLocalidad_inc',
            UpdateRelRedLocalidad: '/RelRedLocalidad/UpdateRelRedLocalidad',
            GetRelRedMedioList: '/RelRedMedio/GetRelRedMedioList',
            GetRelRedMedio_Inc: '/RelRedMedio/GetRelRedMedio_Inc',
            UpdateRelRedMedio: '/RelRedMedio/UpdateRelRedMedio',
            GetCatMedioByCiuLocCol: '/CatMedios/GetCatMedioByCiuLocCol',
            Get_ActivaIP: '/General_Sistema_II/Get_ActivaIP',
            GetCatalogoIPByCliente: '/catalogoIps_dos/GetCatalogoIPByCliente',
            GetAdd_RelServicioIPTem: '/catalogoIps_dos/GetAdd_RelServicioIPTem'

        };

        factory.GetCatalogo_IpsList = function (ObjRedIP) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjRedIP;
            $http.post(globalService.getUrl() + paths.GetCatalogo_IpsList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetListCatalogo_Ips = function (ObjRedList) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjRedList;
            $http.post(globalService.getUrl() + paths.GetListCatalogo_Ips, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetDeepCatalogo_Ips = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetDeepCatalogo_Ips, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetcatalogoIps_dosList = function (ObjIPList) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjIPList;
            $http.post(globalService.getUrl() + paths.GetcatalogoIps_dosList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdatecatalogoIps_dos = function (objcatalogoIps_dos) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros =  {'objcatalogoIps_dos':objcatalogoIps_dos };
            $http.post(globalService.getUrl() + paths.UpdatecatalogoIps_dos, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetDeepcatalogoIps_dos = function (IdIp) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdIP': IdIp};
            $http.post(globalService.getUrl() + paths.GetDeepcatalogoIps_dos, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetListCombo = function () {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            $http.get(globalService.getUrl() + paths.GetListCombo, config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetGeneral_Sistema_II = function () {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            $http.get(globalService.getUrl() + paths.GetGeneral_Sistema_II, config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedPlazaList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedPlazaList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedPlaza_Inc = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedPlaza_Inc, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedPlaza = function (objRelRedPlaza) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedPlaza': objRelRedPlaza};
            $http.post(globalService.getUrl() + paths.UpdateRelRedPlaza, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedCompaniaList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedCompaniaList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedCompania_Inc = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedCompania_Inc, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedCompania = function (objRelRedCompania) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedCompania': objRelRedCompania};
            $http.post(globalService.getUrl() + paths.UpdateRelRedCompania, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedEstado_Dis = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedEstado_Dis, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedEstadoList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedEstadoList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedEstado = function (objRelRedEstado) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedEstado': objRelRedEstado};
            $http.post(globalService.getUrl() + paths.UpdateRelRedEstado, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedCiudad_Dis = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedCiudad_Dis, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedCiudadList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedCiudadList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedCiudad = function (objRelRedCiudad) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedCiudad': objRelRedCiudad};
            $http.post(globalService.getUrl() + paths.UpdateRelRedCiudad, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedLocalidadList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedLocalidadList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedLocalidad_inc = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedLocalidad_inc, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedLocalidad = function (objRelRedLocalidad) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedLocalidad': objRelRedLocalidad};
            $http.post(globalService.getUrl() + paths.UpdateRelRedLocalidad, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedMedioList = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedMedioList, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetRelRedMedio_Inc = function (IdRed) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'IdRed': IdRed};
            $http.post(globalService.getUrl() + paths.GetRelRedMedio_Inc, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.UpdateRelRedMedio = function (objRelRedMedio) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = {'objRelRedMedio': objRelRedMedio};
            $http.post(globalService.getUrl() + paths.UpdateRelRedMedio, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetCatMedioByCiuLocCol = function (ObjListMedio) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjListMedio;
            $http.post(globalService.getUrl() + paths.GetCatMedioByCiuLocCol, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.Get_ActivaIP = function () {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            $http.get(globalService.getUrl() + paths.Get_ActivaIP, config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetCatalogoIPByCliente = function (ObjIpList) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjIpList;
            $http.post(globalService.getUrl() + paths.GetCatalogoIPByCliente, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        factory.GetAdd_RelServicioIPTem = function (ObjSerIp) {
            var deferred = $q.defer();
            var config = {headers: {'Authorization': $localStorage.currentUser.token}};
            var Parametros = ObjSerIp;
            $http.post(globalService.getUrl() + paths.GetAdd_RelServicioIPTem, JSON.stringify(Parametros), config).then(function (response) {
                deferred.resolve(response.data);
            }).catch(function (response) {
                deferred.reject(response);
            });
            return deferred.promise;
        };

        return factory;

    });


text:
from base import Struct
import os.path as op

##
# 16.06.2005, c
class Reader( Struct ):
    """
    Reads and executes a Python file as a script with execfile(), storing its
    locals. Then sets the __dict__ of a new instance of obj_class to the stored
    locals.

    Example:

    >>> class A:
    >>>    pass

    >>> read = Reader( '.' )
    >>> instance_of_a = read( A, 'file.py' )

    It is equivalent to:

    >>> mod = __import__( 'file' )
    >>> instance_of_a = A()
    >>> instance_of_a.__dict__.update( mod.__dict__ )

    The first way does not create the 'file.pyc'...
    """
    ##
    # 16.06.2005, c
    def __init__( self, directory ):
        self.directory = directory

    ##
    # 16.06.2005, c
    # 17.10.2005
    # 09.02.2006
    def __call__( self, obj_class, name ):
        filename = op.join( self.directory, name + '.py' )

        aux = {}
        execfile( filename, {}, aux )

        obj = obj_class()
        for key, val in aux.iteritems():
            obj.__dict__[key] = val

        return obj


text:
@echo ON
rem ==============Build Project======================
ng build -prod


text:
#include "AfxConsole.h"

#include <sstream>

namespace advancedfx {

void Printf_Null(const char* fmt, ...)
{

}

void DevPrintf_Null(int, const char* fmt, ...)
{

}

Con_Printf_t Message = Printf_Null;
Con_Printf_t Warning = Printf_Null;

Con_DevPrintf_t DevMessage = DevPrintf_Null;
Con_DevPrintf_t DevWarning = DevPrintf_Null;

// CSubCommandArgs /////////////////////////////////////////////////////////////

CSubCommandArgs::CSubCommandArgs(ICommandArgs* commandArgs, int offset)
	: m_Offset(offset)
	, m_CommandArgs(commandArgs)
{
	std::ostringstream oss;

	for (int i = 0; i < m_Offset; ++i)
	{
		if (0 < i)
			oss << " ";
		oss << m_CommandArgs->ArgV(i);
	}

	m_Prefix = oss.str();
}

int CSubCommandArgs::ArgC()
{
	return m_CommandArgs->ArgC() - m_Offset + 1;
}

char const* CSubCommandArgs::ArgV(int i)
{
	if (0 == i)
	{
		return m_Prefix.c_str();
	}

	return m_CommandArgs->ArgV(i + m_Offset - 1);
}

} // namespace advancedfx {


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Closterandra minor Boiv.

### Remarks
null


text:
<button
    class="page-toggle-button {{'active' if active_page == 'profile' }}"
    data-action="viewprofile"
>
    Profile
</button>
<button
    class="page-toggle-button {{'active' if active_page == 'account' }}"
    data-action="viewaccount"
>
    Account
</button>
<button
        class="page-toggle-button {{'active' if active_page == 'linkedAccounts' }}"
        data-action="viewlinkedaccounts"
>
    Linked Accounts
</button>