commit stringlengths 40 40 | subject stringlengths 1 3.25k | old_file stringlengths 4 311 | new_file stringlengths 4 311 | old_contents stringlengths 0 26.3k | lang stringclasses 3
values | proba float64 0 1 | diff stringlengths 0 7.82k |
|---|---|---|---|---|---|---|---|
6503d008b490134c4dc8962a688990f56e859154 | update stuff when inserting a character | static/seriously.js | static/seriously.js | var cp437 = {};
cp437.codepage = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "
cp437.encode = function(codePoint) {
return cp437.codepage.charAt(codePoint);
}
cp437.decode = function(c) {
return cp437.codepage.indexOf(c);
}
function genChar() {
var code = prompt("Generate CP437 Character:");
if(!code)
return;
$('#code').val($('#code').val() + cp437.encode(parseInt(code)));
updateByteCount();
};
function getByteCount(s) {
var count = 0, stringLength = s.length;
s = String(s || "");
for (var i = 0; i < stringLength; i++) {
var partCount = encodeURI(s[i]).split("%").length;
count += partCount == 1 ? 1 : partCount - 1;
}
return count;
}
function updateByteCount() {
var c = $('#code').val();
var byteCount = c.length;
var charCount = c.length;
var s = byteCount + " bytes and " + charCount + " chars long.";
$('#byteCount').html(s);
}
function getExplanation() {
var string = false;
var codeBlock = false;
var listBlock = false;
var numBlock = false;
var code = $('#code').val();
var explain = '';
for(var x=0; x < code.length; x++) {
var c = code.charAt(x);
if(c === '"') {
if(string) {
var prev = code.lastIndexOf('"',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the string value "'+strval+'"\r\n'
}
string = !string;
continue;
} else if(c === '`') {
if(codeBlock) {
var prev = code.lastIndexOf('`',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the function value `'+strval+'`\r\n'
}
codeBlock = !codeBlock;
continue;
} else if(c === '[') {
listBlock = true;
continue;
} else if(c === ':') {
if(numBlock) {
var prev = code.lastIndexOf(':',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the numeric value "'+strval+'"\r\n'
}
numBlock = !numBlock;
continue;
} else if(c === ']') {
listBlock = false;
var prev = code.lastIndexOf('[',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the list value "'+strval+'"\r\n'
continue;
}
if(codeBlock || string || listBlock || numBlock) {
continue;
}
if(cp437.decode(c) > -1)
explain += explanations[cp437.decode(c)] +'\r\n';
}
if(string) {
var prev = code.lastIndexOf('"',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the string value "'+strval+'"\r\n'
} else if(codeBlock) {
var prev = code.lastIndexOf('"',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the function value `'+strval+'`\r\n'
} else if(listBlock) {
var prev = code.lastIndexOf('[',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the list value "'+strval+'"\r\n'
} else if(numBlock) {
var prev = code.lastIndexOf(':',x-1);
var strval = code.slice(prev+1,x);
explain += 'push the numeric value "'+strval+'"\r\n'
}
$('#explanation').html(explain);
}
function updateHexDump() {
var hex = '';
var code = $('#code').val();
for(var i = 0; i < code.length; i++) {
hex += cp437.decode(code.charAt(i)).toString(16);
}
$('#hexdump').val(hex);
}
function updateUtils() {
updateByteCount();
getExplanation();
updateHexDump();
}
function utf8_to_b64(str) {
return window.btoa(unescape(encodeURIComponent(str)));
}
function b64_to_utf8(str) {
return decodeURIComponent(escape(window.atob(str)));
}
updateUtils();
$(document).ready(
function() {
$("#permalink").click(
function() {
var code = encodeURIComponent(utf8_to_b64(window.JSON.stringify({
code : $('#code').val(),
input : $('#input').val()
})));
prompt("Permalink:", "http://"
+ window.location.hostname + "/link/" + code);
window.location.pathname = "/link/" + code;
});
$('#code').on('input propertychange paste', function() {
updateUtils();
});
$('#hexdump').on('input propertychange paste', function() {
updateUtils();
});
$("input").keypress(function(e){
var charCode = !e.charCode ? e.which : e.charCode;
var c = String.fromCharCode(charCode);
if(cp437.decode(c) < 0)
e.preventDefault();
});
}); | JavaScript | 0 | @@ -779,33 +779,29 @@
%0D%0A update
-ByteCount
+Utils
();%0D%0A%7D;%0D%0A%0D%0Af
@@ -3946,13 +3946,17 @@
+var
hex
+i
-+
= cp
@@ -3993,24 +3993,92 @@
tring(16);%0D%0A
+ if(hexi.length %3C 2) hexi = %220%22 + hexi;%0D%0A hex+=hexi;%0D%0A
%7D%0D%0A $
|
89ac6e8548eb57891589fa36b339a09b5066b5e1 | use $sessionStorage to save the last filters used in the screen | Frontend-Ng1/www/app/podcasts/podcasts.js | Frontend-Ng1/www/app/podcasts/podcasts.js | /**
* Created by kevin on 25/10/2015 for PodcastServer
*/
import {Component, Module} from '../decorators';
import {TitleService} from '../common/service/title.service';
import AppRouteConfig from '../config/route';
import PodcastService from '../common/service/data/podcastService';
import TypeService from '../common/service/data/typeService';
import PodcastDetailsModule from './details/details';
import PodcastCreationModule from './creation/creation';
import template from './podcasts.html!text';
import './podcasts.css!';
@Module({
name : 'ps.podcasts',
modules : [PodcastCreationModule, PodcastDetailsModule, PodcastService, AppRouteConfig, TypeService, TitleService]
})
@Component({
selector : 'podcasts',
as : 'plc',
template : template,
path : '/podcasts',
resolve: {
podcasts: (podcastService) => {"ngInject"; return podcastService.findAll(); },
types: typeService => {"ngInject"; return typeService.findAll(); }
}
})
export default class PodcastsListCtrl {
constructor(TitleService) {
"ngInject";
this.filters = { title : '', type : '' };
TitleService.title = 'Podcasts';
}
}
| JavaScript | 0 | @@ -1011,13 +1011,72 @@
istC
-trl %7B
+omponent %7B%0A%0A static defaultFilters = %7B title: '', type: '' %7D;
%0A%0A
@@ -1101,16 +1101,33 @@
eService
+, $sessionStorage
) %7B%0A
@@ -1159,84 +1159,388 @@
his.
-filters = %7B title : '', type : '' %7D;%0A TitleService.title = 'Podcasts'
+$sessionStorage = $sessionStorage;%0A this.TitleService = TitleService;%0A %7D%0A%0A $onInit()%7B%0A TitleService.title = 'Podcasts';%0A this.filters = PodcastsListComponent.defaultFilters;%0A %7D%0A%0A get filters() %7B%0A return this.$sessionStorage.podcasts;%0A %7D%0A%0A set filters(val) %7B%0A this.$sessionStorage.podcasts = this.$sessionStorage.podcasts %7C%7C val
;%0A
|
6603e39e6a643223b9659331c5d0724aad09d50b | Fix SYWEB-109 : No error if HS rejects the username in registration. | webclient/login/register-controller.js | webclient/login/register-controller.js | /*
Copyright 2014 OpenMarket Ltd
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.
*/
angular.module('RegisterController', ['matrixService'])
.controller('RegisterController', ['$scope', '$rootScope', '$location', 'matrixService', 'eventStreamService',
function($scope, $rootScope, $location, matrixService, eventStreamService) {
'use strict';
var config = window.webClientConfig;
var useCaptcha = true;
if (config !== undefined) {
useCaptcha = config.useCaptcha;
}
// FIXME: factor out duplication with login-controller.js
// Assume that this is hosted on the home server, in which case the URL
// contains the home server.
var hs_url = $location.protocol() + "://" + $location.host();
if ($location.port() &&
!($location.protocol() === "http" && $location.port() === 80) &&
!($location.protocol() === "https" && $location.port() === 443))
{
hs_url += ":" + $location.port();
}
var generateClientSecret = function() {
var ret = "";
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 32; i++) {
ret += chars.charAt(Math.floor(Math.random() * chars.length));
}
return ret;
};
$scope.account = {
homeserver: hs_url,
desired_user_id: "",
desired_user_name: "",
password: "",
identityServer: "http://matrix.org:8090",
pwd1: "",
pwd2: "",
displayName : ""
};
$scope.register = function() {
// Set the urls
matrixService.setConfig({
homeserver: $scope.account.homeserver,
identityServer: $scope.account.identityServer
});
if ($scope.account.pwd1 !== $scope.account.pwd2) {
$scope.feedback = "Passwords don't match.";
return;
}
else if ($scope.account.pwd1.length < 6) {
$scope.feedback = "Password must be at least 6 characters.";
return;
}
if ($scope.account.email) {
$scope.clientSecret = generateClientSecret();
matrixService.linkEmail($scope.account.email, $scope.clientSecret, 1).then(
function(response) {
$scope.wait_3pid_code = true;
$scope.sid = response.data.sid;
$scope.feedback = "";
},
function(response) {
$scope.feedback = "Couldn't request verification email!";
}
);
} else {
$scope.registerWithMxidAndPassword($scope.account.desired_user_id, $scope.account.pwd1);
}
};
$scope.registerWithMxidAndPassword = function(mxid, password, threepidCreds) {
matrixService.register(mxid, password, threepidCreds, useCaptcha).then(
function(response) {
$scope.feedback = "Success";
if (useCaptcha) {
Recaptcha.destroy();
}
// Update the current config
var config = matrixService.config();
angular.extend(config, {
access_token: response.data.access_token,
user_id: response.data.user_id
});
matrixService.setConfig(config);
// And permanently save it
matrixService.saveConfig();
// Update the global scoped used_id var (used in the app header)
$rootScope.updateHeader();
eventStreamService.resume();
if ($scope.account.displayName) {
// FIXME: handle errors setting displayName
matrixService.setDisplayName($scope.account.displayName);
}
// Go to the user's rooms list page
$location.url("home");
},
function(error) {
console.trace("Registration error: "+error);
if (useCaptcha) {
Recaptcha.reload();
}
if (error.data) {
if (error.data.errcode === "M_USER_IN_USE") {
$scope.feedback = "Username already taken.";
$scope.reenter_username = true;
}
else if (error.data.errcode == "M_CAPTCHA_INVALID") {
$scope.feedback = "Failed captcha.";
}
else if (error.data.errcode == "M_CAPTCHA_NEEDED") {
$scope.feedback = "Captcha is required on this home " +
"server.";
}
}
else if (error.status === 0) {
$scope.feedback = "Unable to talk to the server.";
}
});
}
$scope.verifyToken = function() {
matrixService.authEmail($scope.clientSecret, $scope.sid, $scope.account.threepidtoken).then(
function(response) {
if (!response.data.success) {
$scope.feedback = "Unable to verify code.";
} else {
$scope.registerWithMxidAndPassword($scope.account.desired_user_id, $scope.account.pwd1, [{'sid':$scope.sid, 'clientSecret':$scope.clientSecret, 'idServer': $scope.account.identityServer.split('//')[1]}]);
}
},
function(error) {
$scope.feedback = "Unable to verify code.";
}
);
};
var setupCaptcha = function() {
console.log("Setting up ReCaptcha")
var config = window.webClientConfig;
var public_key = undefined;
if (config === undefined) {
console.error("Couldn't find webClientConfig. Cannot get public key for captcha.");
}
else {
public_key = webClientConfig.recaptcha_public_key;
if (public_key === undefined) {
console.error("No public key defined for captcha!")
}
}
Recaptcha.create(public_key,
"regcaptcha",
{
theme: "red",
callback: Recaptcha.focus_response_field
});
};
$scope.init = function() {
if (useCaptcha) {
setupCaptcha();
}
};
}]);
| JavaScript | 0 | @@ -5351,32 +5351,163 @@
%7D%0A
+ else if (error.data.error) %7B%0A $scope.feedback = error.data.error;%0A %7D%0A
|
196b1746e17241d764f35d67d257da8b0c111a7c | Disable errors in Ace Editor | public/visifile_drivers/ui_components/editorComponent.js | public/visifile_drivers/ui_components/editorComponent.js | function component( args ) {
/*
base_component_id("editorComponent")
load_once_from_file(true)
*/
//alert(JSON.stringify(args,null,2))
var uid = uuidv4()
var uid2 = uuidv4()
var mm = Vue.component(uid, {
data: function () {
return {
text: args.text,
uid2: uid2
}
},
template: `<div>
<div v-bind:id='uid2' ></div>
<hr />
<slot :text2="text"></slot>
</div>`
,
mounted: function() {
var mm = this
var editor = ace.edit( uid2, {
mode: "ace/mode/javascript",
selectionStyle: "text"
})
document.getElementById(uid2).style.width="100%"
document.getElementById(uid2).style.height="45vh"
editor.getSession().setValue(mm.text);
editor.getSession().on('change', function() {
mm.text = editor.getSession().getValue();
//alert("changed text to : " + mm.text)
});
},
methods: {
getText: function() {
return this.text
}
}
})
return {
name: uid
}
}
| JavaScript | 0.000001 | @@ -985,16 +985,67 @@
.text);%0A
+ editor.getSession().setUseWorker(false);%0A%0A
%0A
|
569c7be28dda43e7e383a69276ce7750a51dbc96 | Fix linting errors | config/ember-try.js | config/ember-try.js | const getChannelURL = require('ember-source-channel-url');
module.exports = async function() {
return {
useYarn: true,
scenarios: [
{
name: 'ember-lts-3.16',
npm: {
devDependencies: {
'ember-source': '~3.16.10'
}
}
},
{
name: 'ember-lts-3.20',
npm: {
devDependencies: {
'ember-source': '~3.20.7'
}
}
},
{
name: 'ember-lts-3.24',
npm: {
devDependencies: {
'ember-source': '~3.24.3'
}
}
},
{
name: 'ember-lts-3.28',
npm: {
devDependencies: {
'ember-source': '~3.28.8'
}
}
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-source': await getChannelURL('release')
}
}
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-source': await getChannelURL('beta')
}
}
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-source': await getChannelURL('canary'),
},
},
},
{
name: 'ember-classic',
env: {
EMBER_OPTIONAL_FEATURES: JSON.stringify({
'application-template-wrapper': true,
'default-async-observers': false,
'template-only-glimmer-components': false
})
},
npm: {
devDependencies: {
'ember-source': '~3.28.8'
},
ember: {
edition: 'classic'
}
}
}
]
};
};
| JavaScript | 0.000075 | @@ -1228,17 +1228,16 @@
canary')
-,
%0A
@@ -1232,33 +1232,32 @@
ry')%0A %7D
-,
%0A %7D,%0A
@@ -1246,25 +1246,24 @@
%7D%0A %7D
-,
%0A %7D,%0A
|
720db848537010fb2e636e3bf7432186228aef19 | fix typo in ember-try config for lts 2.4 | config/ember-try.js | config/ember-try.js | /*jshint node:true*/
module.exports = {
scenarios: [
{
name: 'default',
bower: {
devDependencies: { }
},
npm: {
devDependencies: { }
}
},
{
name: 'ember-lts-2-4',
bower: {
devDependencies: {
'ember': 'components/ember#lts-2-4'
},
resolutions: {
'ember': 'lts-2-4'
}
},
npm: {
devDependencies: {
'ember-data': '2.4.3'
},
resolutions: {
'ember-data': '2.4.3'
}
}
},
{
name: 'ember-release',
bower: {
devDependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
npm: {
devDependencies: {
'ember-data': 'emberjs/data#release'
},
resolutions: {
'ember-data': 'release'
}
}
},
{
name: 'ember-beta',
allowedToFail: true,
bower: {
devDependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
npm: {
devDependencies: {
'ember-data': 'emberjs/data#beta'
},
resolutions: {
'ember-data': 'beta'
}
}
},
{
name: 'ember-canary',
allowedToFail: true,
bower: {
devDependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
},
npm: {
devDependencies: {
'ember-data': 'emberjs/data#master'
},
resolutions: {
'ember-data': 'master'
}
}
}
]
};
| JavaScript | 0.000004 | @@ -218,17 +218,17 @@
er-lts-2
--
+.
4',%0A
|
cb86c82dbcc7316fcd5e3da512cc38c63a11fc0d | Drop Ember 2.16 from Ember try matrix | config/ember-try.js | config/ember-try.js | 'use strict';
const getChannelURL = require('ember-source-channel-url');
const { embroiderSafe, embroiderOptimized } = require('@embroider/test-setup');
module.exports = async function () {
return {
useYarn: true,
scenarios: [
{
name: 'ember-lts-2.16',
npm: {
devDependencies: {
'ember-source': 'lts',
},
},
},
{
name: 'ember-lts-3.20',
npm: {
devDependencies: {
'ember-source': '~3.20.5',
},
},
},
{
name: 'ember-lts-3.24',
npm: {
devDependencies: {
'ember-source': '~3.24.3',
},
},
},
{
name: 'ember-release',
npm: {
devDependencies: {
'ember-source': await getChannelURL('release'),
},
},
},
{
name: 'ember-beta',
npm: {
devDependencies: {
'ember-source': await getChannelURL('beta'),
},
},
},
{
name: 'ember-canary',
npm: {
devDependencies: {
'ember-source': await getChannelURL('canary'),
},
},
},
{
name: 'ember-classic',
env: {
EMBER_OPTIONAL_FEATURES: JSON.stringify({
'application-template-wrapper': true,
'default-async-observers': false,
'template-only-glimmer-components': false,
}),
},
npm: {
devDependencies: {
'ember-source': '~3.28.0',
},
ember: {
edition: 'classic',
},
},
},
embroiderSafe(),
embroiderOptimized(),
],
};
};
| JavaScript | 0 | @@ -244,160 +244,8 @@
%7B%0A
- name: 'ember-lts-2.16',%0A npm: %7B%0A devDependencies: %7B%0A 'ember-source': 'lts',%0A %7D,%0A %7D,%0A %7D,%0A %7B%0A
|
59ac7ddc43a41dbe1e5be8617d6a4108ed5a02ab | Update RivCrimeReport.js | Examples/js/RivCrimeReport.js | Examples/js/RivCrimeReport.js | (function() {
// Create the connector object
var myConnector = tableau.makeConnector();
// Define the schema
myConnector.getSchema = function(schemaCallback) {
var cols = [{
id: "id",
dataType: tableau.dataTypeEnum.string
},;
var tableSchema = {
id: "earthquakeFeed",
alias: "Earthquakes with magnitude greater than 4.5 in the last seven days",
columns: cols
};
schemaCallback([tableSchema]);
};
// Download the data
myConnector.getData = function(table, doneCallback) {
$.getJSON("https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/4.5_week.geojson", function(resp) {
var feat = resp.features,
tableData = [];
// Iterate over the JSON object
for (var i = 0, len = feat.length; i < len; i++) {
tableData.push({
"id": feat[i].id,
});
}
table.appendRows(tableData);
doneCallback();
});
};
tableau.registerConnector(myConnector);
// Create event listeners for when the user submits the form
$(document).ready(function() {
$("#submitButton").click(function() {
tableau.connectionName = "USGS Earthquake Feed"; // This will be the data source name in Tableau
tableau.submit(); // This sends the connector object to Tableau
});
});
})();
| JavaScript | 0 | @@ -282,17 +282,17 @@
%7D
-,
+%5D
;%0D%0A%0D%0A
|
8322754cc0abec1851e36797d6f99d58f438b122 | Fix yellow warning in scene_ios_test | Examples/js/scene_ios_test.js | Examples/js/scene_ios_test.js | /**
* Copyright (c) 2015-present, Viro, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroScene,
ViroBox,
ViroDirectionalLight,
Viro360Image,
ViroMaterials,
Viro3DObject,
ViroAnimations,
ViroImage,
ViroText,
ViroAnimatedComponent,
Viro360Video,
} from 'react-viro';
var scene_ios_test = React.createClass({
render: function() {
return (
<ViroScene>
<ViroDirectionalLight color="#ffffff" direction={[0, 0, -1.0]} />
<Viro360Video source={{uri: "https://s3-us-west-2.amazonaws.com/viro/360_surf.mp4"}} onLoadStart={this._onLoadStart("Start")} onLoadEnd={this._onLoadEnd("End")} rotation={[0,0,0]} />
<ViroText style={styles.baseText} position={[0,0, -8]} text="Testing!!!" />
<ViroImage width={5.0} height={10.0} position={[6, .1, -8.1]} rotation={[0, 0, 0]} source={{uri: "http://wiki.magicc.org/images/c/ce/MAGICC_logo_small.jpg"}} />
<ViroText style={{fontFamily: 'Helvetica-Bold', fontSize:10, textAlign:'center', textAlignVertical:'bottom', textClipMode:'cliptobounds', color:'#ff0000'}} text="Canada is the NYTimes place to visit this year. With it's beautiful cities and epic landscapes, our neighbor up north is full of splendor and adventure. Plus their president is cool :)." width={5.0} height={10.0} position={[6, .1, -8]} rotation={[0, 0, 0]} />
<ViroText style={{fontFamily: 'Helvetica-Bold', fontSize:12, textAlign:'left'}} text="Rotated Bold underlined Helvetica up in here!" width={5.0} position={[-3, .1, -8]} rotation={[0, -25, 0]} />
<ViroText style={styles.baseText} position={[0,-1, -8]} text="Longer text that is within 1 thingy" />
<ViroText style={styles.baseTextTwo} width={10.0} position={[0,1.5, -8]} text="Testing same text different width and length up in here. Know what I mean?" />
<Viro3DObject source={require('./res/male02_obj.obj')}
resources={[require('./res/male02.mtl'),
require('./res/01_-_Default1noCulling.JPG'),
require('./res/male-02-1noCulling.JPG'),
require('./res/orig_02_-_Defaul1noCulling.JPG')]}
position={[-0.0, -100, -10]}
scale={[0.1, 0.1, 0.1]}
onLoadStart={this._onLoadObjStart}
onLoadEnd={this._onLoadObjEnd}
/>
<Viro3DObject source={require('./res/heart.obj')}
position={[0.2, -5.5, -1.15]}
materials={["heart"]}
/>
<ViroImage source={require('./res/card_main.png')} height={2} width={4}
position={[0, 0, -5]}
scale={[0.1, 0.1, 0.1]} />
</ViroScene>
);
},
_onLoadObjStart() {
console.log("Started loading male02 OBJ file");
},
_onLoadObjEnd() {
console.log("Finished loading male02 OBJ file")
},
_onLoadStart(startText) {
return () => {
console.log("360 photo started");
}
},
_onLoadEnd(endText) {
return () => {
console.log("360 photo ended");
}
},
});
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
color: '#333333',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
baseText: {
fontFamily: 'Courier',
fontSize: 20,
color: '#ffff00',
},
baseTextTwo: {
fontFamily: 'Arial',
fontSize: 12,
color: '#ffffff',
},
});
ViroMaterials.createMaterials({
wework_title: {
shininess: 1.0,
lightingModel: "Constant",
diffuseColor: "#ff0000",
},
heart: {
lightingModel: "Constant",
diffuseTexture: require('./res/heart_d.jpg'),
},
})
ViroAnimations.registerAnimations({
moveRight:{properties:{positionX:"+=0.5"}, duration: 1000},
rotate:{properties:{rotateZ:"+=45"}, duration:1000},
scale:{properties:{scaleX:1.0, scaleY:0.8, scaleZ:1.0},
easing:"Bounce",
duration: 5000},
animateImage:[
["moveRight", "rotate"],
["scale"],
],
});
module.exports = scene_ios_test;
| JavaScript | 0.013666 | @@ -1395,11 +1395,11 @@
clip
-tob
+ToB
ound
|
65170493a22c3cc5959435fbfbe80f0508da4495 | Add some more tests | tests/unit/helpers/percentage-test.js | tests/unit/helpers/percentage-test.js | import {
percentage
} from 'ember-percentages/helpers/percentage';
module('PercentageHelper');
// Replace this with your real tests.
test('it returns a percentage without a trailing .0', function() {
equal(percentage(0.42), '42%');
});
test('it correctly rounds the percentage up where appropriate', function() {
equal(percentage(0.6789, 1), '67.9%');
});
test('it correctly rounds the percentage down where appropriate', function() {
equal(percentage(0.6788881, 4), '67.8888%');
});
| JavaScript | 0 | @@ -481,16 +481,176 @@
67.8888%25');%0A%7D);%0A
+%0Atest('it correctly handles 1', function() %7B%0A equal(percentage(1), '100%25');%0A%7D);%0A%0Atest('it correctly handles 0', function() %7B%0A equal(percentage(0), '0%25');%0A%7D);%0A
|
e5b7449d672cda414f2c51598aa3e52ee3e98903 | fix moving bugs | quantity_presenter.js | quantity_presenter.js | var QuantityPresenter = function(quantity) {
this.quantity = quantity;
this.integer = Math.floor(this.quantity);
this.remainder = quantity - this.integer;
this.fractions = {
0: "",
0.25: "\u00BC",
0.5: "\u00BD",
0.75: "\u00BE",
0.142: "\u2150",
0.111: "\u2151",
0.1: "\u2152",
0.333: "\u2153",
0.667: "\u2154",
0.2: "\u2155",
0.4: "\u2156",
0.6: "\u2157",
0.6: "\u2158",
0.167: "\u2159",
0.833: "\u215A",
0.125: "\u215B",
0.375: "\u215C",
0.625: "\u215D",
0.875: "\u215E",
};
this.closestFraction = Object.keys(fractions).find(function(fraction) {
return Math.abs(this.remainder - parseFloat(fraction)) < 0.01;
}.bind(this))
if (this.closestFraction) {
this.integerAsString = this.integer == 0 ? '' : '' + this.integer
this.quantityForDisplay = this.integerAsString + fractions[this.closestFraction];
} else {
this.quantityForDisplay = '' + this.quantity;
}
} | JavaScript | 0.000001 | @@ -606,16 +606,21 @@
ct.keys(
+this.
fraction
@@ -887,16 +887,21 @@
tring +
+this.
fraction
|
45666311783560f896b98327f977ce9108401272 | add primitive for whileTrue | kernel_primitives.js | kernel_primitives.js | ProtoObject._new = function() {
return this.basicNew().initialize();
};
_Object._new = ProtoObject._new;
OrderedCollection._new = _Object._new;
Point._new = _Object._new;
Rectangle._new = _Object._new;
S2JWorld._new = _Object._new;
BlockClosure._new = _Object._new;
Number.prototype._plus = function(anotherNumber){ return this + anotherNumber };
Number.prototype._minus = function(anotherNumber){ return this - anotherNumber };
Number.prototype._at = function(anotherNumber){ return Point.x_y_(this, anotherNumber); }
Array.new_ = function(arr){return new Array(arr)};
BlockClosure._objectPrototype.value = function(){
this.$func.apply(this, arguments);
} | JavaScript | 0.001408 | @@ -605,16 +605,45 @@
ype.
-value =
+prototype.value = WithNonLocalReturn(
func
@@ -684,12 +684,197 @@
rguments);%0A%7D
+);%0A%0ABlockClosure._objectPrototype.prototype.whileTrue_ = function(anotherBlock)%7B%0A // TODO implement whileTrue for real%0A while(this.value() == _true) %7B%0A anotherBlock.value();%0A %7D%0A%7D;
|
6e9e7c119bef4ca8f182f81ed20680a476237913 | fix breadcrumbs | www/widgets/breadcrumbs/breadcrumbs.js | www/widgets/breadcrumbs/breadcrumbs.js | app.directive('breadcrumbsBreadcrumbs', [
"settings",
"$location",
function(
settings,
$location
) {
return {
templateUrl: settings.widgets + 'breadcrumbs/breadcrumbs.html',
link: function(scope, element, attrs) {
//Breadcrumbs
var locations = $location.path().split('/').splice(1);
var locationspath = [];
for (i = 0; i < locations.length; i++){
if (i > 0){
locationspath.push(locations[i-1] + "/" + locations[i]);
}
else{
locationspath.push(locations[i]);
}
}
scope.locObj = {};
for(i = 0; i < locations.length; i++){
scope.locObj[locations[i]] = locationspath[i];
}
}
}
}
]); | JavaScript | 0.99875 | @@ -240,21 +240,19 @@
ttrs) %7B%0A
-
+%0A
-%0A
//
@@ -263,16 +263,18 @@
dcrumbs%0A
+
va
@@ -326,16 +326,18 @@
ice(1);%0A
+
va
@@ -366,16 +366,18 @@
+
for (i =
@@ -446,36 +446,91 @@
- locationspath.push
+var somevar = %22%22;%0A for(x = i; x %3E= 0; x--)%7B%0A if
(locatio
@@ -538,18 +538,47 @@
s%5Bi-
-1%5D + %22/%22
+x%5D != %22%22)%7B%0A somevar
+
+=
loc
@@ -589,13 +589,22 @@
ns%5Bi
-%5D);%0A%0A
+-x%5D + %22/%22%0A
@@ -629,16 +629,12 @@
-else%7B%0A
+%7D%0A
@@ -662,28 +662,23 @@
th.push(
-locations%5Bi%5D
+somevar
);%0A
@@ -685,16 +685,17 @@
%7D
+%0A
@@ -690,32 +690,38 @@
%7D%0A
+else%7B%0A
%0A
@@ -718,25 +718,59 @@
-%0A
+locationspath.push(locations%5Bi%5D);%0A
%7D%0A
@@ -753,32 +753,35 @@
s%5Bi%5D);%0A
+
%7D%0A %0A
@@ -772,25 +772,29 @@
%7D%0A
-%0A
+%7D%0A
scope
@@ -811,26 +811,19 @@
%7B%7D;%0A
-
+%0A
-%0A
-
for(
@@ -849,32 +849,34 @@
s.length; i++)%7B%0A
+
scop
@@ -921,24 +921,27 @@
%5Bi%5D;%0A
+
%7D%0A %0A
@@ -941,20 +941,25 @@
+ %7D
%0A
-%7D%0A
+ %7D%0A
%7D%0A
-%7D%0A
%5D);
+%0A
|
760658c9c12f106a7ff132b51a2954bb2b183a9b | allow to render less without files | packages/less/index.js | packages/less/index.js | const lessCompiler = require('less')
const read = require('@lump/read')
const write = require('@lump/write')
/*
* Compile less file
*/
module.exports = async ({ src, dest, options }) => {
if (!src || !dest) {
throw new Error('Missing Arguments')
}
const less = await read(src)
const css = await renderLess(less, options)
await write(dest, css)
}
function renderLess (data, options) {
return lessCompiler.render(data, options)
.then(output => output.css)
}
| JavaScript | 0 | @@ -123,19 +123,41 @@
e less f
-ile
+rom file/less to file/css
%0A */%0Amod
@@ -183,16 +183,25 @@
(%7B src,
+ content,
dest, o
@@ -206,16 +206,21 @@
options
+ = %7B%7D
%7D) =%3E %7B
@@ -235,15 +235,18 @@
src
-%7C%7C !des
+&& !conten
t) %7B
@@ -302,24 +302,34 @@
const less =
+ src%0A ?
await read(
@@ -333,16 +333,30 @@
ad(src)%0A
+ : content%0A
const
@@ -396,21 +396,33 @@
ons)%0A%0A
-await
+return dest%0A ?
write(d
@@ -431,16 +431,26 @@
t, css)%0A
+ : css%0A
%7D%0A%0Afunct
|
58b48098bfb333e93cafb38c7323fdef803ecdf8 | Change the C function creation logic into lazy-loading. | bridgesupport.js | bridgesupport.js | /**
* This module takes care of loading the BridgeSupport XML files for a given
* framework, and parsing the data into the given framework object.
*/
var fs = require('fs')
, sax = require('sax')
, path = require('path')
, core = require('./core')
, types = require('./types')
, join = path.join
, basename = path.basename
, exists = path.existsSync
, DY_SUFFIX = '.dylib'
, BS_SUFFIX = '.bridgesupport'
function bridgesupport (fw, _global) {
var bridgeSupportDir = join(fw.basePath, 'Resources', 'BridgeSupport')
, bridgeSupportXML = join(bridgeSupportDir, fw.name + BS_SUFFIX)
, bridgeSupportDylib = join(bridgeSupportDir, fw.name + DY_SUFFIX)
// If there's no BridgeSupport file, then just return the empty object...
if (!exists(bridgeSupportXML)) {
console.warn('No BridgeSupport files found for framework "%s" at: %s', fw.name, bridgeSupportXML);
return;
}
if (exists(bridgeSupportDylib)) {
fw.inline = core.dlopen(bridgeSupportDylib);
}
var contents = fs.readFileSync(bridgeSupportXML, 'utf8')
, parser = sax.parser(true)
, gotEnd = false
, classes = []
, constants = []
, curName
, curRtnType
, curArgTypes
, isInline
//console.error(contents);
parser.onerror = function (e) { throw e; }
parser.onopentag = function (node) {
//console.log(node.name);
switch (node.name) {
case 'depends_on':
bridgesupport.import(node.attributes.path);
break;
case 'class':
break;
case 'method':
break;
case 'arg':
if (curName) {
// class methods also have args, we only want functions though
// TODO: Get 64-bit type
curArgTypes.push(types.map(node.attributes.type));
}
break;
case 'retval':
if (curName) {
// class methods also have retvals, we only want functions though
// TODO: Get 64-bit type
curRtnType = types.map(node.attributes.type);
}
break;
case 'signatures':
// ignore
break;
case 'string_constant':
_global[node.attributes.name] = node.attributes.value;
break;
case 'enum':
_global[node.attributes.name] = parseInt(node.attributes.value);
break;
case 'struct':
break;
case 'field':
//console.error(node);
break;
case 'cftype':
break;
case 'constant':
//constants.push(node);
break;
case 'function':
curName = node.attributes.name;
curRtnType = null;
curArgTypes = [];
isInline = node.attributes.inline == 'true';
// TODO: is variadic? will require a 'function generator'
break;
case 'args':
break;
case 'opaque':
break;
case 'informal_protocol':
break;
case 'function_alias':
break;
default:
throw new Error('unkown tag: '+ node.name);
break;
}
};
parser.onclosetag = function (node) {
switch (node) {
case 'function':
if (isInline && !fw.inline) throw new Error('declared inline but could not find inline dylib!');
_global[curName] = core.Function(curName, curRtnType, curArgTypes, false, isInline ? fw.inline : fw.lib);
curName = null;
break;
}
};
parser.onend = function () {
gotEnd = true;
};
// Parse the contents of the file. This should happen synchronously.
parser.write(contents).close();
if (!gotEnd) {
throw new Error('could not parse BridgeSupport files synchronously');
}
/*
// Now time to set up the inheritance on all the Classes.
// This has to happen after parsing has completed to ensure that all the
// required parent classes have been parsed and loaded.
classes.forEach(function (c) {
Class.setupInheritance(c);
});
constants.forEach(function (node) {
var sym = lib.get(node.attributes.name);
if (node.attributes.declared_type == 'NSString*') {
sym = Class.wrapId(sym);
sym.__proto__ = Class.getClass('NSString').prototype;
framework[node.attributes.name] = sym;
}
});
*/
}
module.exports = bridgesupport;
| JavaScript | 0.000001 | @@ -3076,32 +3076,290 @@
ase 'function':%0A
+ // Binded functions will be lazy-loaded. We simply define a getter that%0A // does the creation magic the first time, and replaces the getter with%0A // the binded function%0A (function (curName, curRtnType, curArgTypes, isInline) %7B%0A
if (isIn
@@ -3459,24 +3459,75 @@
+
_global
-%5BcurName%5D
+.__defineGetter__(curName, function () %7B%0A var f
= c
@@ -3612,16 +3612,163 @@
w.lib);%0A
+ delete _global%5BcurName%5D;%0A return global%5BcurName%5D = f;%0A %7D);%0A %7D)(curName, curRtnType, curArgTypes, isInline);%0A
|
dc74ef87e18cfcb537b93dbc535788cb8893be37 | Stop breaking things Raquel, this is why you need tests | reducers/file_list.js | reducers/file_list.js | import Cookie from 'js-cookie'
import _ from 'lodash'
import { SAVE_FILE, DELETE_FILE } from '../actions/file_list_actions'
const initialState = Cookie.get('files')
const setState = () => {
const files = Cookie.get('files')
if (files) { return JSON.parse(files) }
return []
}
const saveExistingFile = (state, updatedFile) => {
let newState
if (state.length === 0) {
newState = [updatedFile]
} else {
const removeFile = _.flatten([_.slice(state, 0, updatedFile.id), _.slice(state, updatedFile.id + 1, state.length)])
newState = [...removeFile, updatedFile]
}
Cookie.set('files', newState)
return newState
}
export const fileList = (state = setState(), action) => {
switch (action.type) {
case SAVE_FILE: {
const fileId = state[action.file.id].id
if (fileId) {
return saveExistingFile(state, action.file)
}
const newState = [...state, action.file]
Cookie.set('files', newState)
return newState
}
case DELETE_FILE: {
const newState = _.flatten([_.slice(state, 0, action.id), _.slice(state, action.id + 1, state.length)])
Cookie.set('files', newState)
return newState
}
default:
return state
}
} | JavaScript | 0.000002 | @@ -760,18 +760,16 @@
nst file
-Id
= state
@@ -784,19 +784,16 @@
file.id%5D
-.id
%0A%0A
@@ -804,10 +804,8 @@
file
-Id
) %7B%0A
|
7c9338fbfdab7044e94a7ff5fdb443a2b1a596b3 | index follower count | init/mongo-collections.js | init/mongo-collections.js | var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(process.env.MONGOHQ_URL, function(err, db) {
if (err) throw err;
process.nextTick(function() { initCollections(db); });
});
function initCollections(db)
{
var i,
collectionsAndIndexes = {
worker_state : [],
log_totals : [
{ calls : 1 },
{ emails : 1 },
{ views : 1 },
],
tweets : [
],
},
running = 0;
console.log("Connected to mongo, initing collections...");
function whenDone()
{
if (--running == 0) {
console.log('READY FOR JUSTICE, BYES');
process.exit();
}
}
for (i in collectionsAndIndexes) {
++running;
(function() {
var coll = i,
fields = collectionsAndIndexes[i];
db.createCollection(coll, function(err, collection) {
console.log('Created collection ' + coll);
var j;
for (j in fields) {
++running;
(function() {
var index = fields[j];
collection.ensureIndex(index, function(err, indexName) {
console.log('Indexed collection ' + coll + ':', index);
whenDone();
});
})();
}
whenDone();
});
})();
}
}
| JavaScript | 0.000001 | @@ -440,16 +440,44 @@
ets : %5B%0A
+%09%09%09%09%7B followers_count : 1 %7D,
%0A
|
5adbc834a53b6a809b462c9be6038d7db7a1580c | add explicit analytics id | packages/docs-next/src/router/index.js | packages/docs-next/src/router/index.js | // Imports
import Router from 'vue-router'
import scrollBehavior from './scroll-behavior'
import Vue from 'vue'
import VueGtag from 'vue-gtag'
// Globals
import { IS_PROD } from '@/util/globals'
import { trailingSlash } from '@/util/helpers'
import {
abort,
locale,
layout,
route,
redirect,
} from '@/util/routes'
// Setup
Vue.use(Router)
export function createRouter (vuetify, store, i18n) {
const loadedLocales = ['en']
const router = new Router({
mode: 'history',
base: process.env.BASE_URL,
scrollBehavior: (...args) => scrollBehavior(vuetify, ...args),
routes: [
locale([
layout('Home', [route('Home')]),
route('Whiteframes', null, 'examples/whiteframes/:whiteframe'),
layout('Default', [
route('Documentation'),
], ':category/:page'),
layout('Default', [abort()], '*'),
]),
// Redirect for language fallback
redirect('/:locale(%s)/*', to => to.params.pathMatch),
// The previous one doesn't match if there's no slash after the language code
redirect('/:locale(%s)'),
redirect(to => to.path),
],
})
function loadLocale (locale) {
if (
!locale ||
i18n.locale === locale ||
loadedLocales.includes(locale)
) return Promise.resolve()
return import(
/* webpackChunkName: "locale-[request]" */
`@/i18n/messages/${locale}.json`
).then(messages => {
i18n.setLocaleMessage(locale, messages.default)
loadedLocales.push(locale)
i18n.locale = locale
})
}
router.beforeEach((to, from, next) => {
return to.path.endsWith('/') ? next() : next(trailingSlash(to.path))
})
router.beforeEach((to, _, next) => {
loadLocale(to.params.locale).then(() => next())
})
Vue.use(VueGtag, {
bootstrap: IS_PROD,
config: { id: process.env.VUE_APP_GOOGLE_ANALYTICS },
}, router)
return router
}
| JavaScript | 0.000001 | @@ -1837,44 +1837,23 @@
id:
-process.env.VUE_APP_GOOGLE_ANALYTICS
+'UA-75262397-3'
%7D,%0A
|
2216b272223b9bc04bf89d4e562538f3d64703a8 | add first solution | Algorithms/JS/integers/allFactorials.js | Algorithms/JS/integers/allFactorials.js | // All factors
// Given a number N, find all factors of N.
// Example:
// N = 6
// factors = [1, 2, 3, 6]
// Make sure the returned array is sorted.
/**
* @param {number} A
* @return {array []}
*/
| JavaScript | 0.000002 | @@ -199,8 +199,151 @@
%5B%5D%7D%0A */%0A
+%0Afunction allFactors(A)%7B%0A var result = %5B%5D;%0A for(var i = 1; i%3C=A; i++)%7B%0A if(A %25 i === 0) result.push(i);%0A %7D%0A return result%0A%7D%0A
|
d7d1bb7fb1d0649b9c0b880f90a613cf49fb4566 | test rotate | pet-projects/xylo-stars/js/main.js | pet-projects/xylo-stars/js/main.js | $(function() {
// FastClick.attach(document.body);
// $.fn.checkPosition = function() {
// var top = this[0].getBoundingClientRect().top;
// var left = this[0].getBoundingClientRect().left;
// var right = this[0].getBoundingClientRect().right;
// var bottom = this[0].getBoundingClientRect().bottom;
// // console.log(top, right, bottom, left)
// }
buzz.defaults.formats = ['wav'];
var xyloSounds = [];
var sounds = ['a', 'b', 'c', 'c2', 'd1', 'e1', 'f', 'g'];
for (var i = 0; i < sounds.length; i++) {
var sound = sounds[i];
xyloSounds.push(new buzz.sound('audio/' + sound));
}
var starRatio = 228/225;
var countStars = getRandomInt(7, 20);
var securityZoneSize = getRandomInt(10, 100);
divideArea(securityZoneSize, countStars);
$(window).on('resize', function() {
countStars = getRandomInt(7, 20);
securityZoneSize = getRandomInt(10, 100);
$('.star').remove();
divideArea(securityZoneSize, countStars);
});
$('.star').on('mousedown', function() {
var concreteSound = getRandomInt(0, sounds.length);
if (xyloSounds[concreteSound].isPaused()) {
xyloSounds[concreteSound].play();
} else {
xyloSounds[concreteSound].stop().play();
}
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandom() {
return Math.random() > 0.5 ? Math.random() : Math.random() -1;
}
function setSquare(topCoord, leftCoord, $elementSide) {
var newSquare = document.createElement('div');
$(newSquare).addClass('star');
$(newSquare).css({
'top': topCoord + 100 * getRandom(),
'left': leftCoord + 10 * getRandom(),
'width': $elementSide * starRatio,
'height': $elementSide,
'transform-rotate': getRandomInt(10, 360) + 'deg'
});
$('.sky').append(newSquare);
}
function divideArea(securityZoneSize, numberOfSquares) {
var $width = $(window).width() - securityZoneSize;
var $height = $(window).height() - securityZoneSize;
var $square = $width * $height;
var $elementSquare = parseInt($square / numberOfSquares);
var $elementSide = parseInt(Math.sqrt($elementSquare));
for (var i = securityZoneSize; i < $width - $elementSide; i+= $elementSide) {
for (var j = securityZoneSize; j < $height - $elementSide; j+= $elementSide) {
setSquare(j, i, $elementSide);
}
}
}
});
| JavaScript | 0.000001 | @@ -1673,24 +1673,71 @@
ent('div');%0A
+ var rotateDeg = getRandomInt(10, 360);%0A
$(ne
@@ -1759,24 +1759,24 @@
ss('star');%0A
-
$(ne
@@ -1971,16 +1971,28 @@
entSide,
+
%0A
@@ -1997,16 +1997,20 @@
'
+-ms-
transfor
@@ -2014,18 +2014,196 @@
form
--rotate':
+': 'rotate(' + rotateDeg + 'deg)',%0A '-webkit-transform': 'rotate(' + rotateDeg + 'deg)',%0A 'transform': 'rotate(' + rotateDeg + 'deg)'%0A %7D);%0A console.log(
getR
@@ -2227,26 +2227,16 @@
+ 'deg'
-%0A %7D
);%0A
|
d278b7f7aee7c3926eb473b75072c386de7bfc38 | set tocco languages on intl plugin | storybook/config.js | storybook/config.js | import 'core-js/stable'
import 'regenerator-runtime/runtime'
import {configure, addParameters, addDecorator} from '@storybook/react'
import {withInfo} from '@storybook/addon-info'
import {setIntlConfig, withIntl} from 'storybook-addon-intl'
import {addLocaleData} from 'react-intl'
import enLocaleData from 'react-intl/locale-data/en'
import deLocaleData from 'react-intl/locale-data/de'
import frLocaleData from 'react-intl/locale-data/fr'
import itLocaleData from 'react-intl/locale-data/it'
import {withThemes} from 'storybook-styled-components'
import {withA11y} from '@storybook/addon-a11y'
import '@storybook/addon-console'
import theme from './theme'
import darkTheme from '../packages/tocco-theme/src/ToccoTheme/darkTheme'
import defaultTheme from '../packages/tocco-theme/src/ToccoTheme/defaultTheme'
import CustomPropTable from './CustomPropTable'
addLocaleData(enLocaleData)
addLocaleData(deLocaleData)
addLocaleData(frLocaleData)
addLocaleData(itLocaleData)
setIntlConfig({
locales: ['de-CH', 'en', 'de', 'fr', 'it'],
defaultLocale: 'de-CH',
getMessages: () => {}
})
addDecorator(withInfo({
TableComponent: CustomPropTable,
styles: defaultTheme => (
{
...defaultTheme,
button: {
...defaultTheme.button,
base: {
...defaultTheme.button.base,
backgroundColor: '#9E2124',
border: 0
}
},
header: {
...defaultTheme.header,
body: {
...defaultTheme.header.body,
borderBottom: 0
},
h2: {
display: 'none'
}
},
info: {
...defaultTheme.info,
margin: 0,
padding: '10px'
},
infoBody: {
...defaultTheme.infoBody,
border: 0,
margin: 0,
padding: 0
},
propTableHead: {
display: 'none'
},
source: {
...defaultTheme.source,
h1: {
...defaultTheme.source.h1,
borderBottom: 0
}
}
}
)
}))
addDecorator(withIntl)
addDecorator(withThemes(
{
'Default Theme': defaultTheme,
'Dark Theme': darkTheme
}
))
addParameters({
options: {
theme,
hierarchyRootSeparator: /\|/,
hierarchySeparator: /\//
},
backgrounds: [
{name: 'White', value: '#fff'},
{name: 'Dark', value: '#707070'},
{name: 'Tocco', value: '#9E2124'}
]
})
addDecorator(withA11y)
const req = require.context('../packages/tocco-ui/src/', true, /\.stories\.js$/)
const req2 = require.context('../packages/app-extensions/src/', true, /\.stories\.js$/)
const req3 = require.context('../packages/entity-browser/src/', true, /\.stories\.js$/)
const req4 = require.context('../packages/entity-detail/src/', true, /\.stories\.js$/)
const req5 = require.context('../packages/entity-list/src/', true, /\.stories\.js$/)
const req6 = require.context('../packages/login/src/', true, /\.stories\.js$/)
const req7 = require.context('../packages/resource-scheduler/src/', true, /\.stories\.js$/)
const req8 = require.context('../packages/admin/src/', true, /\.stories\.js$/)
function loadStories() {
req.keys().forEach(filename => req(filename))
req2.keys().forEach(filename => req2(filename))
req3.keys().forEach(filename => req3(filename))
req4.keys().forEach(filename => req4(filename))
req5.keys().forEach(filename => req5(filename))
req6.keys().forEach(filename => req6(filename))
req7.keys().forEach(filename => req7(filename))
req8.keys().forEach(filename => req8(filename))
}
configure(loadStories, module)
| JavaScript | 0 | @@ -1008,28 +1008,31 @@
', '
-en', 'de', 'fr', 'it
+fr-CH', 'it-CH', 'en-US
'%5D,%0A
|
00f53e988d0b1963560d5c1156b7f75f81b320d6 | Add success snackbar to QuestionCreateForm | frontend/src/components/Question/CreateForm.js | frontend/src/components/Question/CreateForm.js | import React from 'react';
import PropTypes from 'prop-types';
import CreateConnector from './CreateConnector';
import QuestionForm from './Form';
import { formValuesToRequest } from './transforms';
import FAButton from '../FAButton';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import Router from 'next/router';
import CancelDialog from './CancelDialog';
const createHandleSubmit = createQuestion => (values, addHandlers) => {
console.log('VALUES: ');
console.log(values);
// This is where `addHandlers` comes in handy as the form controls its state
addHandlers(
createQuestion({
variables: { input: formValuesToRequest(values) },
})
.then(resp => {
console.log('addHandlers OK!');
console.log('Response: ');
console.log(resp);
// this.props.showNotification();
})
.catch(error => {
// The component is and should not be aware of this being a GraphQL error.
console.log('addHandlers ERROR:');
console.log(error);
// this.props.showApiErrorNotification(error);
}),
);
};
const questionInitialValues = {
type: 'OPEN_ENDED',
wording: '',
imageUrl: '',
secondaryWording: '',
// These empty choices are here so that Formik can render the input fields
choices: [{ text: '' }, { text: '' }, { text: '' }, { text: '' }, { text: '' }],
};
class QuestionCreateForm extends React.Component {
state = {
warningDialogOpen: false,
};
handleClickOpen = () => {
this.setState({ warningDialogOpen: true });
};
handleClose = () => {
this.setState({ warningDialogOpen: false });
};
createBackToListHandler = isDirty => () => {
// If the user entered any input, show a warning dialog to confirm
// before discarding the draft.
if (isDirty) {
this.setState({ warningDialogOpen: true });
return;
}
Router.push('/admin/questoes');
};
render() {
const { warningDialogOpen } = this.state;
return (
<CreateConnector>
{({ createQuestion }) => (
<QuestionForm
initialValues={questionInitialValues}
onSubmit={createHandleSubmit(createQuestion)}
>
{({ form, isDirty }) => (
<React.Fragment>
<FAButton
onClick={this.createBackToListHandler(isDirty)}
aria-label="Voltar pra lista de questões"
>
<ArrowBackIcon />
</FAButton>
<CancelDialog
open={warningDialogOpen}
onCancel={this.handleClose}
onContinue={() => {
Router.push('/admin/questoes');
}}
/>
{form}
</React.Fragment>
)}
</QuestionForm>
)}
</CreateConnector>
);
}
}
export default QuestionCreateForm;
| JavaScript | 0 | @@ -362,16 +362,58 @@
Dialog';
+%0Aimport %7B withSnackbar %7D from 'notistack';
%0A%0Aconst
@@ -433,16 +433,17 @@
ubmit =
+(
createQu
@@ -448,16 +448,34 @@
Question
+, enqueueSnackbar)
=%3E (val
@@ -862,39 +862,128 @@
-// this.props.showNotification(
+enqueueSnackbar('Quest%C3%A3o salva com sucesso', %7B%0A variant: 'success',%0A autoHideDuration: 6000,%0A %7D
);%0A
@@ -2069,24 +2069,68 @@
render() %7B%0A
+ const %7B enqueueSnackbar %7D = this.props;%0A
const %7B
@@ -2364,16 +2364,33 @@
Question
+, enqueueSnackbar
)%7D%0A
@@ -3098,23 +3098,8 @@
%0A%7D%0A%0A
-export default
Ques
@@ -3112,10 +3112,122 @@
eateForm
+.propTypes = %7B%0A enqueueSnackbar: PropTypes.func.isRequired,%0A%7D;%0A%0Aexport default withSnackbar(QuestionCreateForm)
;%0A
|
4840a29524a0c3ae199006e26ef9cd2dafb6d093 | Remove template pattern for EnumerationProperty | js/EnumerationProperty.js | js/EnumerationProperty.js | // Copyright 2019-2021, University of Colorado Boulder
/**
* Property whose value is a member of an Enumeration.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
import Enumeration from '../../phet-core/js/Enumeration.js';
import EnumerationIO from '../../phet-core/js/EnumerationIO.js';
import merge from '../../phet-core/js/merge.js';
import axon from './axon.js';
import Property from './Property.js';
/** @template T */
class EnumerationProperty extends Property {
/**
* @param {Enumeration} enumeration
* @param {*} initialValue - one of the values from enumeration
* @param {Object} [options]
*/
constructor( enumeration, initialValue, options ) {
assert && assert( enumeration instanceof Enumeration, `invalid enumeration: ${enumeration}` );
assert && assert( enumeration.includes( initialValue ), `invalid initialValue: ${initialValue}` );
if ( options ) {
// client cannot specify superclass options that are not supported by EnumerationProperty
assert && assert( !options.hasOwnProperty( 'isValidValue' ), 'EnumerationProperty does not support isValidValue' );
// client cannot specify superclass options that are controlled by EnumerationProperty
assert && assert( !options.hasOwnProperty( 'valueType' ), 'EnumerationProperty sets valueType' );
assert && assert( !options.hasOwnProperty( 'phetioType' ), 'EnumerationProperty sets phetioType' );
}
options = merge( {
valueType: enumeration,
phetioType: Property.PropertyIO( EnumerationIO( enumeration ) ),
validValues: enumeration.VALUES // for PhET-iO documentation and support
}, options );
super( initialValue, options );
// @public (read-only)
this.enumeration = enumeration;
}
}
axon.register( 'EnumerationProperty', EnumerationProperty );
export default EnumerationProperty; | JavaScript | 0 | @@ -406,27 +406,8 @@
';%0A%0A
-/** @template T */%0A
clas
|
f076e791d42682e42ee797d1f356e052ee2d3c87 | remove self | js/assets/elr-calendar.js | js/assets/elr-calendar.js | import elrUtlities from 'elr-utility-lib';
import elrTimeUtlities from 'elr-time-utilities';
import elrCalendarCreate from './elr-calendar-create';
import elrCalendarActions from './elr-calendar-actions';
const $ = require('jquery');
let elr = elrUtlities();
let elrTime = elrTimeUtlities();
let elrCreate = elrCalendarCreate();
let elrActions = elrCalendarActions();
const elrCalendar = function({
calendarClass = 'elr-calendar',
view = 'month',
addHolidays = true,
currentDate = elrTime.today(),
newEvents = []
} = {}) {
// let self = {};
let $calendar = $(`.${calendarClass}`);
if ($calendar.length) {
let $body = $('body');
let evtClass = 'elr-events';
let classes = {
'weekend': 'elr-cal-weekend',
'muted': 'elr-cal-muted',
'holiday': 'elr-cal-holiday',
'today': 'elr-cal-today',
'month': 'elr-month',
'week': 'elr-week',
'date': 'elr-date'
};
$calendar.each(function() {
let $cal = $(this);
let $calendarNav = $cal.find('.elr-calendar-nav');
let $calendarSelect = $cal.find('.elr-calendar-select');
let $calendarSelectButton = $calendarSelect.find('button[type=submit]');
let $addEventForm = $cal.find('form.elr-calendar-new-evt').hide();
let $showEventFormButton = $cal.find('button.elr-show-evt-form');
let $calendarViewActiveButton = $cal.find(`.elr-calendar-view-nav button[data-view=${view}]`).addClass('active');
let evts = elrTime.holidays;
elrCreate.buildCalendar(view, currentDate, $calendar, evts);
$cal.on('click', '.elr-calendar-year-prev, .elr-calendar-year-next', function() {
let dir = $(this).data('dir');
elrActions.advanceYear(dir, evts, $cal);
});
$cal.on('click', '.elr-calendar-month-prev, .elr-calendar-month-next', function() {
let dir = $(this).data('dir');
elrActions.advanceMonth(dir, evts, $cal);
});
$cal.on('click', '.elr-calendar-current', function() {
elrCreate.changeCalendar(view, elrTime.today(), $cal, evts);
});
$cal.on('click', 'button.elr-calendar-view', function() {
let $calendarInner = $cal.find('.calendar-inner');
let dateObj = {
'month': $calendarInner.data('month'),
'date': $calendarInner.find(`.${classes.date}`).first().data('date'),
'year': $calendarInner.data('year')
};
$('button.elr-calendar-view.active').removeClass('active');
$(this).addClass('active');
elrCreate.changeCalendar($(this).data('view'), dateObj, $cal, evts);
})
});
}
// return self;
};
export default elrCalendar; | JavaScript | 0.000112 | @@ -542,30 +542,8 @@
) %7B%0A
- // let self = %7B%7D;%0A
@@ -2888,29 +2888,8 @@
%7D
-%0A%0A // return self;
%0A%7D;%0A
|
40d0764852ab632a54dacf5c63debe5575013319 | Fix in German translation | js/i18n/grid.locale-de.js | js/i18n/grid.locale-de.js | ;(function($){
/**
* jqGrid German Translation
* Version 1.0.0 (developed for jQuery Grid 3.3.1)
* Olaf Klöppel opensource@blue-hit.de
* http://blue-hit.de/
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
**/
$.jgrid = {
defaults : {
recordtext: "Zeige {0} - {1} von {2}",
emptyrecords: "Keine Datensätze vorhanden",
loadtext: "Lädt...",
pgtext : "Seite {0} von {1}"
},
search : {
caption: "Suche...",
Find: "Finden",
Reset: "Zurücksetzen",
odata : ['gleich', 'ungleich', 'kleiner', 'kleiner gleich','größer','größer gleich', 'beginnt mit','beginnt nicht mit','ist in','ist nicht in','endet mit','endet nicht mit','enthält','enthält nicht'],
groupOps: [ { op: "AND", text: "alle" }, { op: "OR", text: "mindestens eins" } ],
matchText: " match",
rulesText: " rules"
},
edit : {
addCaption: "Datensatz hinzufügen",
editCaption: "Datensatz bearbeiten",
bSubmit: "Speichern",
bCancel: "Abbrechen",
bClose: "Schließen",
saveData: "Daten wurden geändert! Änderungen speichern?",
bYes : "ja",
bNo : "nein",
bExit : "abbrechen",
msg: {
required:"Feld ist erforderlich",
number: "Bitte geben Sie eine Zahl ein",
minValue:"Wert muss größer oder gleich sein, als ",
maxValue:"Wert muss kleiner oder gleich sein, als ",
email: "ist keine valide E-Mail Adresse",
integer: "Bitte geben Sie eine Ganzzahl ein",
date: "Bitte geben Sie ein gültiges Datum ein",
url: "ist keine gültige URL. Prefix muss eingegeben werden ('http://' oder 'https://')"
}
},
view : {
caption: "Datensatz anschauen",
bClose: "Schließen"
},
del : {
caption: "Löschen",
msg: "Ausgewählte Datensätze löschen?",
bSubmit: "Löschen",
bCancel: "Abbrechen"
},
nav : {
edittext: " ",
edittitle: "Ausgewählten Zeile editieren",
addtext:" ",
addtitle: "Neuen Zeile einfügen",
deltext: " ",
deltitle: "Ausgewählte Zeile löschen",
searchtext: " ",
searchtitle: "Datensatz finden",
refreshtext: "",
refreshtitle: "Tabelle neu laden",
alertcap: "Warnung",
alerttext: "Bitte Zeile auswählen",
viewtext: "",
viewtitle: "View selected row"
},
col : {
caption: "Spalten anzeigen/verbergen",
bSubmit: "Speichern",
bCancel: "Abbrechen"
},
errors : {
errcap : "Fehler",
nourl : "Keine URL angegeben",
norecords: "Keine Datensätze zum verarbeiten",
model : "colNames und colModel sind unterschiedlich lang!"
},
formatter : {
integer : {thousandsSeparator: " ", defaultValue: '0'},
number : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, defaultValue: '0,00'},
currency : {decimalSeparator:",", thousandsSeparator: ".", decimalPlaces: 2, prefix: "", suffix:" €", defaultValue: '0,00'},
date : {
dayNames: [
"So", "Mo", "Di", "Mi", "Do", "Fr", "Sa",
"Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"
],
monthNames: [
"Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez",
"Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"
],
AmPm : ["am","pm","AM","PM"],
S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th'},
srcformat: 'Y-m-d',
newformat: 'd/m/Y',
masks : {
ISO8601Long:"d.m.Y H:i:s",
ISO8601Short:"d.m.Y",
ShortDate: "j.n.Y",
LongDate: "l, d. F Y",
FullDateTime: "l, d. F Y G:i:s",
MonthDay: "d. F",
ShortTime: "G:i",
LongTime: "G:i:s",
SortableDateTime: "Y-m-d\\TH:i:s",
UniversalSortableDateTime: "Y-m-d H:i:sO",
YearMonth: "F Y"
},
reformatAfterEdit : false
},
baseLinkUrl: '',
showAction: '',
target: '',
checkbox : {disabled:true},
idName : 'id'
}
};
})(jQuery); | JavaScript | 0.999999 | @@ -2244,25 +2244,34 @@
e: %22
-View selected row
+Ausgew%C3%A4hlte Zeile anzeigen
%22%0A%09%7D
|
41fd5e07d59eb3dbc6a826a5c0a46cbf0804fe8f | Correct coding style | js/id/services/taginfo.js | js/id/services/taginfo.js | iD.taginfo = function() {
var taginfo = {},
endpoint = 'https://taginfo.openstreetmap.org/api/4/',
tag_sorts = {
point: 'count_nodes',
vertex: 'count_nodes',
area: 'count_ways',
line: 'count_ways'
},
tag_filters = {
point: 'nodes',
vertex: 'nodes',
area: 'ways',
line: 'ways'
};
if (!iD.taginfo.cache) {
iD.taginfo.cache = {};
}
var cache = iD.taginfo.cache;
function sets(parameters, n, o) {
if (parameters.geometry && o[parameters.geometry]) {
parameters[n] = o[parameters.geometry];
}
return parameters;
}
function setFilter(parameters) {
return sets(parameters, 'filter', tag_filters);
}
function setSort(parameters) {
return sets(parameters, 'sortname', tag_sorts);
}
function clean(parameters) {
return _.omit(parameters, 'geometry', 'debounce');
}
function shorten(parameters) {
if (!parameters.query) {
delete parameters.query;
} else {
parameters.query = parameters.query.slice(0, 3);
}
return parameters;
}
function popularKeys(parameters) {
var pop_field = 'count_all';
if (parameters.filter) pop_field = 'count_' + parameters.filter;
return function(d) { return parseFloat(d[pop_field]) > 10000; };
}
function popularValues() {
return function(d) { return parseFloat(d.fraction) > 0.01 || d.in_wiki; };
}
function valKey(d) { return { value: d.key }; }
function valKeyDescription(d) {
return {
value: d.value,
title: d.description
};
}
var debounced = _.debounce(d3.json, 100, true);
function request(url, debounce, callback) {
if (cache[url]) {
callback(null, cache[url]);
} else if (debounce) {
debounced(url, done);
} else {
d3.json(url, done);
}
function done(err, data) {
if (!err) cache[url] = data;
callback(err, data);
}
}
taginfo.keys = function(parameters, callback) {
var debounce = parameters.debounce;
parameters = clean(shorten(setSort(parameters)));
request(endpoint + 'keys/all?' +
iD.util.qsString(_.extend({
rp: 10,
sortname: 'count_all',
sortorder: 'desc',
page: 1
}, parameters)), debounce, function(err, d) {
if (err) return callback(err);
callback(null, d.data.filter(popularKeys(parameters)).map(valKey));
});
};
taginfo.values = function(parameters, callback) {
var debounce = parameters.debounce;
parameters = clean(shorten(setSort(setFilter(parameters))));
request(endpoint + 'key/values?' +
iD.util.qsString(_.extend({
rp: 25,
sortname: 'count_all',
sortorder: 'desc',
page: 1
}, parameters)), debounce, function(err, d) {
if (err) return callback(err);
callback(null, d.data.filter(popularValues()).map(valKeyDescription), parameters);
});
};
taginfo.docs = function(parameters, callback) {
var debounce = parameters.debounce;
parameters = clean(setSort(parameters));
var path = 'key/wiki_pages?';
if (parameters.value) path = 'tag/wiki_pages?';
else if (parameters.rtype) path = 'relation/wiki_pages?';
var decoratedCallback;
if (parameters.value) {
decoratedCallback = function(err, data) {
// The third argument to callback is the softfail flag, to
// make the callback function not show a message to the end
// user when no docs are found but just return false.
var docsFound = callback(err, data, true);
if (!docsFound) {
taginfo.docs(_.omit(parameters, 'value'), callback);
}
}
}
request(endpoint + path +
iD.util.qsString(parameters), debounce, decoratedCallback||callback);
};
taginfo.endpoint = function(_) {
if (!arguments.length) return endpoint;
endpoint = _;
return taginfo;
};
return taginfo;
};
| JavaScript | 0.000647 | @@ -4191,32 +4191,33 @@
%7D%0A %7D
+;
%0A %7D%0A%0A
@@ -4315,18 +4315,20 @@
Callback
+
%7C%7C
+
callback
|
eebe2de4dd3027129ef2bfef1348d133d636f2a9 | Improve comments (slightly) | src/update/Updater.js | src/update/Updater.js | import Immutable from 'immutable';
import Analyser from 'circuit-analysis';
import {Functions} from 'circuit-models';
import R from 'ramda';
import EventProcessor from './EventProcessor.js';
import Modes from './Modes.js';
import Executor from './Executor.js';
import Wire from '../components/elements/Wire.jsx';
const {stamp} = Functions;
function viewModelChanged(state1, state2) {
return state1.get('views') !== state2.get('views');
}
function toConnectors(elem) {
const props = elem.get('props');
return props
.get('connectors')
.map((vector, key) => ({
pos: vector,
id: {
viewID: props.get('id'),
connectorID: key
}
}));
}
function merge(connectors) {
return connectors
.reduce((nodeIDs, c) => {
return nodeIDs.push(c.id);
}, new Immutable.List());
}
function giveOrderedID(map, node, i) {
return map.set(i, node);
}
function position(connector) { return connector.pos.toString(); }
function toNodes(views) {
return views // withMutations?
.valueSeq()
.flatMap(toConnectors)
.groupBy(position).valueSeq()
.map(merge)
.reduce(giveOrderedID, new Immutable.Map());
}
function setNodesInModels(models, nodes) {
return models
.withMutations(ms => {
nodes.forEach((node, nodeID) => {
node.forEach(connector => {
ms.setIn([connector.viewID, 'nodes', connector.connectorID], nodeID);
});
});
});
}
function getCircuitInfo(state) {
return {
numOfNodes: state.get('nodes').size,
numOfVSources: state.get('models')
.filter(m => m.has('vSources'))
.reduce((n, m) => n + m.get('vSources'), 0)
};
}
function solveCircuit(state, circuitInfo) {
try {
const {solve, stamp: stamper} = Analyser.createEquationBuilder(circuitInfo);
state.get('models').forEach(model => {
stamp(model, stamper);
});
const solution = solve();
return {
solution: R.flatten(solution())
};
} catch(e) {
// if we can't solve, there's probably something wrong with the circuit
console.warn(e);
// just return a blank solution (zeros for voltages/currents)
const n = Math.max(0, circuitInfo.numOfNodes + circuitInfo.numOfVSources - 1);
return {
solution: Array.fill(new Array(n), 0),
error: e
};
}
}
function updateCircuit(state, solution, circuitInfo) {
if (!solution) { return state; }
const flattened = R.prepend(0, solution); // add 0 volt ground node
const voltages = R.take(circuitInfo.numOfNodes, flattened);
let currents = R.drop(circuitInfo.numOfNodes, flattened);
return state.update('views', views => views.map(view => {
const viewID = view.getIn(['props', 'id']);
const model = state.getIn(['models', viewID]);
const nodeIDs = model.get('nodes');
// set voltages
const vs = nodeIDs.map(nodeID => voltages[nodeID]);
view = view.setIn(['props', 'voltages'], vs.toJS());
// set currents
const numOfVSources = model.get('vSources', 0);
if (numOfVSources > 0) {
const cs = R.take(numOfVSources, currents);
currents = R.drop(numOfVSources, currents);
view = view.setIn(['props', 'currents'], cs);
}
return view;
}));
}
/**
* Use BFS to find a path between two nodes in the circuit graph.
*/
function isPathBetween(startNode, destNode, nodes, models, modelID) {
const visited = [],
q = [];
visited[startNode] = true;
q.push(startNode);
if (startNode === destNode) { return true; }
while (q.length !== 0) {
const n = q.shift();
const connectors = nodes[n];
// queue all directly connected nodes
for (let i = 0; i < connectors.length; i++) {
const con = connectors[i];
const id = con.viewID;
if (id === modelID) {
continue; // ignore paths through the model
}
const connectedNodes = models[id].nodes;
for (let j = 0; j < connectedNodes.length; j++) {
const connectedNode = connectedNodes[j];
if (connectedNode === destNode) {
return true;
}
if (!visited[connectedNode]) {
visited[connectedNode] = true;
q.push(connectedNode);
}
}
}
}
return false;
}
function hasPathProblem(state) {
const models = state.get('models'),
isCurrentSource = model => model.get('type') === 'CurrentSource', // TODO make this less ugh
hasPath = (currentSource, id) => {
const nodes = state.get('nodes'),
[n1, n2] = currentSource.get('nodes').toJS();
return isPathBetween(n1, n2, nodes.toJS(), models.toJS(), id);
};
// look for current sources with no path for current
return !models
.filter(isCurrentSource)
.every(hasPath);
}
function Updater() {
const eventProcessor = new EventProcessor();
const executor = new Executor();
let eventQueue = new Immutable.List();
let state = new Immutable.Map({
mode: Modes.add(Wire),
currentOffset: 0,
// NOTE: Immutable.Maps are iterated in a stable order. This (for better of worse) is implicitly relied on
views: new Immutable.Map(), // elemID -> element view
models: new Immutable.Map(), // elemID -> element model
nodes: new Immutable.Map() // nodeID -> node
});
function processEventQueue() {
const {mode, actions} = eventProcessor.process(eventQueue, state.get('mode'));
eventQueue = [];
state = state.set('mode', mode);
return actions;
}
// uses previous state + delta to calculate new props for CircuitCanvas
function update(delta) {
state = state.update('currentOffset', currentOffset => currentOffset += delta); // TODO a better way of doing this (and handling overflow)
// TODO could do a lot of this in begin.viewModelChanged...
const pathProblem = hasPathProblem(state);
const circuitInfo = getCircuitInfo(state);
const {solution, error} = solveCircuit(state, circuitInfo);
state = updateCircuit(state, solution, circuitInfo);
return {
props: {
elements: state.get('views'),
pushEvent: event => eventQueue.push(event)
},
context: {
currentOffset: state.get('currentOffset'),
circuitError: error || pathProblem
}
};
}
function begin() {
const actions = processEventQueue();
const oldState = state;
state = executor.executeAll(actions, oldState);
if (viewModelChanged(state, oldState)) {
// FIXME this will cause re-analysis even when hover-highlighting... could be better
// create a graph of the circuit that we can use to analyse
const nodes = toNodes(state.get('views'));
const edges = setNodesInModels(state.get('models'), nodes);
state = state.withMutations(s => {
s.set('nodes', nodes).set('models', edges);
});
}
}
return {
begin,
update
};
}
export default Updater;
| JavaScript | 0 | @@ -3585,50 +3585,8 @@
%5D;%0A%0A
- // queue all directly connected nodes%0A
@@ -3768,24 +3768,31 @@
gh the model
+ itself
%0A %7D%0A
|
415ee02f5306d09c9ca162f1b5924c7e4c0a0e4f | fix rate-limiting | config/rate-limit.js | config/rate-limit.js | /**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* 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.
*/
'use strict';
var extend = require('util')._extend;
function RateLimit(options) {
// this is shared by all endpoints that use this instance
var hits = {};
var timeouts = {};
options = extend({}, options, {
windowMs: 60 * 1000, // miliseconds - how long to keep records of requests in memory
delayMs: 0, // milliseconds - base delay applied to the response - multiplied by number of recent hits from user's IP
max: 3, // max number of recent connections during `window` miliseconds before sending a 400 response
global: false // if true, IP address is ignored and setting is applied equally to all requests
});
return {
limit: function limit(req, res, next) {
var ip = options.global ? 'global' : req.ip;
if (typeof hits[ip] !== 'number' || isNaN(hits[ip])) {
hits[ip] = 0; // first one's free ;)
} else {
hits[ip]++;
}
clearTimeout(timeouts[ip]);
timeouts[ip] = setTimeout(function() {
// cleanup
hits[ip]--;
if (hits[ip] <=0 ) {
delete hits[ip];
}
}, options.windowMs);
if (hits[ip] >= options.max) {
// 429 status = Too Many Requests (RFC 6585)
return res.status(429).json({
error: 'Too many requests, please try again later.',
code: 429
});
} else {
var delay = hits[ip] * options.delayMs;
setTimeout(next, delay);
}
},
reset: function reset(req, res, next) {
var ip = options.global ? 'global' : req.ip;
clearTimeout(timeouts[ip]);
delete hits[ip];
delete timeouts[ip];
next();
}
};
}
module.exports = RateLimit; | JavaScript | 0.000004 | @@ -930,16 +930,18 @@
elayMs:
+50
0, // mi
@@ -1054,9 +1054,9 @@
ax:
-3
+5
, //
@@ -1513,34 +1513,47 @@
%7D%0A
-%0A
c
-learTimeout(timeou
+onsole.log('limit:', ip, ':', hi
ts%5Bi
@@ -1557,16 +1557,17 @@
s%5Bip%5D);%0A
+%0A
ti
@@ -2163,24 +2163,71 @@
' : req.ip;%0A
+ console.log('reset:', ip, ':', hits%5Bip%5D);
%0A clear
|
058b63a88afc8b5e6013d554a6b19eef3c61a6c9 | remove space.. | js/solGS/combineTrials.js | js/solGS/combineTrials.js | /**
* trials search, selections to combine etc...
* @author Isaak Y Tecle <iyt2@cornell.edu>
*
*/
JSAN.use("Prototype");
JSAN.use('jquery.blockUI');
function getPopIds () {
jQuery('#homepage_trials_list tr').filter(':has(:checkbox:checked)')
.bind('click', function() {
jQuery("#done_selecting input").val('Done selecting');
var td = jQuery(this).html();
//alert(td);
var selectedTrial = '<tr>' + td + '</tr>';
jQuery("#selected_trials_table tr:last").after(selectedTrial);
jQuery("#selected_trials_table tr").each( function() {
jQuery(this).find("input[type=checkbox]")
.attr('onclick', 'removeSelectedTrial()')
.prop('checked', true);
});
});
jQuery("#selected_trials").show();
jQuery("#combine").show();
jQuery("#search_again").show();
}
function doneSelecting() {
jQuery("#homepage_trials_list").hide();
jQuery("#done_selecting").hide();
}
function removeSelectedTrial() {
jQuery("#selected_trials_table tr").on("change", function() {
jQuery(this).remove();
if( jQuery("#selected_trials_table td").doesExist() == false) {
jQuery("#selected_trials").hide();
jQuery("#combine").hide();
jQuery("#search_again").hide();
jQuery("#done_selecting input").val('Combine');
searchAgain();
}
});
}
function searchAgain () {
searchTrials();
jQuery("#done_selecting").show();
}
function downloadData() {
var trialIds = getSelectedTrials();
trialIds = trialIds.join(",");
var action = "/solgs/retrieve/populations/data";
jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
jQuery.blockUI({message: 'Please wait..'});
jQuery.ajax({
type: 'POST',
dataType: "json",
url: action,
data: {'trials' : trialIds},
success: function(res) {
if (res.not_matching_pops == null) {
var combinedPopsId = res.combined_pops_id;
jQuery.unblockUI();
// alert('all clones in all trials genotyped using the same RE');
goToCombinedTrialsPage(combinedPopsId);
} else {
if(res.not_matching_pops ) {
jQuery.unblockUI();
alert('populations ' + res.not_matching_pops +
' were genotyped using different marker sets. ' +
'Please make new selections to combine.' );
}
if (res.redirect_url) {
window.location.href = res.redirect_url;
}
}
},
error: function(res) {
alert('An error occured retrieving phenotype' +
'and genotype data for trials..');
}
});
}
function getSelectedTrials () {
var trialIds = [];
var selectedTrialsExist = jQuery("#selected_trials_table").doesExist();
if (selectedTrialsExist == true) {
jQuery("#selected_trials_table tr").each(function () {
var trialId = jQuery(this).find("input[type=checkbox]").val();
if (trialId) {
trialIds.push(trialId);
}
});
}
trialIds = trialIds.sort();
return trialIds;
}
function goToCombinedTrialsPage(combinedPopsId) {
var action = '/solgs/populations/combined/' + combinedPopsId;
if(combinedPopsId) {
window.location.href = action;
}
}
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
| JavaScript | 0.000015 | @@ -869,18 +869,16 @@
.show();
-%0A
%0A j
|
96e1ecaf4043f3f3a9649d6b15e6f8c94892558f | remove now unused local eval instance ID | ui/analyse/src/ceval/cevalCtrl.js | ui/analyse/src/ceval/cevalCtrl.js | var m = require('mithril');
var makePool = require('./cevalPool');
var dict = require('./cevalDict');
var util = require('../util');
var stockfishProtocol = require('./stockfishProtocol');
var sunsetterProtocol = require('./sunsetterProtocol');
module.exports = function(possible, variant, emit) {
var instanceId = Math.random().toString(36).substring(2).slice(0, 4);
var pnaclSupported = navigator.mimeTypes['application/x-pnacl'];
var minDepth = 7;
var maxDepth = util.storedProp('ceval.max-depth', 18);
var multiPv = util.storedProp('ceval.multipv', 1);
var threads = util.storedProp('ceval.threads', Math.ceil((navigator.hardwareConcurrency || 1) / 2));
var hashSize = util.storedProp('ceval.hash-size', 128);
var curDepth = 0;
var enableStorage = lichess.storage.make('client-eval-enabled');
var allowed = m.prop(true);
var enabled = m.prop(possible() && allowed() && enableStorage.get() == '1');
var started = false;
var pool;
if (variant.key !== 'crazyhouse') {
pool = makePool(stockfishProtocol, {
asmjs: '/assets/vendor/stockfish.js/stockfish.js',
pnacl: pnaclSupported && '/assets/vendor/stockfish.pexe/nacl/stockfish.nmf'
}, {
minDepth: minDepth,
maxDepth: maxDepth,
variant: variant,
multiPv: multiPv,
threads: pnaclSupported && threads,
hashSize: pnaclSupported && hashSize
});
} else {
pool = makePool(sunsetterProtocol, {
asmjs: '/assets/vendor/Sunsetter/sunsetter.js'
});
}
// adjusts maxDepth based on nodes per second
var npsRecorder = (function() {
var values = [];
var applies = function(res) {
return res.eval.nps && res.eval.depth >= 16 &&
!res.eval.mate && Math.abs(res.eval.cp) < 500 &&
(res.work.currentFen.split(/\s/)[0].split(/[nbrqkp]/i).length - 1) >= 10;
}
return function(res) {
if (!applies(res)) return;
values.push(res.eval.nps);
if (values.length >= 5) {
var depth = 18,
knps = util.median(values) / 1000;
if (knps > 100) depth = 19;
if (knps > 150) depth = 20;
if (knps > 250) depth = 21;
if (knps > 500) depth = 22;
if (knps > 1000) depth = 23;
if (knps > 2000) depth = 24;
if (knps > 3500) depth = 25;
maxDepth(depth);
if (values.length > 20) values.shift();
}
};
})();
var onEmit = function(res) {
res.instanceId = instanceId;
res.eval.maxDepth = res.work.maxDepth;
npsRecorder(res);
curDepth = res.eval.depth;
emit(res);
}
var start = function(path, steps, threatMode) {
if (!enabled() || !possible()) return;
var step = steps[steps.length - 1];
var existing = step[threatMode ? 'threat' : 'ceval'];
if (existing && existing.depth >= maxDepth()) return;
var work = {
initialFen: steps[0].fen,
moves: [],
currentFen: step.fen,
path: path,
ply: step.ply,
maxDepth: maxDepth(),
threatMode: threatMode,
emit: function(res) {
if (enabled()) onEmit(res);
}
};
if (threatMode) {
var c = step.ply % 2 === 1 ? 'w' : 'b';
var fen = step.fen.replace(/ (w|b) /, ' ' + c + ' ');
work.currentFen = fen;
work.initialFen = fen;
} else {
// send fen after latest castling move and the following moves
for (var i = 1; i < steps.length; i++) {
var step = steps[i];
if (step.san.indexOf('O-O') === 0) {
work.moves = [];
work.initialFen = step.fen;
} else work.moves.push(step.uci);
}
}
var dictRes = dict(work, variant, multiPv());
if (dictRes) {
setTimeout(function() {
// this has to be delayed, or it slows down analysis first render.
work.emit({
work: work,
eval: {
depth: maxDepth(),
cp: dictRes.cp,
best: dictRes.best,
mate: 0,
dict: true
}
});
}, 500);
pool.warmup();
} else pool.start(work);
started = true;
};
var stop = function() {
if (!enabled() || !started) return;
pool.stop();
started = false;
};
return {
instanceId: instanceId,
pnaclSupported: pnaclSupported,
start: start,
stop: stop,
allowed: allowed,
possible: possible,
enabled: enabled,
multiPv: multiPv,
threads: threads,
hashSize: hashSize,
toggle: function() {
if (!possible() || !allowed()) return;
stop();
enabled(!enabled());
enableStorage.set(enabled() ? '1' : '0');
},
curDepth: function() {
return curDepth;
},
maxDepth: maxDepth,
destroy: pool.destroy
};
};
| JavaScript | 0 | @@ -297,80 +297,8 @@
%7B%0A%0A
- var instanceId = Math.random().toString(36).substring(2).slice(0, 4);%0A
va
@@ -2337,41 +2337,8 @@
) %7B%0A
- res.instanceId = instanceId;%0A
@@ -4092,36 +4092,8 @@
n %7B%0A
- instanceId: instanceId,%0A
|
f89ff6456f2e09d00e8575cf5094622fe78fc44f | add "Signup Week" to people's mixpanel identities | src/util/analytics.js | src/util/analytics.js | import { get, partial } from 'lodash'
import { mostRecentCommunity } from '../models/person'
// These strings were not used prior to hylo-redux
export const ADDED_COMMUNITY = 'Add community'
export const EDITED_USER_SETTINGS = 'Edit user settings'
export const INVITED_COMMUNITY_MEMBERS = 'Invited community members'
// These strings correspond to the names of events in Mixpanel with historical
// data, so they should be changed with care
export const ADDED_COMMENT = 'Post: Comment: Add'
export const ADDED_POST = 'Add Post'
export const CLICKTHROUGH = 'Clickthrough'
export const EDITED_POST = 'Edit Post'
export const LOGGED_IN = 'Login success'
export const SHOWED_POST_COMMENTS = 'Post: Comments: Show'
export const STARTED_LOGIN = 'Login start'
export const STARTED_SIGNUP = 'Signup start'
export const VIEWED_COMMUNITY = 'Community: Load Community'
export const VIEWED_NOTIFICATIONS = 'Notifications: View'
export const VIEWED_PERSON = 'Member Profiles: Loaded a profile'
export const VIEWED_SELF = 'Member Profiles: Loaded Own Profile'
export function trackEvent (eventName, options = {}) {
const { person, post, tag, community, ...otherOptions } = options
const track = partial(window.analytics.track, eventName)
switch (eventName) {
case ADDED_COMMUNITY:
case VIEWED_COMMUNITY:
case INVITED_COMMUNITY_MEMBERS:
track({community: community.name})
break
case VIEWED_PERSON:
let { id, name } = person
track({id, name})
break
case ADDED_COMMENT:
case SHOWED_POST_COMMENTS:
track({post_id: post.id})
break
case ADDED_POST:
case EDITED_POST:
track({post_tag: tag, community: community.name})
break
case CLICKTHROUGH:
track({community, ...otherOptions})
break
case EDITED_USER_SETTINGS:
case LOGGED_IN:
case STARTED_LOGIN:
case STARTED_SIGNUP:
case VIEWED_NOTIFICATIONS:
case VIEWED_SELF:
track()
break
default:
const message = `Don't know how to handle event named "${eventName}"`
window.alert(message)
throw new Error(message)
}
return Promise.resolve()
}
export const identify = person => {
if (!person) return
let { id, name, email, post_count, created_at } = person
let community = mostRecentCommunity(person)
let account = person.linkedAccounts[0]
window.analytics.identify(id, {
email, name, post_count, createdAt: created_at,
provider: get(account, 'provider_key'),
community: get(community, 'name')
})
}
// this is used to make sure that all events, whether they were fired before or
// after signup, are assigned to the same user
export const alias = id => {
window.analytics.alias(id)
}
| JavaScript | 0 | @@ -85,16 +85,53 @@
/person'
+%0Aimport moment from 'moment-timezone'
%0A%0A// The
@@ -2540,16 +2540,95 @@
'name')
+,%0A 'Signup Week': moment.tz(created_at, 'UTC').startOf('week').toISOString()
%0A %7D)%0A%7D%0A
|
d6ed431194fc032d73d9f0e428502a4f8d1cfcb0 | remove unused ui/puzzle chessground option | ui/puzzle/src/view/chessground.js | ui/puzzle/src/view/chessground.js | var m = require('mithril');
var Chessground = require('chessground').Chessground;
module.exports = function(ctrl) {
return m('div.cg-board-wrap', {
config: function(el, isUpdate) {
if (!isUpdate) ctrl.ground(Chessground(el, makeConfig(ctrl)));
}
});
}
var global3d = document.getElementById('top').classList.contains('is3d');
function makeConfig(ctrl) {
var opts = ctrl.makeCgOpts();
return {
fen: opts.fen,
orientation: opts.orientation,
turnColor: opts.turnColor,
check: opts.check,
lastMove: opts.lastMove,
coordinates: ctrl.pref.coords !== 0,
addPieceZIndex: ctrl.pref.is3d || global3d,
movable: {
free: false,
color: opts.movable.color,
dests: opts.movable.dests,
rookCastle: ctrl.pref.rookCastle
},
draggable: {
enabled: ctrl.pref.moveEvent > 0,
showGhost: ctrl.pref.highlight
},
selectable: {
enabled: ctrl.pref.moveEvent !== 1
},
events: {
move: ctrl.userMove
},
premovable: {
enabled: opts.premovable.enabled
},
drawable: {
enabled: true
},
highlight: {
lastMove: ctrl.pref.highlight,
check: ctrl.pref.highlight,
dragOver: true
},
animation: {
enabled: true,
duration: ctrl.pref.animation.duration
},
disableContextMenu: true
};
}
| JavaScript | 0.000001 | @@ -1194,30 +1194,8 @@
ight
-,%0A dragOver: true
%0A
|
0bd1e9cf590bc7e61c159b952d0a5518b8611488 | fix #947 misspelled word cancel | src/utils/constant.js | src/utils/constant.js | export const ROLE_TYPE = {
ADMIN: 'admin',
DEFAULT: 'admin',
DEVELOPER: 'developer',
}
export const CANCEL_REQUEST_MESSAGE = 'cancle request'
| JavaScript | 0.000019 | @@ -134,10 +134,10 @@
canc
-l
e
+l
req
|
1e5eba8f1196fe542a50404e548a09ebf1173d6a | fix error | src/utils/dispatch.js | src/utils/dispatch.js | /*
* dispatch.js
* Fabian Irsara
* Copyright 2015, Licensed GPL & MIT
*/
define(function(){
/**
* helper function to dispatch event on a given object<br>
* optionally pass in data to the event
*
* @method dispatch
* @memberof utils
* @param {Object} obj which should dispatch the event
* @param {String} name custom event name
* @param {data} data (optional) that should be added to the event
**/
var dispatch = function(obj, name, data){
var event = new Event(name, {
bubbles: true,
cancelable: true
});
if (data && typeof data === 'object') {
for (var k in data) {
if (data.hasOwnProperty(k)) {
event[k] = data[k];
}
}
}
if (obj) {
obj.dispatchEvent(event);
}
return event;
};
/**
* helper function to create a custom event with optional data
*
* @method create
* @memberof utils.dispatch
* @param {String} name custom event name
* @param {data} data (optional) that should be added to the event
**/
dispatch.create = function(name, data){
var event = new Event(name, {
bubbles: true,
cancelable: true
});
if (data && typeof data === 'object') {
for (var k in data) {
if (data.hasOwnProperty(k)) {
event[k] = data[k];
}
}
}
return event;
};
return dispatch;
});
| JavaScript | 0.000002 | @@ -731,16 +731,37 @@
if (obj
+ && obj.dispatchEvent
) %7B%0A
|
77fb4a4028579f2aa4bd8bd7382aca1221205f81 | Add support for traversing plus and minus operations. | src/utils/traverse.js | src/utils/traverse.js | /**
* Traverses an AST node, calling a callback for each node in the hierarchy in
* source order.
*
* @param {Object} node
* @param {function(Object, function(Object), boolean): ?boolean} callback
*/
export default function traverse(node, callback) {
var descended = false;
function descend(node) {
descended = true;
childPropertyNames(node).forEach(property => {
const value = node[property];
if (Array.isArray(value)) {
value.forEach(child => {
child.parent = node;
traverse(child, callback);
});
} else if (value) {
value.parent = node;
traverse(value, callback);
}
});
}
const shouldDescend = callback(
node,
descend,
childPropertyNames(node).length === 0
);
if (!descended && shouldDescend !== false) {
descend(node);
}
}
/**
* Traverses an AST node, calling a callback for each node in the hierarchy
* depth-first in source order.
*
* @param {Object} node
* @param {function(Object, boolean): ?boolean} callback
*/
export function depthFirstTraverse(node, callback) {
traverse(node, (node, descend, isLeaf) => {
if (isLeaf) {
return callback(node, isLeaf);
} else {
descend(node);
return callback(node, isLeaf);
}
});
}
/**
* @param {Object} node
* @returns {string[]}
*/
function childPropertyNames(node) {
const names = ORDER[node.type];
if (!names) {
throw new Error('cannot traverse unknown node type: ' + node.type);
}
return names;
}
const ORDER = {
Program: ['body'],
ArrayInitialiser: ['members'],
AssignOp: ['assignee', 'expression'],
Block: ['statements'],
Bool: [],
BoundFunction: ['parameters', 'body'],
ConcatOp: ['left', 'right'],
Conditional: ['condition', 'consequent', 'alternate'],
DynamicMemberAccessOp: ['expression', 'indexingExpr'],
ForIn: ['keyAssignee', 'valAssignee', 'target', 'step', 'filter', 'body'],
ForOf: ['keyAssignee', 'valAssignee', 'target', 'filter', 'body'],
Function: ['parameters', 'body'],
FunctionApplication: ['function', 'arguments'],
Identifier: [],
Int: [],
LogicalAndOp: ['left', 'right'],
LogicalNotOp: ['expression'],
LogicalOrOp: ['left', 'right'],
MemberAccessOp: ['expression'],
NewOp: ['ctor', 'arguments'],
ObjectInitialiser: ['members'],
ObjectInitialiserMember: ['key', 'expression'],
ProtoMemberAccessOp: ['expression'],
Return: ['expression'],
SeqOp: ['left', 'right'],
String: [],
This: [],
While: ['condition', 'body']
};
| JavaScript | 0 | @@ -2372,16 +2372,45 @@
sion'%5D,%0A
+ PlusOp: %5B'left', 'right'%5D,%0A
ProtoM
@@ -2508,16 +2508,49 @@
ng: %5B%5D,%0A
+ SubtractOp: %5B'left', 'right'%5D,%0A
This:
|
1d9ec16d01ea54dabb046b1b798a64c8ae6279bd | Change turn rest api endpoint. | controller/index.js | controller/index.js | var Https = require('https');
var Common = require('./common');
exports.main = {
handler: function (request, reply) {
var params = Common.getRoomParameters(request, null, null, null);
reply.view('index_template', params);
}
};
exports.turn = {
handler: function (request, reply) {
var getOptions = {
host: 'instant.io',
port: 443,
path: '/rtcConfig',
method: 'GET'
};
Https.get(getOptions, function (result) {
console.log(result.statusCode == 200);
var body = '';
result.on('data', function (data) {
body += data;
});
result.on('end', function () {
reply(body);
});
}).on('error', function (e) {
reply({
"username":"webrtc",
"password":"webrtc",
"uris":[
"stun:stun.l.google.com:19302",
"stun:stun1.l.google.com:19302",
"stun:stun2.l.google.com:19302",
"stun:stun3.l.google.com:19302",
"stun:stun4.l.google.com:19302",
"stun:stun.services.mozilla.com",
"turn:turn.anyfirewall.com:443?transport=tcp"
]
});
});
}
};
| JavaScript | 0 | @@ -371,16 +371,18 @@
path: '/
+__
rtcConfi
@@ -382,16 +382,18 @@
tcConfig
+__
',%0A
|
aa688fee8ca39e5e7b276bdc16de22f759ddbb23 | Remove categorys | controllers/home.js | controllers/home.js | const moment = require('moment')
// const category = require('../models/category')
// const rssFeed = require('../models/rssFeed')
const rss = require('../models/rss')
// const CATEGORY_LIMIT = 10
// const CATEGORY_OFFSET = 1
const CATEGORY_ARRAY = [1, 2, 3, 4, 5, 6, 7, 8]
const CATEGORY_MAP = {
1: '資訊',
2: '正妹',
3: '生活',
4: '研究',
5: '資源',
6: 'iphoneapp',
7: '新聞',
8: '其他議題',
}
const RSS_LIMIT = 100
const RSS_OFFSET = 0
// rssFeed.readAll().then(
// function(result){
// // console.log('???', result)
// })
// category.readAll(
// CATEGORY_LIMIT,
// CATEGORY_OFFSET
// ).then(
// result => {
// // console.log('!!!', result.rows)
// result.rows.forEach( item => {
// })
// }
// )
const URL_LENGTH = 60
/**
* GET /
* Home page.
*/
exports.index = (req, res) => {
rss.readAll(RSS_LIMIT, RSS_OFFSET).then(
result => {
result.rows.forEach( item => {
// console.log('item', item)
// change time format
item.timeago = moment(item.createtimestamp).fromNow()
if (item.rssurl.length > URL_LENGTH) {
item.trimRssurl = item.rssurl.substring(0, URL_LENGTH - 3) + '...'
} else {
item.trimRssurl = item.rssurl
}
})
res.render('home', {
title: 'Welcome to Artifactblue',
categoryArray: CATEGORY_ARRAY,
categoryMap: CATEGORY_MAP,
result: result.rows,
})
}
)
}
| JavaScript | 0.000093 | @@ -252,16 +252,18 @@
%5B1, 2, 3
+/*
, 4, 5,
@@ -269,16 +269,18 @@
6, 7, 8
+*/
%5D%0Aconst
@@ -330,16 +330,19 @@
'%E7%94%9F%E6%B4%BB',%0A
+ //
4: '%E7%A0%94%E7%A9%B6'
@@ -344,16 +344,19 @@
'%E7%A0%94%E7%A9%B6',%0A
+ //
5: '%E8%B3%87%E6%BA%90'
@@ -358,16 +358,19 @@
'%E8%B3%87%E6%BA%90',%0A
+ //
6: 'iph
@@ -379,16 +379,19 @@
eapp',%0A
+ //
7: '%E6%96%B0%E8%81%9E'
@@ -393,16 +393,19 @@
'%E6%96%B0%E8%81%9E',%0A
+ //
8: '%E5%85%B6%E4%BB%96%E8%AD%B0
|
20595e01609d1983b81c3151a26498e3e6238e07 | Update room.js add parseAuthHeader method | controllers/room.js | controllers/room.js | const async = require('async');
const crypto = require('crypto');
const nodemailer = require('nodemailer');
const passport = require('passport');
const Room = require('../models/Room');
const User = require('../models/User');
exports.testBasicAuth = (req, res, next) => {
res.json({ "username": req.user.username });
};
exports.findAll = (req, res, next) => {
res.json({ username: req.user.username, email: user.email });
};
exports.findById = (req, res, next) => {
res.json({ username: req.user.username, email: user.email });
};
exports.addRoom = (req, res, next) => {
res.json({ username: req.user.username, email: user.email });
};
exports.updateRoom = (req, res, next) => {
res.json({ username: req.user.username, email: user.email });
};
exports.deleteRoom = (req, res, next) => {
res.json({ username: req.user.username, email: req.user.emails[0].value });
};
| JavaScript | 0.000001 | @@ -224,99 +224,1011 @@
);%0A%0A
-exports.testBasicAuth = (req, res, next) =%3E %7B%0A res.json(%7B %22username%22: req.user.username
+var parseAuthHeader = function(req,res) %7B%0A%09var auth = req.headers%5B'authorization'%5D; // auth is in base64(username:password) so we need to decode the base64%0A%09console.log(%22Authorization Header is: %22, auth);%0A%09var tmp = auth.split(' '); // Split on a space, the original auth looks like %22Basic Y2hhcmxlczoxMjM0NQ==%22 and we need the 2nd part%0A%09var buf = new Buffer(tmp%5B1%5D, 'base64'); // create a buffer and tell it the data coming in is base64%0A%09var plain_auth = buf.toString(); // read it back out as a string%0A%09console.log(%22Decoded Authorization %22, plain_auth);%0A%09// At this point plain_auth = %22username:password%22%0A%09var creds = plain_auth.split(':'); // split on a ':'%0A%09var username = creds%5B0%5D;%0A%09var password = creds%5B1%5D;%0A%09console.log(%22username=%22+username+ %22 password=%22+password);%0A%09return username;%0A%7D;%0A%0Aexports.testBasicAuth = (req, res, next) =%3E %7B%0A%09email = parseAuthHeader(req,res);%0A%09User.findOne(%7B email: email %7D, (err, user) =%3E %7B%0A%09 if (err) %7B return next(err)%7D; %0A res.send(user);%0A%09
%7D);%0A
|
0f6cc85b5d171ddcc2aba24f375301e51f922a33 | add GET handler | controllers/task.js | controllers/task.js | 'use strict';
const mongoose = require('mongoose');
const express = require('express');
const path = require('path');
const db = require('../lib/db');
const app = express();
const router = express.Router();
const core = require('../src/core');
const prefix = '/tasks';
module.exports = (parent) => {
app.disable('x-powered-by');
app.set('trust proxy', parent.get('trust proxy'));
app.set('views', path.join(__dirname, '..', 'views', 'task'));
core.logger.verbose('Init:');
core.logger.verbose(`\t\tGET -> ${prefix}`);
router.get('/', (req, res, next) => {
db.UserModel.find().exec((err, users) => {
if (err) {
next(err);
} else {
var content = parent.wordsList['user'][res.locals.lang]['index'];
content.data = users;
res.render('index', content);
}
});
});
router.param('id', function (req, res, next, id) {
try {
req.taskId = mongoose.Types.ObjectId(id);
db.TaskModel.findById(req.taskId, (err, task) => {
if (err) {
next(err);
} else if (!task) {
err = new Error('Task not found');
err.apiError = 'not_found';
next(err);
} else {
req.currentTask = task;
next();
}
});
} catch (e) {
next(e);
}
});
core.logger.verbose(`\t\tGET -> ${prefix}/:id`);
router.get('/:id', (req, res, next) => {
if (req.xhr) {
res.json({ok: true, data: req.currentTask});
} else {
res.render('index');
}
});
core.logger.verbose(`\t\tGET -> ${prefix}/:id/status`);
router.get('/:id/status', (req, res, next) => {
if (req.xhr) {
res.json({ok: true, data: {status: req.currentTask.status}});
} else {
res.render('index');
}
});
app.use(prefix, parent.authorize, router);
parent.use(app);
}; | JavaScript | 0.000001 | @@ -1702,32 +1702,154 @@
%7D else %7B%0A
+ var content = parent.wordsList%5B'task'%5D%5Bres.locals.lang%5D%5B'index'%5D;%0A content.data = req.currentTask;%0A
res.
@@ -1854,32 +1854,41 @@
s.render('index'
+, content
);%0A %7D%0A
@@ -2009,35 +2009,8 @@
%3E %7B%0A
- if (req.xhr) %7B%0A
@@ -2079,68 +2079,8 @@
%7D);%0A
- %7D else %7B%0A res.render('index');%0A %7D%0A
|
cf0d35cf832c4ef9fcb8ffb575ee1300098c32cf | should be lowercase | routes/format_bulk.js | routes/format_bulk.js | var libphonenumber = require('libphonenumber');
var Q = require('Q');
var express = require('express');
var router = express.Router();
function returnWithResult(number, deferred){
return function(error, result){
if (error){
deferred.resolve({
number:number,
message:error.message
});
}else{
deferred.resolve({
number:number,
result:result
});
}
}
}
function forAllNumbersWithCountryCode(numbers, country_code, format){
var array = [];
numbers.forEach(function(number){
var deferred = Q.defer();
format(number,
country_code,
returnWithResult(number, deferred));
array.push(deferred.promise);
});
return Q.all(array);
}
function hasAnError(results){
return results.some(function(result){ return 'message' in result; });
}
function respondWithJson(res){
return function(results){
if (hasAnError(results)){
res.status(422);
}
res.json(results);
};
}
router.get('/e164/:country_code/:numbers', function(req, res) {
var numbers = req.params.numbers.split(',');
var country_code = req.params.country_code;
forAllNumbersWithCountryCode(numbers, country_code, libphonenumber.e164).then(respondWithJson(res));
});
router.get('/intl/:country_code/:numbers', function(req, res) {
var numbers = req.params.numbers.split(',');
var country_code = req.params.country_code;
forAllNumbersWithCountryCode(numbers, country_code, libphonenumber.intl).then(respondWithJson(res));
});
router.post('/e164/:country_code', function(req, res) {
var numbers = req.body.numbers.split(',');
var country_code = req.params.country_code;
forAllNumbersWithCountryCode(numbers, country_code, libphonenumber.e164).then(respondWithJson(res));
});
router.post('/intl/:country_code', function(req, res) {
var numbers = req.body.numbers.split(',');
var country_code = req.params.country_code;
forAllNumbersWithCountryCode(numbers, country_code, libphonenumber.intl).then(respondWithJson(res));
});
module.exports = router;
| JavaScript | 1 | @@ -58,17 +58,17 @@
equire('
-Q
+q
');%0Avar
|
31e8dc968edcd70841d9dc628564561c1d8f5fbc | Update quickstart.js | samples/quickstart.js | samples/quickstart.js | var thecallr = require('thecallr');
try {
// initialize instance Thecallr
// set your credentials or an Exception will raise
var tc = new thecallr.api("login", "password");
// Basic example
// Example to send a SMS
// 1. "call" method: each parameter of the method as an argument
tc.call("sms.send", "THECALLR", "+33123456789", "Hello, world", {
flash_message: false
})
.success(function(data) {
console.log("Response:", data);
})
.error(function(error) {
console.error("\nError:", error.message);
console.error("Code:", error.code);
console.error("Data:", error.data);
});
// 2. "send" method: parameter of the method is an array
var my_array = ["THECALLR", "+33123456789", "Hello, world", {
"flash_message": false
}];
tc.send("sms.send", my_array)
.success(function(data) {
console.log("Success 2", data);
})
.error(function(error) {
console.error("\nError:", error.message);
console.error("Code:", error.code);
console.error("Data:", error.data);
});
}
catch (e) {
console.error("Fatal error");
console.error(e);
}
| JavaScript | 0.000001 | @@ -858,17 +858,19 @@
og(%22
-Success
+Response
2
+:
%22, d
|
c6916a166871ad4e26ed33513784f5fbb746e679 | set as action so it only notifies once | tutor/src/models/course/task-plans.js | tutor/src/models/course/task-plans.js | import { computed, observable, action } from 'mobx';
import { find } from 'lodash';
import Map from 'shared/model/map';
import TaskPlan from '../task-plan/teacher';
export default class CourseTaskPlans extends Map {
@observable course;
constructor(attrs) {
super();
this.course = attrs.course;
}
get chainedValues() {
return { course: this.course };
}
withPlanId(planId) {
let plan = this.get(planId);
if (!plan) {
plan = new TaskPlan({ id: planId });
this.set(planId, plan);
}
return plan;
}
@action onPlanSave(oldId, planAttrs) {
let tp = this.get(oldId);
if (tp) {
tp.update(planAttrs);
} else {
tp = new TaskPlan(planAttrs);
}
this.set(planAttrs.id, tp);
if (oldId != tp.id) {
this.delete(oldId);
}
}
addClone(planAttrs) {
this.set(planAttrs.id, new TaskPlan(planAttrs));
}
@computed get active() {
return this.where(plan => !plan.is_deleting);
}
@computed get isPublishing() {
return this.where(plan => plan.isPublishing);
}
@computed get hasPublishing() {
return Boolean(find(this.array, 'isPublishing'));
}
@computed get reading() {
return this.where(plan => plan.type === 'reading');
}
@computed get homework() {
return this.where(plan => plan.type === 'homework');
}
@computed get pastDue() {
return this.where(plan => plan.isPastDue);
}
@computed get open() {
return this.where(plan => plan.isOpen);
}
withPeriodId(periodId) {
return this.where(plan => find(plan.tasking_plans, { target_id: periodId }));
}
pastDueWithPeriodId(periodId) {
return this.where(plan => plan.isPastDueWithPeriodId(periodId));
}
// called from api
fetch() { }
onLoaded({ data: { plans } }) {
plans.forEach(plan => {
const tp = this.get(plan.id);
tp ? tp.update(plan) : this.set(plan.id, new TaskPlan(plan));
});
}
}
| JavaScript | 0 | @@ -1747,16 +1747,24 @@
) %7B %7D%0A
+@action
onLoaded
|
d9b3fe6871e84d43b11acbe87e96417b90259d08 | Update mediascape.js | helloworld/Triggers/js/mediascape/mediascape.js | helloworld/Triggers/js/mediascape/mediascape.js | //main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
document.head.appendChild(rscript);
return;
}
require.config({
baseUrl: 'js/',
paths: {
// the left side is the module ID,
// the right side is the path to
// the jQuery file, relative to baseUrl.
// Also, the path should NOT include
// the '.js' file extension. This example
// is using jQuery 1.8.2 located at
// js/jquery-1.8.2.js, relative to
// the HTML page.
jquery: 'lib/jquery-2.1.3.min',
namedwebsockets: 'lib/namedwebsockets',
qrcode: 'lib/qrcode.min',
webcodecam:'lib/WebCodeCam.min',
qrcodelib:'lib/qrcodelib',
socketio: '/socket.io/socket.io',
shake: 'lib/shake'
}
});
// Start the main app logic.
define("mediascape", ["mediascape/Agentcontext/agentcontext",
"mediascape/Association/association",
"mediascape/Discovery/discovery",
"mediascape/DiscoveryAgentContext/discoveryagentcontext",
"mediascape/Sharedstate/sharedstate",
"mediascape/Mappingservice/mappingservice",
"mediascape/Applicationcontext/applicationcontext"], function ($, Modules) {
//jQuery, modules and the discovery/modules module are all.
//loaded and can be used here now.
//creation of mediascape and discovery objects.
var mediascape = {};
var moduleList = Array.prototype.slice.apply(arguments);
mediascape.init = function (options) {
mediascapeOptions = {};
_this = Object.create(mediascape);
for (var i = 0; i < moduleList.length; i++) {
var name = moduleList[i].__moduleName;
var dontCall = ['sharedState', 'mappingService', 'applicationContext'];
if (dontCall.indexOf(name) === -1) {
mediascape[name] = new moduleList[i](mediascape, "gq" + i, mediascape);
} else {
mediascape[name] = moduleList[i];
}
}
return _this;
};
mediascape.version = "0.0.1";
// See if we have any waiting init calls that happened before we loaded require.
if (window.mediascape) {
var args = window.mediascape.__waiting;
delete window.mediascape;
if (args) {
mediascape.init.apply(this, args);
}
}
window.mediascape = mediascape;
//return of mediascape object with discovery and features objects and its functions
return mediascape;
});
require(["mediascape"], function (mediascape) {
mediascape.init();
/**
*
* Polyfill for custonevents
*/
(function () {
function CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var event = new CustomEvent("mediascape-ready", {
"detail": {
"loaded": true
}
});
document.dispatchEvent(event);
});
}());
| JavaScript | 0 | @@ -805,16 +805,237 @@
L page.%0A
+ receiver: 'https://www.gstatic.com/cast/sdk/libs/receiver/2.0.0/cast_receiver',%0A sender:'https://www.gstatic.com/cv/js/sender/v1/cast_sender',%0A presentation: 'lib/presentation-api-shim',%0A
|
36713585b6c2d416c441b358e8a3daccd29d9846 | use 'this' instead of global 'events' | src/docs/js/generateEventsHelper.js | src/docs/js/generateEventsHelper.js | /*global args*/
args = Array.prototype.slice.call(args, 1);
// [0] = type, [1] = lib.jar [2] = blockX, [3] = classX
var File = java.io.File,
FileReader = java.io.FileReader,
FileInputStream = java.io.FileInputStream,
FRAMEWORK = args[0],
out = java.lang.System.out,
err = java.lang.System.err,
Modifier = java.lang.reflect.Modifier,
clz,
ZipInputStream = java.util.zip.ZipInputStream,
zis = new ZipInputStream(new FileInputStream(args[1])),
entry = null;
var content = [
'/*********************',
'## Events Helper Module (' + FRAMEWORK + ' version)',
'The Events helper module provides a suite of functions - one for each possible event.',
'For example, the events.' +
args[2] +
'() function is just a wrapper function which calls events.on(' +
args[3] +
', callback, priority)',
'This module is a convenience wrapper for easily adding new event handling functions in Javascript. ',
'At the in-game or server-console prompt, players/admins can type `events.` and use TAB completion ',
'to choose from any of the approx. 160 different event types to listen to.',
'',
'### Usage',
'',
' events.' + args[2] + '( function( event ) { ',
" echo( event.player, 'You broke a block!'); ",
' });',
'',
'The crucial difference is that the events module now has functions for each of the built-in events. The functions are accessible via TAB-completion so will help beginning programmers to explore the events at the server console window.',
'',
'***/'
];
var canary = false;
if (FRAMEWORK == 'CanaryMod') {
canary = true;
}
for (var i = 0; i < content.length; i++) {
out.println(content[i]);
}
var names = [];
while ((entry = zis.nextEntry) != null) {
names.push(String(entry.name));
}
names.sort();
names.forEach(function(name) {
var re1 = /org\/bukkit\/event\/.+Event\.class$/;
if (canary) {
re1 = /net\/canarymod\/hook\/.+Hook\.class$/;
}
if (re1.test(name)) {
name = name.replace(/\//g, '.').replace('.class', '');
try {
clz = java.lang.Class.forName(name);
} catch (e) {
err.println('Warning: could not Class.forName("' + name + '")');
clz = engine.eval(name);
}
var isAbstract = Modifier.isAbstract(clz.getModifiers());
if (isAbstract) {
return;
}
var parts = name.split('.');
var shortName = null;
if (canary) {
shortName = name.replace('net.canarymod.hook.', '');
}
if (!canary) {
shortName = name.replace('org.bukkit.event.', '');
}
var fname = parts
.reverse()
.shift()
.replace(/^(.)/, function(a) {
return a.toLowerCase();
});
if (!canary) {
fname = fname.replace(/Event$/, '');
}
if (canary) {
fname = fname.replace(/Hook$/, '');
}
var javaDoc = canary
? 'https://ci.visualillusionsent.net/job/CanaryLib/javadoc/net/canarymod/hook/'
: 'https://hub.spigotmc.org/javadocs/spigot/org/bukkit/event/';
var comment = [
'/*********************',
'### events.' + fname + '()',
'',
'#### Parameters',
'',
' * callback - A function which is called whenever the [' +
shortName +
' event](' +
javaDoc +
shortName.replace('.', '/') +
'.html) is fired',
'',
' * priority - optional - see events.on() for more information.',
'',
'***/'
//http://jd.bukkit.org/rb/apidocs/org/bukkit/event/player/PlayerJoinEvent.html
];
for (var i = 0; i < comment.length; i++) {
out.println(comment[i]);
}
out.println('exports.' + fname + ' = function(callback,priority){ ');
if (canary) {
out.println(
' return events.on(Packages.' + name + ',callback,priority);'
);
} else {
out.println(' return events.on(' + name + ',callback,priority);');
}
out.println('};');
}
});
| JavaScript | 0.999999 | @@ -3690,29 +3690,27 @@
' return
-event
+thi
s.on(Package
@@ -3795,21 +3795,19 @@
return
-event
+thi
s.on(' +
|
96f19a3d8937b075080ad70d304ecfa4136b6ff9 | Replace YellowBox references with LogBox | Libraries/Utilities/RCTLog.js | Libraries/Utilities/RCTLog.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
const invariant = require('invariant');
const levelsMap = {
log: 'log',
info: 'info',
warn: 'warn',
error: 'error',
fatal: 'error',
};
let warningHandler: ?(Array<any>) => void = null;
const RCTLog = {
// level one of log, info, warn, error, mustfix
logIfNoNativeHook(level: string, ...args: Array<any>): void {
// We already printed in the native console, so only log here if using a js debugger
if (typeof global.nativeLoggingHook === 'undefined') {
RCTLog.logToConsole(level, ...args);
} else {
// Report native warnings to YellowBox
if (warningHandler && level === 'warn') {
warningHandler(...args);
}
}
},
// Log to console regardless of nativeLoggingHook
logToConsole(level: string, ...args: Array<any>): void {
const logFn = levelsMap[level];
invariant(
logFn,
'Level "' + level + '" not one of ' + Object.keys(levelsMap).toString(),
);
console[logFn](...args);
},
setWarningHandler(handler: typeof warningHandler): void {
warningHandler = handler;
},
};
module.exports = RCTLog;
| JavaScript | 0 | @@ -793,14 +793,11 @@
to
-Yellow
+Log
Box%0A
|
b77ad8bde8802ab7a8ff7435840362c9b7047724 | Add undefined check | src/duration-picker/DurationCard.js | src/duration-picker/DurationCard.js | import React, { Component, PropTypes } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
import { FormattedMessage } from 'react-intl';
import ErrorMsg from '../_common/ErrorMsg';
import SelectGroup from '../_common/SelectGroup';
import InputGroup from '../_common/InputGroup';
import ForwardStartingOptions from './ForwardStartingOptions';
import { durationText } from '../_utils/TradeUtils';
import ToggleSwitch from '../_common/ToggleSwitch';
export default class DurationCard extends Component {
static propTypes = {
dateStart: PropTypes.number,
duration: PropTypes.number,
durationUnit: PropTypes.string,
forwardStartingDuration: PropTypes.object, // treated as special case
options: PropTypes.array,
onUnitChange: PropTypes.func,
onDurationChange: PropTypes.func,
onStartDateChange: PropTypes.func,
};
shouldComponentUpdate = shouldPureComponentUpdate;
startLaterHandler() {
const { dateStart, onStartDateChange, forwardStartingDuration } = this.props;
if (dateStart) {
onStartDateChange();
} else {
const nextDay = forwardStartingDuration.range[1];
const nextDayOpening = Math.floor(nextDay.open[0].getTime() / 1000);
onStartDateChange(nextDayOpening);
}
}
render() {
const {
dateStart,
duration,
durationUnit,
forwardStartingDuration,
options,
onUnitChange,
onDurationChange,
onStartDateChange,
} = this.props;
const allowStartLater = !!forwardStartingDuration;
const onlyStartLater = allowStartLater && !options;
const forwardOptions = forwardStartingDuration.options;
let optionsToUse;
if (onlyStartLater) {
optionsToUse = forwardOptions;
} else if (!allowStartLater) {
optionsToUse = options;
} else {
optionsToUse = !!dateStart ? forwardOptions : options;
}
const unitOptions = optionsToUse.map(opt => ({ value: opt.unit, text: durationText(opt.unit) }));
const currentUnitBlock = optionsToUse.find(opt => opt.unit === durationUnit);
const min = currentUnitBlock && currentUnitBlock.min;
const max = currentUnitBlock && currentUnitBlock.max;
const showError = duration > max || duration < min;
const errorMsg = (duration > max ? `Maximum is ${max} ` : `Minimum is ${min} `) + durationText(durationUnit);
return (
<div>
{(allowStartLater && !onlyStartLater) &&
<FormattedMessage id="Start_Later" defaultMessage="Start Later">
{text =>
<ToggleSwitch
text={text}
checked={!!dateStart}
onClick={::this.startLaterHandler}
disabled={onlyStartLater}
/>
}
</FormattedMessage>
}
{!!dateStart &&
<ForwardStartingOptions
dateStart={dateStart}
ranges={forwardStartingDuration.range}
onStartDateChange={onStartDateChange}
/>
}
{currentUnitBlock ?
<div id="duration-fields" className="row">
<InputGroup
type="number"
value={duration}
min={min}
max={max}
onChange={onDurationChange}
/>
<SelectGroup
options={unitOptions}
value={durationUnit}
onChange={onUnitChange}
/>
</div> :
<div />
}
<ErrorMsg shown={showError} text={errorMsg} />
</div>
);
}
}
| JavaScript | 0.000003 | @@ -1784,16 +1784,43 @@
ptions =
+ forwardStartingDuration &&
forward
|
59c01c69fd317a4c7a30c2a899872ef7aeade856 | rename _get_form() -> _get_form_data() | src/view/node_info.js | src/view/node_info.js | define(['jquery', 'jquery-ui', 'view/helpers', 'view/internal'],
function($, _unused_jquery_ui, view_helpers, internal) {
var d = null,
submit_callback = null,
delete_callback = null;
function _get_form() {
return {
name: $('.info #editformname').val(),
type: $('.info #edittype').val(),
url: $('.info #editurl').val(),
status: $('.info #editstatus').val(),
startdate: $("#editstartdate").val(),
enddate: $("#editenddate").val(),
};
}
//internal.edit_tab.get('node', "#editbox").submit(function(e) {
// if (submit_callback) {
// return submit_callback(e, _get_form_data());
// }
// console.log('bug: edit tab submit called with no callback set');
// e.preventDefault();
//})
//internal.edit_tab.get('node', "#deletenode").click(function(e) {
// if (delete_callback) {
// return delete_callback(e, _get_form_data());
// }
// console.log('bug: edit tab delete called with no callback set');
// e.preventDefault();
//});
function show(d) {
var info = $('.info'),
f = false,
t = true,
visible = {
"third-internship-proposal": [t, t, t, f, f],
"chainlink": [f, f, f, f, f],
"skill": [f, f, f, f, t],
"interest": [f, f, f, f, t],
"_defaults": [f, f, f, f, t],
},
fields = ["#status", "#startdate", "#enddate", "#desc", "#url"],
flags = visible.hasOwnProperty(d.type) ? visible[d.type] : visible._defaults,
i;
internal.edit_tab.show('node');
for (i = 0 ; i < flags.length; ++i) {
var elem = info.find(fields[i]);
elem[flags[i] ? 'show' : 'hide']();
}
$('.info').attr('class', 'info');
$('.info').addClass('type-' + d.type); // Add a class to distinguish types for css
$('.info').find('#editformname').val(d.name);
$("#editenddate").datepicker({
inline: true,
showOtherMonths: true,
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
});
$("#editstartdate").datepicker({
inline: true,
showOtherMonths: true,
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
});
$('#editdescription').val(d.type);
$('#edittype').val(d.type);
$('#editurl').val(d.url);
$('#editstatus').val(d.status);
if (d.type === "third-internship-proposal") {
$('#editstartdate').val(d.start);
$('#editenddate').val(d.end);
}
}
function hide()
{
internal.edit_tab.hide();
}
function on_save(f) {
$('#edit-node-dialog__save').click(function(e) {
return f(e, _get_form_data());
});
}
function on_delete(f) {
$('#edit-node-dialog__delete').click(function(e) {
return f(e, _get_form_data());
});
}
function on_keyup(f) {
$('.info').keyup(function(e) {
return f(e, _get_form_data());
});
}
return {
show: show,
hide: hide,
on_submit: on_submit,
on_delete: on_delete,
};
});
| JavaScript | 0.000103 | @@ -206,16 +206,21 @@
get_form
+_data
() %7B%0A
|
4312a880e7521b7a3aa6b8439bb2f7db6bcccc38 | fix lint error | ui/src/utils/private/click-outside.js | ui/src/utils/private/click-outside.js | import { listenOpts } from '../event.js'
let timer
const
{ notPassiveCapture } = listenOpts,
registeredList = []
function hasModalsAbove (node) {
while ((node = node.nextElementSibling) !== null) {
if (node.classList.contains('q-dialog--modal')) {
return true
}
}
return false
}
function globalHandler (evt) {
clearTimeout(timer)
const target = evt.target
if (
target === void 0
|| target.nodeType === 8
|| target.classList.contains('no-pointer-events') === true
) {
return
}
for (let i = registeredList.length - 1; i >= 0; i--) {
const state = registeredList[ i ]
if (
(
state.anchorEl.value === null
|| state.anchorEl.value.contains(target) === false
)
&& (
target === document.body
|| (state.innerRef.value !== null && state.innerRef.value.contains(target) === false)
)
&& (
state.getEl !== void 0
? hasModalsAbove(state.getEl()) !== true
: true
)
) {
// mark the event as being processed by clickOutside
// used to prevent refocus after menu close
evt.qClickOutside = true
state.onClickOutside(evt)
}
else {
return
}
}
}
export function addClickOutside (clickOutsideProps) {
registeredList.push(clickOutsideProps)
if (registeredList.length === 1) {
document.addEventListener('mousedown', globalHandler, notPassiveCapture)
document.addEventListener('touchstart', globalHandler, notPassiveCapture)
}
}
export function removeClickOutside (clickOutsideProps) {
const index = registeredList.findIndex(h => h === clickOutsideProps)
if (index > -1) {
registeredList.splice(index, 1)
if (registeredList.length === 0) {
clearTimeout(timer)
document.removeEventListener('mousedown', globalHandler, notPassiveCapture)
document.removeEventListener('touchstart', globalHandler, notPassiveCapture)
}
}
}
| JavaScript | 0.000001 | @@ -821,17 +821,16 @@
f.value
-
!== null
|
4145f4d19c19a7fc77a853ce026ab8e38934b92d | update tests | src/main/webapp/openlmis-currency/openlmis-currency.controller.spec.js | src/main/webapp/openlmis-currency/openlmis-currency.controller.spec.js | /*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2013 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 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. For additional information contact info@OpenLMIS.org.
*/
describe('ForgotPasswordController', function() {
var $rootScope, $q, vm, currencyService, $scope;
beforeEach(function() {
module('openlmis-currency');
inject(function (_$rootScope_, $controller, _$q_, _currencyService_) {
$rootScope = _$rootScope_;
$q = _$q_;
currencyService = _currencyService_;
$scope = $rootScope.$new();
vm = $controller('CurrencyController', {$scope: $scope});
});
});
it('should format money with currency symbol on left', function() {
var currencySettings = {};
currencySettings['currencySymbol'] = '$';
currencySettings['currencySymbolSide'] = 'left';
spyOn(currencyService, 'get').andReturn($q.when(currencySettings));
$scope.value = 23.43;
$scope.$apply();
expect(vm.valueCurrency).toEqual('$ 23.43');
});
it('should format money with currency symbol on right', function() {
var currencySettings = {};
currencySettings['currencySymbol'] = 'zł';
currencySettings['currencySymbolSide'] = 'right';
spyOn(currencyService, 'get').andReturn($q.when(currencySettings));
$scope.value = 23.43;
$scope.$apply();
expect(vm.valueCurrency).toEqual('23.43 zł');
});
});
| JavaScript | 0 | @@ -845,22 +845,16 @@
be('
-ForgotPassword
+Currency
Cont
@@ -1532,16 +1532,71 @@
'left';
+%0A currencySettings%5B'currencyDecimalPlaces'%5D = 2;
%0A%0A
@@ -2000,16 +2000,71 @@
'right';
+%0A currencySettings%5B'currencyDecimalPlaces'%5D = 2;
%0A%0A
|
2efa9a7cd6e405805c20479e4363b6cff4e1c41c | update unit test | src/etl/dim-division-etl-manager.js | src/etl/dim-division-etl-manager.js | 'use strict'
// external deps
var ObjectId = require("mongodb").ObjectId;
var BaseManager = require('module-toolkit').BaseManager;
var moment = require("moment");
// internal deps
require('mongodb-toolkit');
var DivisionManager = require('../managers/master/division-manager');
module.exports = class DimDivisionEtlManager extends BaseManager {
constructor(db, user, sql) {
super(db, user);
this.sql = sql;
this.divisionManager = new DivisionManager(db, user);
}
run() {
return this.extract()
.then((data) => {
return this.transform(data)
})
.then((data) => {
return this.load(data)
});
}
extract() {
var timestamp = new Date(1970, 1, 1);
return this.divisionManager.collection.find({
_deleted: false
}).toArray();
}
transform(data) {
var result = data.map((item) => {
return {
divisionCode: item.code,
divisionName: item.name
};
});
return Promise.resolve([].concat.apply([], result));
}
load(data) {
return this.sql.getConnection()
.then((request) => {
var sqlQuery = '';
var count = 1;
for (var item of data) {
sqlQuery = sqlQuery.concat("insert into DL_Dim_Divisi(ID_Dim_Divisi, Kode_Divisi, Nama_Divisi) values(" + count + ", '" + item.divisionCode + "', '" + item.divisionName + "'); ");
count = count + 1;
}
request.multiple = true;
return request.query(sqlQuery)
// return request.query('select count(*) from dimdivisi')
// return request.query('select top 1 * from dimdivisi')
.then((results) => {
console.log(results);
return Promise.resolve();
})
})
.catch((err) => {
console.log(err);
return Promise.reject(err);
});
}
}
| JavaScript | 0 | @@ -567,33 +567,8 @@
) =%3E
- %7B%0A return
thi
@@ -584,30 +584,16 @@
rm(data)
-%0A %7D
)%0A
@@ -617,33 +617,8 @@
) =%3E
- %7B%0A return
thi
@@ -629,30 +629,16 @@
ad(data)
-%0A %7D
);%0A %7D
|
76cab7f168edf5e13b43897ef5b6f1a1637338b1 | Add update to Wizard styles | src/widgets/Wizard.js | src/widgets/Wizard.js | /* eslint-disable import/no-named-as-default */
/* eslint-disable react/forbid-prop-types */
import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { StyleSheet, View } from 'react-native';
import { Stepper } from './Stepper';
import { TabNavigator } from './TabNavigator';
import DataTablePageView from './DataTablePageView';
import { WizardActions } from '../actions/WizardActions';
import { selectCurrentTab } from '../selectors/wizard';
import { PAGE_CONTENT_PADDING_HORIZONTAL } from '../globalStyles/pageStyles';
import { BACKGROUND_COLOR, BLUE_WHITE, SHADOW_BORDER } from '../globalStyles/colors';
/**
* Layout component for a Tracker and TabNavigator, displaying steps
* to completion for completion. See TabNavigator and StepsTracker
* for individual component implementation.
*/
const WizardComponent = ({ tabs, currentTab, switchTab, useNewStepper }) => {
const titles = useMemo(() => tabs.map(tab => tab.title), [tabs]);
return (
<View style={localStyles.container}>
<View style={localStyles.stepperContainer}>
<Stepper
useNewStepper={useNewStepper}
numberOfSteps={tabs.length}
currentStep={currentTab}
onPress={switchTab}
titles={titles}
/>
</View>
<DataTablePageView>
<TabNavigator tabs={tabs} currentTabIndex={currentTab} />
</DataTablePageView>
</View>
);
};
const localStyles = StyleSheet.create({
container: { backgroundColor: BACKGROUND_COLOR, flex: 1 },
stepperContainer: {
backgroundColor: BLUE_WHITE,
borderColor: SHADOW_BORDER,
marginBottom: 2,
marginHorizontal: PAGE_CONTENT_PADDING_HORIZONTAL,
},
});
WizardComponent.defaultProps = {
useNewStepper: false,
};
WizardComponent.propTypes = {
tabs: PropTypes.array.isRequired,
switchTab: PropTypes.func.isRequired,
currentTab: PropTypes.number.isRequired,
useNewStepper: PropTypes.bool,
};
const mapStateToProps = state => {
const currentTab = selectCurrentTab(state);
return { currentTab };
};
const mapDispatchToProps = dispatch => ({
switchTab: tab => dispatch(WizardActions.switchTab(tab)),
});
export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
| JavaScript | 0 | @@ -508,86 +508,8 @@
';%0A%0A
-import %7B PAGE_CONTENT_PADDING_HORIZONTAL %7D from '../globalStyles/pageStyles';%0A
impo
@@ -530,28 +530,16 @@
D_COLOR,
- BLUE_WHITE,
SHADOW_
@@ -962,24 +962,52 @@
container%7D%3E%0A
+ %3CDataTablePageView%3E%0A
%3CView
@@ -1052,16 +1052,18 @@
+
%3CStepper
@@ -1073,16 +1073,18 @@
+
+
useNewSt
@@ -1115,16 +1115,18 @@
+
numberOf
@@ -1155,16 +1155,18 @@
+
+
currentS
@@ -1192,16 +1192,18 @@
+
onPress=
@@ -1210,24 +1210,26 @@
%7BswitchTab%7D%0A
+
ti
@@ -1254,51 +1254,30 @@
-/%3E%0A %3C/View%3E%0A %3CDataTablePage
+ /%3E%0A %3C/
View%3E%0A
+%0A
@@ -1517,35 +1517,23 @@
-backgroundColor: BLUE_WHITE
+marginBottom: 2
,%0A
@@ -1540,16 +1540,22 @@
border
+Bottom
Color: S
@@ -1576,78 +1576,28 @@
-marginBottom: 2,%0A marginHorizontal: PAGE_CONTENT_PADDING_HORIZONTAL
+borderBottomWidth: 1
,%0A
|
c73812126a8aeb5ac5c5f4327b443d2353393eb5 | fix escaping of chapter names | src/zbase/webui/widgets/zbase-documentation-menu/documentation_menu.js | src/zbase/webui/widgets/zbase-documentation-menu/documentation_menu.js | var DocumentationMenu = function() {
var createMenuItems = function(parent, items, index) {
var j = 0;
for(var i in items) {
var item = i;
var key = item.toLowerCase().replace(/ /, "_");
var section = document.createElement("z-menu-item");
section.classList.add("link", "doc_section");
parent.appendChild(section);
var link = document.createElement("a");
link.href = "/a/documentation/" + key;
var indexSpan = document.createElement("span");
var textSpan = document.createElement("span");
indexSpan.classList.add("index");
indexSpan.innerHTML = index.concat(++j).join(".");
textSpan.innerHTML = item;
link.appendChild(indexSpan);
link.appendChild(textSpan);
section.appendChild(link);
if(Object.keys(items[i]).length > 0) {
createMenuItems(section, items[i], index.concat(+j));
}
}
};
var render = function(elem) {
var tpl = $.getTemplate("widgets/zbase-documentation-menu", "zbase_documentation_menu_main_tpl");
elem.innerHTML = "";
elem.appendChild(tpl);
$.httpGet("/a/_/d/toc.json", function(res) {
var docStructure = JSON.parse(res.response);
var menuSection = $("z-menu-section", elem);
qax = docStructure;
createMenuItems(menuSection, docStructure.toc, []);
$.handleLinks(menuSection);
});
};
return {
render: render
};
};
| JavaScript | 0.000102 | @@ -198,10 +198,14 @@
ce(/
+%5B
/
+%5D/g
, %22_
|
2f1b2b0f0dcda99ff035f901048316469beb322d | Add semicolon | src/foam/nanos/auth/DeletedAware.js | src/foam/nanos/auth/DeletedAware.js | /**
* @license
* Copyright 2019 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.INTERFACE({
package: 'foam.nanos.auth',
name: 'DeletedAware',
methods: [
{
name: 'getDeleted',
returns: 'Boolean',
javaReturns: 'boolean',
swiftReturns: 'Bool'
},
{
name: 'setDeleted',
args: [
{
name: 'value',
javaType: 'boolean',
swiftType: 'Bool'
}
]
}
]
});
foam.CLASS({
package: 'foam.nanos.auth',
name: 'DeletedAwareDummy',
implements: [
'foam.nanos.auth.DeletedAware'
],
documentation: 'Dummy class for testing DeletedAware',
properties: [
{
class: 'Long',
name: 'id'
},
{
class: 'Boolean',
name: 'deleted'
}
]
}) | JavaScript | 0.999999 | @@ -804,20 +804,21 @@
eleted'%0A %7D%0A %5D%0A%7D)
+;
|
0cd3288749b0a88d4e765c648251a34917912835 | Remove duplicate property | src/foam/u2/view/ScrollTableView.js | src/foam/u2/view/ScrollTableView.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.u2.view',
name: 'ScrollTableView',
extends: 'foam.u2.Element',
requires: [
'foam.dao.FnSink',
'foam.mlang.sink.Count',
'foam.u2.view.TableView'
],
css: `
^ {
position: relative;
}
^scrollbar {
box-sizing: border-box;
}
^scrollbarContainer {
overflow: scroll;
}
^table {
/* The following line is required for Safari. */
position: -webkit-sticky;
position: sticky;
top: 0;
}
`,
constants: [
{
type: 'Integer',
name: 'TABLE_HEAD_HEIGHT',
value: 40
}
],
properties: [
{
class: 'foam.dao.DAOProperty',
name: 'data'
},
{
class: 'Int',
name: 'limit',
value: 18,
// TODO make this a funciton of the height.
},
{
class: 'Int',
name: 'skip',
},
{
class: 'foam.dao.DAOProperty',
name: 'scrolledDAO',
expression: function(data, limit, skip) {
return data && data.limit(limit).skip(skip);
},
},
'columns',
{
class: 'FObjectArray',
of: 'foam.core.Action',
name: 'contextMenuActions'
},
{
class: 'Int',
name: 'daoCount'
},
'selection',
{
class: 'Boolean',
name: 'editColumnsEnabled',
documentation: `
Set to true if users should be allowed to choose which columns to use.
`,
value: true
},
{
class: 'Int',
name: 'rowHeight',
documentation: 'The height of one row of the table in px.',
value: 48
},
{
class: 'Boolean',
name: 'fitInScreen',
documentation: `
If true, the table height will be dynamically set such that the table
will not overflow off of the bottom of the page.
`,
value: false
},
{
name: 'table_',
documentation: `
A reference to the table element we use in the fitInScreen calculations.
`
},
{
class: 'Int',
name: 'accumulator',
documentation: 'Used internally to mimic native scrolling speed.',
adapt: function(_, v) {
return v % this.rowHeight;
}
},
{
name: 'scrollbarContainer_',
documentation: `
A reference to the scrollbar's container element so we can update the
height after the view has loaded.
`
},
{
type: 'Int',
name: 'accumulator',
value: 0,
adapt: function(_, v) {
return v % this.rowHeight;
}
},
{
type: 'String',
name: 'scrollHeight',
expression: function(daoCount, limit, rowHeight) {
this.lastScrollTop_ = 0;
this.skip = 0;
return rowHeight * daoCount + this.TABLE_HEAD_HEIGHT + 'px';
}
},
{
type: 'Int',
name: 'lastScrollTop_',
value: 0
}
],
methods: [
function init() {
this.onDetach(this.data$proxy.listen(this.FnSink.create({ fn: this.onDAOUpdate })));
this.onDAOUpdate();
},
function initE() {
this.
addClass(this.myClass()).
start('div', undefined, this.scrollbarContainer_$).
addClass(this.myClass('scrollbarContainer')).
on('scroll', this.onScroll).
start(this.TableView, {
data$: this.scrolledDAO$,
columns: this.columns,
contextMenuActions: this.contextMenuActions,
selection$: this.selection$,
editColumnsEnabled: this.editColumnsEnabled
}, this.table_$).
addClass(this.myClass('table')).
end().
start().
show(this.daoCount$.map((count) => count >= this.limit)).
addClass(this.myClass('scrollbar')).
style({ height: this.scrollHeight$ }).
end().
end();
if ( this.fitInScreen ) {
this.onload.sub(this.updateTableHeight);
window.addEventListener('resize', this.updateTableHeight);
this.onDetach(() => {
window.removeEventListener('resize', this.updateTableHeight);
});
}
}
],
listeners: [
{
name: 'onScroll',
code: function(e) {
var deltaY = e.target.scrollTop - this.lastScrollTop_;
var negative = deltaY < 0;
var rows = Math.floor(Math.abs(this.accumulator + deltaY) / this.rowHeight);
this.accumulator += deltaY;
var oldSkip = this.skip;
this.skip = Math.max(0, this.skip + (negative ? -rows : rows));
if ( this.skip > this.daoCount - this.limit ) this.skip = oldSkip;
this.lastScrollTop_ = e.target.scrollTop;
}
},
{
// TODO: Avoid onDAOUpdate approaches.
name: 'onDAOUpdate',
isFramed: true,
code: function() {
var self = this;
this.data$proxy.select(this.Count.create()).then(function(s) {
self.daoCount = s.value;
});
}
},
{
name: 'updateTableHeight',
code: function() {
// Find the distance from the top of the table to the top of the screen.
var distanceFromTop = this.table_.el().getBoundingClientRect().y;
// Calculate the remaining space we have to make use of.
var remainingSpace = window.innerHeight - distanceFromTop;
// Set the limit such that we make maximum use of the space without
// overflowing.
this.limit = Math.max(1, Math.floor((remainingSpace - this.TABLE_HEAD_HEIGHT) / this.rowHeight));
this.scrollbarContainer_.el().style.height = (this.limit * this.rowHeight) + this.TABLE_HEAD_HEIGHT + 'px';
}
}
]
});
| JavaScript | 0.000001 | @@ -2524,156 +2524,8 @@
%7B%0A
- type: 'Int',%0A name: 'accumulator',%0A value: 0,%0A adapt: function(_, v) %7B%0A return v %25 this.rowHeight;%0A %7D%0A %7D,%0A %7B%0A
|
c041f3ef9a12c38e9180d53274c45ac9376f7a6f | use ember-cli-moment-shim v2 | blueprints/ember-datetimepicker/index.js | blueprints/ember-datetimepicker/index.js | module.exports = {
normalizeEntityName: function() {},
afterInstall: function(options) {
return this.addBowerPackageToProject('datetimepicker', '2.5.4').then(function() {
return this.addAddonToProject({ name: 'ember-cli-moment-shim', target: '^1.0.0' });
}.bind(this));
}
};
| JavaScript | 0.000001 | @@ -256,9 +256,9 @@
: '%5E
-1
+2
.0.0
|
4acd4a4bacba30532d4766ed23eb69a877657fb1 | Test version equality. | script/ci/download.js | script/ci/download.js | const path = require("path")
const fetch = require("node-fetch")
const gunzip = require("gunzip-maybe")
const tar = require("tar-fs")
async function download() {
const {repository: {url}, version} = require(path.resolve("./package.json"))
const [, user, repo] = url.match(/\/([a-z0-9_-]+)\/([a-z0-9_-]+)\.git$/i)
const res = await fetch(`https://api.github.com/repos/${user}/${repo}/releases/tags/${version}`)
if (!res.ok) {
throw new Error(`Github release ${version} not found (${res.status})`)
}
const {assets} = await res.json()
await Promise.all(assets.map(async ({browser_download_url: url}) => {
console.log(`Downloading prebuilds from ${url}`)
const res = await fetch(url)
return new Promise((resolve, reject) => {
res.body.pipe(gunzip()).pipe(tar.extract(".")).on("error", reject).on("finish", resolve)
})
}))
}
download().catch(err => {
console.error(err)
process.exit(1)
})
| JavaScript | 0 | @@ -235,16 +235,189 @@
json%22))%0A
+%0A if (process.env.TRAVIS_TAG && process.env.TRAVIS_TAG != version) %7B%0A throw new Error(%60Version mismatch (TRAVIS_TAG=$%7Bprocess.env.TRAVIS_TAG%7D, version=$%7Bversion%7D%60)%0A %7D%0A%0A
const
|
c04a3b26c6b1859bf77df6a84936c95b457bf65c | Add support for mixed "plain color string" and "color map" background defintitions | src/generators/background-colors.js | src/generators/background-colors.js | const postcss = require('postcss')
const _ = require('lodash')
function findColor(colors, color) {
const colorsNormalized = _.mapKeys(colors, (value, key) => {
return _.camelCase(key)
})
return _.get(colorsNormalized, _.camelCase(color), color)
}
module.exports = function ({ colors, backgroundColors }) {
if (_.isArray(backgroundColors)) {
backgroundColors = _(backgroundColors).map(color => [color, color]).fromPairs()
}
return _(backgroundColors).toPairs().map(([className, colorName]) => {
const kebabClass = _.kebabCase(className)
return postcss.rule({
selector: `.bg-${kebabClass}`
}).append({
prop: 'background-color',
value: findColor(colors, colorName)
})
}).value()
}
| JavaScript | 0.999996 | @@ -392,17 +392,21 @@
Colors).
-m
+flatM
ap(color
@@ -413,22 +413,116 @@
=%3E
-%5Bcolor, color%5D
+%7B%0A if (_.isString(color)) %7B%0A return %5B%5Bcolor, color%5D%5D%0A %7D%0A return _.toPairs(color)%0A %7D
).fr
|
13c063b6df04d428f5c0162e3648e075cfb0da81 | add larger deletion catch net | scripts/botCleaner.js | scripts/botCleaner.js | const pact = require('../pact.js');
pact.db.createReadStream({start: 'poll!',
end: 'poll!~'
})
.on('data', (data) => {
const title = JSON.parse(data.value).question;
if (title.match('href=')) {
pact.db.del(data.key, (err) => {
if (err) {
console.log(err);
}
});
} else {
console.log(title);
}
})
.on('end', () => {
console.log('done');
});
| JavaScript | 0.000016 | @@ -246,16 +246,42 @@
'href=')
+ %7C%7C title.match('http://')
) %7B%0A
|
e601d2087a1b97252ae59b8f3d5d55a0eb4a4204 | add title attr | packages/tocco-ui/src/Button/Button.js | packages/tocco-ui/src/Button/Button.js | import PropTypes from 'prop-types'
import React from 'react'
import Icon from '../Icon'
import LoadingSpinner from '../LoadingSpinner'
import StyledButton from './StyledButton'
import {design} from '../utilStyles'
/**
* Use <Button> to trigger any actions. Choose look and ink according Material Design.
*/
const Button = React.forwardRef((props, ref) => {
return <StyledButton
ref={ref}
{...props.aria}
{...props}
ink={props.ink || design.ink.BASE}
data-cy={props['data-cy']}
>
{props.icon && !props.pending && <Icon
icon={props.icon}
/>}
{props.pending && <LoadingSpinner
ink={props.ink || design.ink.BASE}
look={props.look}
position={props.iconPosition}
size="1em"/>}
{props.label ? <span>{props.label}</span> : props.children ? props.children : '\u200B' }
</StyledButton>
})
Button.defaultProps = {
iconPosition: design.position.PREPEND,
look: design.look.FLAT,
type: 'button'
}
Button.propTypes = {
/**
* A flat object of ARIA keys and values.
*/
'aria': PropTypes.object,
/**
* Instead of using label prop it is possible to pass a child
* (e.g. <Button><FormattedMessage id="client.message"/></Button>). This is not useful for
* styled tags since buttons design is controlled by props ink and look and immutable.
*/
'children': PropTypes.node,
/**
* If true, button occupies less space. It should only used for crowded areas like tables and only if necessary.
*/
'dense': PropTypes.bool,
/**
* If true, the button can not be triggered. Disable a button rather than hide it temporarily.
*/
'disabled': PropTypes.bool,
/**
* Display an icon alongside button label. It is possible to omit label text if an icon is chosen.
* See Icon component for more information.
*/
'icon': PropTypes.string,
/**
* Prepend icon or append icon to label. Default value is 'prepend'.
* Possible values: append|prepend
*/
'iconPosition': PropTypes.oneOf([design.position.APPEND, design.position.PREPEND]),
/**
* Specify color palette. Default value is 'base'.
*/
'ink': design.inkPropTypes,
/**
* Describe button action concise. Default is ''.
*/
'label': PropTypes.node,
/**
* Look of button. Default value is 'flat'.
*/
'look': PropTypes.oneOf([
design.look.BALL,
design.look.FLAT,
design.look.RAISED
]),
/**
* Function that will be triggered on click event.
*/
'onClick': PropTypes.func,
/**
* If true, an animated spinner icon is prepended.
*/
'pending': PropTypes.bool,
/**
* Describe button action in detail to instruct users. It is shown as popover on mouse over.
*/
'title': PropTypes.string,
/**
* HTML Button type. Default is 'button'.
*/
'type': PropTypes.oneOf(['button', 'submit', 'reset']),
/**
* Tabindex indicates if the button can be focused and if/where it participates
* in sequential keyboard navigation.
*/
'tabIndex': PropTypes.number,
/**
* cypress selector string
*/
'data-cy': PropTypes.string
}
export default Button
| JavaScript | 0 | @@ -354,16 +354,96 @@
f) =%3E %7B%0A
+ const %7Baria, ink, label, icon, pending, look, iconPosition, children%7D = props%0A
return
@@ -479,22 +479,16 @@
%7B...
-props.
aria%7D%0A
@@ -501,38 +501,32 @@
props%7D%0A ink=%7B
-props.
ink %7C%7C design.in
@@ -564,16 +564,34 @@
a-cy'%5D%7D%0A
+ title=%7Blabel%7D%0A
%3E%0A
@@ -591,22 +591,16 @@
%3E%0A %7B
-props.
icon &&
@@ -600,22 +600,16 @@
con && !
-props.
pending
@@ -625,30 +625,24 @@
icon=%7B
-props.
icon%7D%0A /%3E
@@ -648,22 +648,16 @@
%3E%7D%0A %7B
-props.
pending
@@ -686,22 +686,16 @@
ink=%7B
-props.
ink %7C%7C d
@@ -722,22 +722,16 @@
look=%7B
-props.
look%7D%0A
@@ -744,22 +744,16 @@
sition=%7B
-props.
iconPosi
@@ -783,22 +783,16 @@
%3E%7D%0A %7B
-props.
label ?
@@ -798,22 +798,16 @@
%3Cspan%3E%7B
-props.
label%7D%3C/
@@ -814,22 +814,16 @@
span%3E :
-props.
children
@@ -827,26 +827,10 @@
ren
-? props.children :
+%7C%7C
'%5Cu
|
9c5daf44f79f82458b2917147a18ecf7af74765b | Fix ViewMap | Kwc/Directories/List/ViewMap/Component.js | Kwc/Directories/List/ViewMap/Component.js | Ext.namespace('Kwc.Directories.List.ViewMap');
Kwc.Directories.List.ViewMap.renderedMaps = [];
Kwc.Directories.List.ViewMap.renderMap = function(map) {
if (Kwc.Directories.List.ViewMap.renderedMaps.indexOf(map) != -1) return;
Kwc.Directories.List.ViewMap.renderedMaps.push(map);
var mapContainer = new Ext.Element(map);
var cfg = mapContainer.down(".options", true);
if (!cfg) return;
cfg = Ext.decode(cfg.value);
// markers aus partials raus sammeln
if (!cfg.markers) cfg.markers = [];
if (!cfg.lightMarkers) cfg.lightMarkers = [];
var markerEls = mapContainer.query(".markerData");
markerEls.each(function(mel) {
var mdata = Ext.decode(mel.value);
if (typeof cfg.markers == 'object') cfg.markers.push(mdata);
cfg.lightMarkers.push(mdata);
});
// mittelpunkt und zoom für die marker finden
if (cfg.lightMarkers.length) {
var lowestLat = null;
var highestLat = null;
var lowestLng = null;
var highestLng = null;
cfg.lightMarkers.each(function(lm) {
if (lowestLng == null || lowestLng > parseFloat(lm.longitude)) {
lowestLng = parseFloat(lm.longitude);
}
if (highestLng == null || highestLng < parseFloat(lm.longitude)) {
highestLng = parseFloat(lm.longitude);
}
if (lowestLat == null || lowestLat > parseFloat(lm.latitude)) {
lowestLat = parseFloat(lm.latitude);
}
if (highestLat == null || highestLat < parseFloat(lm.latitude)) {
highestLat = parseFloat(lm.latitude);
}
});
}
if (lowestLng && highestLng && lowestLat && highestLat) {
if (!cfg.zoom) {
cfg.zoom = [ highestLat, highestLng, lowestLat, lowestLng ];
}
if (!cfg.longitude) {
cfg.longitude = (lowestLng + highestLng) / 2;
}
if (!cfg.latitude) {
cfg.latitude = (lowestLat + highestLat) / 2;
}
}
cfg.mapContainer = mapContainer;
var cls = eval(cfg.mapClass) || Kwf.GoogleMap.Map;
var myMap = new cls(cfg);
Kwf.GoogleMap.load(function() {
this.show();
}, myMap);
};
Kwf.onContentReady(function() {
var maps = Ext.DomQuery.select('div.kwcDirectoriesListViewMap');
Ext.each(maps, function(map) {
var up = Ext.get(map).up('div.kwfSwitchDisplay');
if (up) {
(function(up, map) {
Ext.get(up).switchDisplayObject.on('opened', function() {
Kwc.Directories.List.ViewMap.renderMap(map);
});
}).defer(1, this, [up, map]);
} else {
Kwc.Directories.List.ViewMap.renderMap(map);
}
});
});
| JavaScript | 0.000001 | @@ -2510,16 +2510,20 @@
get(up).
+dom.
switchDi
|
a97713de7f316a097662a15b699868141b6d643d | check if Ext.grid.CheckboxSelectionModel exists by adding/deleting subscribers to/from queue | Kwc/Newsletter/Detail/RecipientsAction.js | Kwc/Newsletter/Detail/RecipientsAction.js | Ext.ns('Kwc.Newsletter.Detail');
Kwc.Newsletter.Detail.RecipientsAction = Ext.extend(Ext.Action, {
constructor: function(config){
config = Ext.apply({
icon : '/assets/silkicons/database_add.png',
cls : 'x-btn-text-icon',
text : trlKwf('Add Recipients'),
tooltip : trlKwf('Adds the currently shown recipients to the newsletter'),
scope : this,
handler : function(a, b, c) {
if (this.getGrid().getSelectionModel() instanceof Ext.grid.CheckboxSelectionModel) {
var selectedRows = this.getGrid().getSelectionModel().getSelections();
var ids = [];
selectedRows.each(function(selectedRow) { ids.push(selectedRow.id); }, this);
var params = this.getStore().baseParams;
params.ids = ids.join(',');
} else {
if (this.getStore().lastOptions) {
var params = this.getStore().lastOptions.params;
} else {
var params = this.getStore().baseParams;
}
}
Ext.Ajax.request({
url : this.controllerUrl + '/json-save-recipients',
params: params,
success: function(response, options, r) {
var msgText = trlKwf('{0} recipients added, total {1} recipients.', [r.added, r.after]);
if (r.rtrExcluded.length) {
msgText += '<br /><br />';
msgText += trlKwf('The following E-Mail addresses were excluded due to the RTR-ECG-Check (see {0})', ['<a href="http://www.rtr.at/ecg" target="_blank">www.rtr.at/ecg</a>']);
msgText += ':<div class="recipientsStatusRtr">'+r.rtrExcluded.join('<br />')+'</div>';
}
Ext.MessageBox.alert(trlKwf('Status'), msgText, function() {
this.findParentByType('kwc.newsletter.recipients').fireEvent('queueChanged');
}, this);
},
progress: true,
timeout: 600000,
scope: this
});
}}, config);
Kwc.Newsletter.Detail.RecipientsAction.superclass.constructor.call(this, config);
}
});
Kwc.Newsletter.Detail.RemoveRecipientsAction = Ext.extend(Ext.Action, {
constructor: function(config){
config = Ext.apply({
icon : '/assets/silkicons/database_delete.png',
cls : 'x-btn-text-icon',
text : trlKwf('Remove Recipients'),
tooltip : trlKwf('Removes the currently shown recipients to the newsletter'),
scope : this,
handler : function(a, b, c) {
if (this.getGrid().getSelectionModel() instanceof Ext.grid.CheckboxSelectionModel) {
var selectedRows = this.getGrid().getSelectionModel().getSelections();
var ids = [];
selectedRows.each(function(selectedRow) { ids.push(selectedRow.id); }, this);
var params = this.getStore().baseParams;
params.ids = ids.join(',');
} else {
if (this.getStore().lastOptions) {
var params = this.getStore().lastOptions.params;
} else {
var params = this.getStore().baseParams;
}
}
Ext.Ajax.request({
url : this.controllerUrl + '/json-remove-recipients',
params: params,
success: function(response, options, r) {
var msgText = trlKwf('{0} recipients removed, total {1} recipients.', [r.removed, r.after]);
Ext.MessageBox.alert(trlKwf('Status'), msgText, function() {
this.findParentByType('kwc.newsletter.recipients').fireEvent('queueChanged');
}, this);
},
progress: true,
timeout: 600000,
scope: this
});
}}, config);
Kwc.Newsletter.Detail.RecipientsAction.superclass.constructor.call(this, config);
}
});
| JavaScript | 0 | @@ -447,32 +447,67 @@
if (
+Ext.grid.CheckboxSelectionModel &&
this.getGrid().g
@@ -2768,32 +2768,67 @@
if (
+Ext.grid.CheckboxSelectionModel &&
this.getGrid().g
|
62bffcab761d3ca395e821e1cd259dab9ed60bc5 | Resolve style errors on data block | blocks/data/index.js | blocks/data/index.js | var Data = require('../../lib/data');
module.exports = {
className: 'data',
template: require('./index.html'),
data: {
name: 'Data',
icon: '/images/blocks_text.png',
attributes: {
label: {
label: 'Header Text',
type: 'string',
value: '',
placeholder: 'Responses',
skipAutoRender: true
},
color: {
label: 'Header and Title Text Color',
type: 'color',
value: '#36494A',
skipAutoRender: true
}
},
currentDataSets: [],
initialDataLoaded: false,
isInteractive: false,
sortOldest: false
},
ready: function (){
var self = this;
if (!self.$data || !self.$data.currentDataSets || self.$data.currentDataSets.length === 0) self.$data.initialDataLoaded = false;
// Fetch collected Data
self.currentDataSets = [];
if(!self.isEditing) {
var data = new Data(self.$parent.$parent.$data.app.id);
data.getAllDataSets(function(currentDataSets) {
self.$data.initialDataLoaded = true;
self.currentDataSets = currentDataSets;
});
}
else {
self.$data.initialDataLoaded = true;
}
}
};
| JavaScript | 0 | @@ -773,18 +773,19 @@
ction ()
+
%7B%0A
-
@@ -814,16 +814,29 @@
if (
+%0A
!self.$d
@@ -841,16 +841,28 @@
$data %7C%7C
+%0A
!self.$
@@ -884,16 +884,28 @@
aSets %7C%7C
+%0A
self.$d
@@ -936,17 +936,40 @@
th === 0
-)
+%0A ) %7B%0A
self.$d
@@ -998,16 +998,26 @@
= false;
+%0A %7D
%0A%0A
@@ -1087,16 +1087,17 @@
if
+
(!self.i
@@ -1217,16 +1217,17 @@
function
+
(current
@@ -1363,16 +1363,16 @@
%7D);%0A
+
@@ -1372,24 +1372,16 @@
%7D
-%0A
else %7B%0A
|
c1a0eee5da12373ecfb1c91b9ea44660c565c0a2 | Remove extra semicolon from new tab page js. | tab_page/js/main.js | tab_page/js/main.js | var sites;
document.addEventListener('DOMContentLoaded', function() {
document.removeEventListener('DOMContentLoaded', arguments.callee, false);
init();
}, false );
chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
console.log('Message received: ' + request.message);
if (request.message == "refresh") {
location.reload();
}
});
function init() {
resetStorageToDefault();
var sitesElement = document.getElementById('sites');
getAllSites(function(items) {
sites = items;
document.addEventListener("DOMNodeInserted", layout, false);
if (sites == undefined || sites == null || sites.length == 0) {
showNoSitesMessage();
return;
}
var fragment = document.createDocumentFragment();
for (var i = 0; i < sites.length; i++) {
var site = sites[i];
var tile = createTile(site.abbreviation, site.url);
var color;
if (site.customColor) {
color = site.customColor;
} else {
color = site.color;
}
tile.style.background = 'rgba(' + color.red +', ' + color.green + ', ' + color.blue + ', ' + 1 +')';
tile.onclick = onTileClick;
fragment.appendChild(tile);
}
sitesElement.appendChild(fragment);
});
window.onresize = function() {
layout();
};
}
function layout() {
if (sites == undefined || sites == null) {
return;
}
document.removeEventListener("DOMNodeInserted", layout);
var sitesElement = document.getElementById("sites");
sitesElement.style.opacity = "1.0";
const MARGIN = 8;
const ROW_HEIGHT = 220 + MARGIN;
const COL_WIDTH = 220 + MARGIN;
const MAX_HEIGHT = window.innerHeight - MARGIN;
const MAX_WIDTH = window.innerWidth - MARGIN;
var rows = Math.max(Math.ceil(Math.sqrt(sites.length * MAX_HEIGHT / MAX_WIDTH)), 1);
var cols = Math.ceil(sites.length / rows);
if ((rows - 1) * cols >= sites.length && sites.length < rows * cols) {
rows--;
}
var shouldWidth = cols * COL_WIDTH;
sitesElement.style.width = shouldWidth + "px";
var scale = MAX_WIDTH / (shouldWidth + 20);
if (ROW_HEIGHT * rows * scale > MAX_HEIGHT) {
scale = MAX_HEIGHT / (ROW_HEIGHT * rows);
}
sitesElement.style.webkitTransform = "scale(" + scale + ", " + scale + ")";
sitesElement.style.marginLeft = -shouldWidth / 2 + "px";
sitesElement.style.minHeight = 228 * rows + "px";
sitesElement.style.marginTop = (-228 * rows) / 2 + "px";
}
function createTile(abbreviation, url) {
var site = document.createElement('a');
site.setAttribute("class", "tile");
site.setAttribute("href", url);
site.innerHTML = abbreviation + '<span class="url">' + getHostname(url) + '</span>';
return site;
}
function isMac() {
if (navigator.appVersion.toLowerCase().indexOf("mac") != -1)
return true;
return false;
}
function onTileClick(e) {
e.preventDefault();
var target = e.target;
var sitesElement = document.getElementById("sites");
var url = target.href;
if (url == null || url == "") {
return false;
}
var newTab = false;
var newWindow = false;
var activeWhenOpened = false;
if (isMac()) {
if (e.metaKey || e.button == 1) {
newTab = true;
if (e.shiftKey) {
activeWhenOpened = true;
}
} else if (e.shiftKey) {
newWindow = true;
activeWhenOpened = true;
}
} else {
if (e.ctrlKey || e.button == 1) {
newTab = true;
if (e.shiftKey) {
activeWhenOpened = true;
}
} else if (e.shiftKey) {
newWindow = true;
activeWhenOpened = true;
}
}
if (newTab) {
chrome.tabs.create({ 'url': url, 'active': activeWhenOpened });
} else if (newWindow) {
chrome.windows.create({ 'url': url, 'focused': activeWhenOpened, 'type': 'normal' });
} else {
target.setAttribute("class", "tile animate");
var sitesTransform = sitesElement.style.webkitTransform;
var floatRegex = /scale\(([0-9]*\.?[0-9]*), ?([0-9]*\.?[0-9]*)\)/;
var sitesScale = floatRegex.exec(sitesTransform)[1];
const MARGIN = 8;
const ROW_HEIGHT = 220;
const COL_WIDTH = 220;
const ROW_OUTER_HEIGHT = 228;
const COL_OUTER_WIDTH = 228;
const CHANGE_LOCATION_DELAY = 300;
const MAX_HEIGHT = window.innerHeight - MARGIN;
const MAX_WIDTH = window.innerWidth - MARGIN;
var rows = Math.max(Math.ceil(Math.sqrt(sites.length * MAX_HEIGHT / MAX_WIDTH)), 1);
var cols = Math.ceil(sites.length / rows);
if ((rows - 1) * cols >= sites.length && sites.length < rows * cols) {
rows--;
}
var scaleX = window.innerWidth / sitesScale / COL_WIDTH;
var scaleY = window.innerHeight / sitesScale / ROW_HEIGHT;
var sitesMidX = parseInt(sitesElement.style.width) / 2;
var sitesMidY = ROW_OUTER_HEIGHT * rows / 2;
var centerX = target.offsetLeft + COL_WIDTH / 2;
var centerY = target.offsetTop + ROW_HEIGHT / 2;
var translateX = sitesMidX - centerX;
var translateY = sitesMidY - centerY;
target.style.webkitTransform = "translate(" + translateX + "px, " + translateY + "px) scale(" + scaleX + ", " + scaleY + ")";
target.style.background = "white";
setTimeout(function() {
window.location = url;
}, CHANGE_LOCATION_DELAY);
}
}
function showNoSitesMessage() {
var siteElement = document.getElementById('sites');
var tile = document.createElement('div');
tile.setAttribute("class", "message");
tile.innerHTML = "<p>" + chrome.i18n.getMessage("no_tiles_added")
+ "<span class='help'>" + chrome.i18n.getMessage("tab_page_no_tiles_added_help", ["<img src='../../icons/icon-bitty-gray.png'>"]) + "</span>";
+ "</p>";
document.getElementsByTagName('body')[0].appendChild(tile);
}
| JavaScript | 0.000001 | @@ -5078,27 +5078,30 @@
es');%0A%0A%09var
-til
+messag
e = document
@@ -5124,19 +5124,22 @@
div');%0A%09
-til
+messag
e.setAtt
@@ -5167,19 +5167,22 @@
age%22);%0A%09
-til
+messag
e.innerH
@@ -5379,17 +5379,16 @@
%3C/span%3E%22
-;
%0A%09 + %22%3C/
@@ -5443,21 +5443,24 @@
appendChild(
-til
+messag
e);%0A%7D%0A
|
d9596e2cc498da2d54650e2e9651dab2caf0ec23 | remove describe.only from item model test | db/models/item.test.js | db/models/item.test.js | 'use strict'
const db = require('APP/db'),
{ Item } = db,
{ expect } = require('chai'),
Promise = require('bluebird')
describe.only('The `Item` model', () => {
/**
* First we clear the database and recreate the tables before beginning a run
*/
before('Await database sync', () => db.didSync)
/**
* Next, we create an (un-saved!) item instance before every spec
*/
let item
beforeEach(() => {
item = Item.build({
price: 1000.01,
quantity: 3
})
})
/**
* Also, we empty the tables after each spec
*/
afterEach(() => {
return Promise.all([
Item.truncate({ cascade: true })
])
})
describe('attributes definition', function() {
it('included `price` and `quantity` fields', function() {
console.log("item", item.price);
return item.save()
.then(function(savedItem) {
expect(savedItem.price).to.equal('1000.01')
expect(savedItem.quantity).to.equal(3)
})
})
})
describe('Validations', () => {
it('requires `price`', () => {
item.price = null
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('notNull Violation')
})
})
it('errors if `price` is an integer', () => {
item.price = 20
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `price` is not a string of letters', () => {
item.price = 'test'
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `price` is less than zero', () => {
item.price = -20
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `price` has too many decimals', () => {
item.price = 20.234
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `price` has too few decimals', () => {
item.price = 20.2
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('requires `quantity` ', () => {
item.quantity = null
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('notNull Violation')
})
})
it('errors if `quantity` is less than zero', () => {
item.quantity = -2
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `quantity` is a decimal', () => {
item.quantity = 2.2
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
it('errors if `quantity` is a string', () => {
item.quantity = 'test'
return item.validate()
.then(function(result) {
expect(result).to.be.an.instanceOf(Error)
expect(result.message).to.contain('Validation error')
})
})
})
})
| JavaScript | 0.000005 | @@ -131,13 +131,8 @@
ribe
-.only
('Th
|
ddd91e4e0cfa15302fc636cfc7b52990f92a3408 | Update actividadLaEleccionDelMono.js | app/actividades/actividadLaEleccionDelMono.js | app/actividades/actividadLaEleccionDelMono.js | import bloques from 'pilas-engine-bloques/actividades/bloques';
var {Accion, Sensor, Si, Sino, Procedimiento} = bloques;
var Avanzar = Accion.extend({
init() {
this._super();
this.set('id', 'Avanzar');
},
block_init(block) {
this._super(block);
block.appendDummyInput()
.appendField('Avanzar')
.appendField(this.obtener_icono('derecha.png'));
},
nombre_comportamiento() {
return 'MoverACasillaDerecha';
},
argumentos() {
return '{}';
}
});
var ComerManzana = Accion.extend({
init() {
this._super();
this.set('id', 'ComerManzana');
},
block_init(block) {
this._super(block);
block.appendDummyInput()
.appendField('Comer manzana ')
.appendField(this.obtener_icono('../libs/data/iconos.manzana.png'));
},
nombre_comportamiento() {
return 'RecogerPorEtiqueta';
},
argumentos() {
return '{\'etiqueta\' : \'ManzanaAnimada\', nombreAnimacion: "comerManzana"}';
}
});
var ComerBanana = Accion.extend({
init() {
this._super();
this.set('id', 'ComerBanana');
},
block_init(block) {
this._super(block);
block.appendDummyInput()
.appendField('Comer banana ')
.appendField(this.obtener_icono('../libs/data/iconos.banana.png')); //TODO: Hardcodeo feo de dir de icono
},
nombre_comportamiento() {
return 'RecogerPorEtiqueta';
},
argumentos() {
return '{\'etiqueta\' : \'BananaAnimada\', nombreAnimacion: "comerBanana"}';
}
});
var TocandoManzana = Sensor.extend({
init() {
this._super();
this.set('id', 'tocandoManzana');
},
block_init(block) {
this._super(block);
block.appendDummyInput()
.appendField('¿Tocando manzana')
.appendField(this.obtener_icono('../libs/data/iconos.manzana.png'))
.appendField('?');
},
nombre_sensor() {
return 'tocando(\'ManzanaAnimada\')';
}
});
var TocandoBanana = Sensor.extend({
init() {
this._super();
this.set('id', 'tocandoBanana');
},
block_init(block) {
this._super(block);
block.appendDummyInput()
.appendField('¿Tocando banana')
.appendField(this.obtener_icono('../libs/data/iconos.banana.png'))
.appendField('?');
},
nombre_sensor() {
return 'tocando(\'BananaAnimada\')';
}
});
var actividadLaEleccionDelMono = {
nombre: 'La elección del mono',
id: 'LaEleccionDelMono',
enunciado: '¿Podés ayudar nuevamente a nuestro mono? Esta vez siempre tiene '+
'una fruta para comer. ¡Pero no siempre es la misma! \n'+
'Ejecutá el programa varias veces para asegurarte que siempre funciona. \n' +
'Pista: Ésta vez no alcanza con el bloque "Si".',
consignaInicial: 'Si el escenario del protagonista varía, nuestro procedimiento debe utilizar alternativas condicionales que ajusten las acciones a estos cambios.',
// la escena proviene de ejerciciosPilas
escena: LaEleccionDelMono, // jshint ignore:line
puedeComentar: false,
puedeDesactivar: false,
puedeDuplicar: false,
subtareas: [Procedimiento],
// TODO: aca irian atributos iniciales que se desean para un personaje
variables: [],
control: [Si,Sino],
expresiones: [],
acciones: [ComerManzana,ComerBanana,Avanzar],
sensores: [TocandoManzana,TocandoBanana],
};
export default actividadLaEleccionDelMono;
| JavaScript | 0 | @@ -2658,9 +2658,9 @@
ta:
-%C3%89
+%C3%A9
sta
|
a8c9119f0c8b77968edcc8af5ee105b0025ecf1b | Switch to needsUpdate pattern | app/assets/javascripts/stores/alerts_store.js | app/assets/javascripts/stores/alerts_store.js | import McFly from 'mcfly';
const Flux = new McFly();
let _needHelpAlertSubmitting = false;
let _needHelpAlertCreated = false;
const needHelpAlertSubmitted = function () {
_needHelpAlertSubmitting = true;
return AlertsStore.emitChange();
};
const needHelpAlertCreated = function () {
_needHelpAlertSubmitting = false;
_needHelpAlertCreated = true;
return AlertsStore.emitChange();
};
const resetNeedHelpAlert = function () {
_needHelpAlertSubmitting = false;
_needHelpAlertCreated = false;
return AlertsStore.emitChange();
};
const storeMethods = {
getNeedHelpAlertSubmitting() {
return _needHelpAlertSubmitting;
},
getNeedHelpAlertSubmitted() {
return _needHelpAlertCreated;
}
};
const AlertsStore = Flux.createStore(storeMethods, (payload) => {
switch (payload.actionType) {
case 'NEED_HELP_ALERT_SUBMITTED':
return needHelpAlertSubmitted();
case 'NEED_HELP_ALERT_CREATED':
return needHelpAlertCreated();
case 'RESET_NEED_HELP_ALERT':
return resetNeedHelpAlert();
default:
// no default
}
});
export default AlertsStore;
| JavaScript | 0 | @@ -206,43 +206,8 @@
ue;%0A
- return AlertsStore.emitChange();%0A
%7D;%0A%0A
@@ -321,43 +321,8 @@
ue;%0A
- return AlertsStore.emitChange();%0A
%7D;%0A%0A
@@ -435,43 +435,8 @@
se;%0A
- return AlertsStore.emitChange();%0A
%7D;%0A%0A
@@ -673,16 +673,44 @@
d) =%3E %7B%0A
+ let needsUpdate = false;%0A%0A
switch
@@ -769,39 +769,32 @@
BMITTED':%0A
-return
needHelpAlertSub
@@ -799,24 +799,63 @@
ubmitted();%0A
+ needsUpdate = true;%0A break;%0A
case 'NE
@@ -884,23 +884,16 @@
:%0A
-return
needHelp
@@ -904,24 +904,63 @@
tCreated();%0A
+ needsUpdate = true;%0A break;%0A
case 'RE
@@ -987,23 +987,16 @@
:%0A
-return
resetNee
@@ -1005,24 +1005,63 @@
elpAlert();%0A
+ needsUpdate = true;%0A break;%0A
default:
@@ -1070,17 +1070,17 @@
//
-n
+N
o defaul
@@ -1084,16 +1084,72 @@
ault%0A %7D
+%0A%0A if (needsUpdate) %7B%0A AlertsStore.emitChange();%0A %7D
%0A%7D);%0A%0Aex
|
cb521db27d6ef7e69812f966c9d037a8989ec423 | fix race condition | src/javascript/app/japan/cashier.js | src/javascript/app/japan/cashier.js | const BinaryPjax = require('../base/binary_pjax');
const Client = require('../base/client');
const BinarySocket = require('../base/socket');
const localize = require('../../_common/localize').localize;
const State = require('../../_common/storage').State;
const CashierJP = (() => {
const onLoad = (action) => {
if (Client.isJPClient() && Client.get('residence') !== 'jp') BinaryPjax.loadPreviousUrl();
if (action === 'deposit') {
return;
}
const $container = $('#japan_cashier_container');
BinarySocket.send({ cashier_password: 1 }).then((response) => {
if (!response.error && response.cashier_password === 1) {
$container.find('#cashier_locked_message').setVisibility(1);
} else {
BinarySocket.send({ get_account_status: 1 }).then((response_status) => {
if (!response_status.error && /cashier_locked/.test(response_status.get_account_status.status)) {
$container.find('#cashier_locked_message').text(localize('Your cashier is locked.')).setVisibility(1); // Locked from BO
} else {
const limit = State.getResponse('get_limits.remainder');
if (typeof limit !== 'undefined' && limit < 1) {
$container.find('#cashier_locked_message').text(localize('You have reached the withdrawal limit.')).setVisibility(1);
} else {
$container.find('#cashier_unlocked_message').setVisibility(1);
BinarySocket.wait('get_settings').then(() => {
$('#id123-control22598118').val(Client.get('loginid'));
$('#id123-control22598060').val(Client.get('email'));
$('#japan_cashier_container button').on('click', (e) => {
const result = errorHandler();
if (!result) e.preventDefault();
});
});
}
}
});
}
});
};
const errorHandler = () => {
$('.error-msg').remove();
const $id = $('#id123-control22598145');
const withdrawal_amount = $id.val();
const showError = (message) => {
$id.parent().append($('<p/>', { class: 'error-msg', text: localize(message) }));
};
if (isNaN(withdrawal_amount) || +withdrawal_amount < 1) {
showError(localize('Should be more than [_1]', ['¥1']));
return false;
} else if (parseInt(Client.get('balance')) < withdrawal_amount) {
showError('Insufficient balance.');
return false;
}
return true;
};
return {
errorHandler,
Deposit : { onLoad: () => { onLoad('deposit'); } },
Withdraw: { onLoad: () => { onLoad('withdraw'); } },
};
})();
module.exports = CashierJP;
| JavaScript | 0.000001 | @@ -1538,150 +1538,67 @@
-$
con
-tainer.find('#cashier_unlocked_message').setVisibility(1);%0A BinarySocket.wait('get_settings').then(() =%3E %7B%0A
+st response_authorize = State.getResponse('authorize');%0A
@@ -1657,36 +1657,48 @@
val(
-Client.get('loginid'));%0A
+response_authorize.loginid %7C%7C 'undef');%0A
@@ -1757,34 +1757,46 @@
val(
-Client.get('email'));%0A
+response_authorize.email %7C%7C 'undef');%0A
@@ -1901,36 +1901,32 @@
-
-
const result = e
@@ -1936,28 +1936,24 @@
rHandler();%0A
-
@@ -2025,36 +2025,32 @@
-
%7D);%0A
@@ -2057,33 +2057,92 @@
-%7D
+$container.find('#cashier_unlocked_message').setVisibility(1
);%0A
@@ -2766,16 +2766,17 @@
ce')) %3C
++
withdraw
|
6ef247ff5a2af1dc165e5b18f78dd6d44b165927 | set type days | src/js/components/LineSelectDays.js | src/js/components/LineSelectDays.js | import React, { Component } from 'react'
let menuItems = [
{ menuItem: 'Dias úteis' },
{ menuItem: 'Sábado' },
{ menuItem: 'Domingos e feriados' }
]
class MenuItemDays extends Component {
render () {
return (
<a href='javascript:void(0);' className={this.props.active ? 'day-selected' : ''} onClick={this.props.onClick}>{this.props.label}</a>
)
}
}
export default class LineSelectDays extends Component {
constructor (props) {
super(props)
this.state = {
selectedIndex: 0
}
}
handleDays (index) {
this.setState({
selectedIndex: index
})
}
render () {
return (
<div className='vdb-line-select-days'>
{menuItems.map((item, index) => {
return <MenuItemDays label={item.menuItem}
key={index}
onClick={this.handleDays.bind(this, index)}
active={this.state.selectedIndex === index} />
})}
</div>
)
}
}
| JavaScript | 0.000219 | @@ -79,16 +79,25 @@
s %C3%BAteis'
+, type: 1
%7D,%0A %7B
@@ -114,16 +114,26 @@
'S%C3%A1bado'
+ , type: 2
%7D,%0A %7B
@@ -163,16 +163,25 @@
eriados'
+, type: 3
%7D%0A%5D%0A%0Acl
|
be3e8daecce8170e289a379531ee03c1996c1b2d | Update TableDirective.js | src/js/directives/TableDirective.js | src/js/directives/TableDirective.js | angular.module('JiNGle.directives').directive('jitable', function($filter) {
'use strict';
return {
restrict: 'AE',
replace: 'true',
templateUrl: JiNGle.viewPath + 'TableDirective.html',
scope: {
columns: '=columns',
data: '=data',
create: '@create',
show: '@show',
pdf: '@pdf',
edit: '@edit',
remove: '@delete'
},
link: function($scope, element, attrs) {
$scope.defaultFormatter = $filter('inline');
// Apply sort rules from attribute
$scope.sortRule = [ ];
if (attrs.sort) attrs.sort.words(function(field) { $scope.sortRule.push(field); });
$scope.isSortedAsc = function(field) { return this.sortRule.indexOf(field) !== -1; };
$scope.isSortedDesc = function(field) { return this.sortRule.indexOf('-' + field) !== -1; };
$scope.sortName = function(field) {
var index = $scope.sortRule.indexOf(field);
if (index === -1) {
index = $scope.sortRule.indexOf('-' + field);
if (index === -1) {
$scope.sortRule.unshift(field);
return;
}
$scope.sortRule.splice(index, 1);
return;
}
$scope.sortRule.splice(index, 1);
$scope.sortRule.unshift('-' + field);
};
}
}
});
| JavaScript | 0 | @@ -540,16 +540,19 @@
filter('
+ji_
inline')
|
9072d8dd5d91edaca4ebe0b929c041e84bb2be36 | Update fetch-refs.js | scripts/fetch-refs.js | scripts/fetch-refs.js | #!/usr/bin/env node
var request = require('request'),
userAgent = require("./user-agent"),
helper = require('./helper'),
bibref = require('../lib/bibref');
if (process.argv.length < 4) {
console.log("Usage: fetch-refs.js [url] [publisher] [no-prefix]");
process.exit(1);
}
var SOURCE = process.argv[2];
var PUBLISHER = process.argv[3];
var PREFIX = process.argv[4] != "--no-prefix";
var FILENAME = PUBLISHER.toLowerCase() + ".json";
var HELPER = "./fetch-helpers/" + PUBLISHER.toLowerCase();
var biblio = helper.readBiblio();
var current = helper.readBiblio(FILENAME);
var refs = bibref.createUppercaseRefs(bibref.expandRefs(bibref.raw));
console.log("Updating", PUBLISHER, "references...");
console.log("Fetching", SOURCE + "...");
request({
url: SOURCE,
headers: {
'User-Agent': userAgent()
}
}, function(err, response, body) {
if (err || response.statusCode !== 200) {
console.log("Can't fetch", SOURCE + ".");
return;
}
console.log("Parsing", SOURCE + "...");
var json = JSON.parse(body);
Object.keys(json).forEach(function(id) {
var ref = json[id];
ref = require(HELPER)(id, ref);
ref.publisher = ref.publisher || PUBLISHER;
ref.source = SOURCE;
var uppercaseId = id.toUpperCase();
var prefixedId = PUBLISHER + "-" + id;
if (!(uppercaseId in refs)) {
current[id] = ref;
if (PREFIX) { current[prefixedId] = { aliasOf: id }; }
} else {
var existingRef = refs[uppercaseId];
while (existingRef.aliasOf) { existingRef = refs[existingRef.aliasOf]; }
if (existingRef.source == SOURCE ||
bibref.normalizeUrl(ref.href) == bibref.normalizeUrl(existingRef.href)) {
current[id] = ref;
if (PREFIX) { current[prefixedId] = { aliasOf: id }; }
} else if (PREFIX) {
current[prefixedId] = ref;
} else {
throw new Error("fetch-refs with no-prefix option, cannot override " + id);
}
}
var rv = bibref.reverseLookup([ref.href])[ref.href];
if (rv && rv.id.toUpperCase() != uppercaseId &&
rv.id.toUpperCase() != prefixedId.toUpperCase() &&
// avoid inadvertently catching drafts.
bibref.normalizeUrl(rv.href) == bibref.normalizeUrl(ref.href)) {
current[rv.id] = { aliasOf: prefixedId };
delete biblio[rv.id];
}
});
current = helper.sortRefs(current);
console.log("updating existing refs.")
helper.writeBiblio(FILENAME, current);
helper.tryOverwrite(FILENAME);
helper.writeBiblio(biblio);
});
| JavaScript | 0 | @@ -1646,16 +1646,46 @@
if (
+!(%22source%22 in existingRef) %7C%7C
existing
|
e3d9163ff94e3cd455b2150a2733e5cdd6632cd5 | Implement a temporary list of tainted domains | core/interceptor.js | core/interceptor.js | /**
* Interceptor
* Belongs to Decentraleyes.
*
* @author Thomas Rientjes
* @since 2016-04-06
* @license MPL 2.0
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/.
*/
'use strict';
/**
* Interceptor
*/
var interceptor = {};
/**
* Constants
*/
const HTTP_EXPRESSION = /^http?:\/\//;
/**
* Public Methods
*/
interceptor.handleRequest = function (requestDetails, tabIdentifier, tab) {
let validCandidate, targetDetails, targetPath;
validCandidate = requestAnalyzer.isValidCandidate(requestDetails, tab);
if (!validCandidate) {
return {
'cancel': false
};
}
targetDetails = requestAnalyzer.getLocalTarget(requestDetails);
targetPath = targetDetails.path;
if (!targetPath) {
return interceptor._handleMissingCandidate(requestDetails.url);
}
if (!files[targetPath]) {
return interceptor._handleMissingCandidate(requestDetails.url);
}
stateManager.requests[requestDetails.requestId] = {
'tabIdentifier': tabIdentifier,
'targetDetails': targetDetails
};
return {
'redirectUrl': chrome.extension.getURL(targetPath)
};
};
/**
* Private Methods
*/
interceptor._handleMissingCandidate = function (requestUrl) {
if (interceptor.blockMissing === true) {
return {
'cancel': true
};
}
if (requestUrl.match(HTTP_EXPRESSION)) {
requestUrl = requestUrl.replace(HTTP_EXPRESSION, 'https://');
return {
'redirectUrl': requestUrl
};
} else {
return {
'cancel': false
};
}
};
interceptor._handleStorageChanged = function (changes) {
if ('blockMissing' in changes) {
interceptor.blockMissing = changes.blockMissing.newValue;
}
};
/**
* Initializations
*/
interceptor.amountInjected = 0;
interceptor.blockMissing = false;
chrome.storage.local.get(['amountInjected', 'blockMissing'], function (items) {
interceptor.amountInjected = items.amountInjected || 0;
interceptor.blockMissing = items.blockMissing || false;
});
/**
* Event Handlers
*/
chrome.storage.onChanged.addListener(interceptor._handleStorageChanged);
| JavaScript | 0.004197 | @@ -588,16 +588,27 @@
ndidate,
+ tabDomain,
targetD
@@ -792,24 +792,770 @@
%7D;%0A %7D%0A%0A
+ try %7B%0A tabDomain = tab.url.match(WEB_DOMAIN_EXPRESSION)%5B1%5D;%0A tabDomain = requestAnalyzer._normalizeDomain(tabDomain);%0A %7D catch (exception) %7B%0A tabDomain = 'example.org';%0A %7D%0A%0A // Temporary list of undetectable tainted domains.%0A let undetectableTaintedDomains = %7B%0A 'cdnjs.com': true,%0A 'dropbox.com': true,%0A 'minigames.mail.ru': true,%0A 'report-uri.io': true,%0A 'securityheaders.io': true,%0A 'stefansundin.github.io': true,%0A 'udacity.com': true%0A %7D;%0A%0A if (undetectableTaintedDomains%5BtabDomain%5D %7C%7C /yandex%5C./.test(tabDomain)) %7B%0A%0A if (tabDomain !== 'yandex.ru') %7B%0A return interceptor._handleMissingCandidate(requestDetails.url);%0A %7D%0A %7D%0A%0A
targetDe
|
263d4796377972720f964c67ebc4987788654aa8 | clean console | core/system/view.js | core/system/view.js | var jade = require('jade')
, HTTP = require('constant-list').HTTP
, TYPE = require('constant-list').TYPE
, Promise = require('promise');
module.exports.render = render;
module.exports.json = json;
module.exports.error = error;
module.exports.partial = partial;
function _resolveObject(data, cb) {
if(!data) {
return cb(null, data);
}
var res = {}
, nbKey = Object.keys(data).length
, refLength = 0
, done = false;
function addRef(key, value) {
res[key] = value;
refLength++;
if(!done && refLength >= nbKey ) {
cb(null, res);
done = true;
}
}
for(var key in data) {
var value = data[key];
if(typeof value == TYPE.OBJECT && value.then) {
value.then(
(function(key) {
return function(res) {
addRef(key, res);
}
})(key)
)
.catch(function(e) {
if(!done) {
done = true;
cb(e);
}
});
} else {
addRef(key, value);
}
}
}
var renderFile = Promise.denodeify(jade.renderFile);
var resolveObject = Promise.denodeify(_resolveObject);
function _result(contentType, body) {
return {
contentType: contentType,
body: body
}
}
function render(viewName, data) {
var format = function(view) {
return _result('text/html', view);
};
return partial(viewName, data)
.then(format);
}
function partial(viewName, data) {
console.log('partial', viewName, data);
var resolveData = function() {
return resolveObject(data);
};
var compile = function(content) {
return renderFile(`./views/${viewName}.jade`, content);
};
return resolveData(data)
.then(compile)
}
function json(content) {
return Promise.resolve(
_result('application/json', JSON.stringify(content))
);
}
function error(message) {
return Promise.resolve(
_result('text/html', message)
);
} | JavaScript | 0.000001 | @@ -1452,50 +1452,8 @@
) %7B%0A
- console.log('partial', viewName, data);%0A
va
|
e19a252193e90c444e57641ca6b19c977cd99055 | Fix linter issue | scripts/get-actual.js | scripts/get-actual.js | /**
* Script for downloading actual data files
* Files are kept in ./scripts/assets/<season-id>-actual.json
*/
const utils = require('./utils')
const path = require('path')
const fs = require('fs')
const fct = require('flusight-csv-tools')
const mmwr = require('mmwr-week')
// Variables and paths
const dataDir = './data'
const outputDir = './scripts/assets'
console.log(' Downloading actual data from delphi epidata API')
console.log(' -----------------------------------------------')
console.log(' Messages overlap due to concurrency. Don\'t read too much.\n')
// Look for seasons in the data directory
let seasons = utils.getSubDirectories(dataDir)
// Stop if no folder found
if (seasons.length === 0) {
console.log(' ✕ No seasons found in data directory!')
process.exit(1)
}
// Print seasons
console.log(` Found ${seasons.length} seasons:`)
seasons.forEach(s => console.log(' ' + s))
console.log('')
function seasonWeeks(seasonId) {
let maxWeek = (new mmwr.MMWRDate(seasonId, 30)).nWeeks
return [
...utils.arange(100 * seasonId + 30, 100 * seasonId + maxWeek + 1),
...utils.arange(100 * (seasonId + 1) + 1, 100 * (seasonId + 1) + 30)
]
}
function getActual(season, callback) {
let seasonId = parseInt(season.split('-')[0])
fct.truth.getSeasonDataAllLags(seasonId)
.then(d => {
// Transfer data for the format used in flusight
// TODO: Use the standard format set in fct
fct.meta.regionIds.forEach(rid => {
d[rid].forEach(({ epiweek, wili, lagData }, idx) => {
d[rid][idx] = {
week: epiweek,
actual: wili,
lagData: lagData.map(ld => {
return { lag: ld.lag, value: ld.wili }
})
}
})
})
// Fill in nulls for weeks not present in the data
let weeks = seasonWeeks(seasonId)
fct.meta.regionIds.forEach(rid => {
let availableWeeks = d[rid].map(({ week }) => week)
weeks.forEach(ew => {
if (availableWeeks.indexOf(ew) === -1) {
d[rid].push({
week: ew,
actual: null,
lagData: []
})
}
})
})
callback(d)
})
.catch(e => {
console.log(`Error while processing ${season}`)
console.log(e)
process.exit(1)
})
}
seasons.forEach((seasonId, seasonIdx) => {
let seasonOutFile = path.join(outputDir, `${seasonId}-actual.json`)
console.log(` Downloading data for ${seasonId}`)
getActual(seasonId, actualData => {
fs.writeFile(seasonOutFile, JSON.stringify(actualData), (err) => {
if (err) throw err
console.log(` ✓ File written at ${seasonOutFile}`)
})
})
})
| JavaScript | 0 | @@ -924,32 +924,33 @@
tion seasonWeeks
+
(seasonId) %7B%0A l
@@ -1180,24 +1180,25 @@
on getActual
+
(season, cal
|
279fb4a7e0b8eaf096f540ddf90b32802170c3b7 | fix deploy script condition (take 10) | scripts/git-builds.js | scripts/git-builds.js | #!/usr/bin/env node
'use strict';
/* eslint-disable no-console */
const spawnSync = require( 'child_process').spawnSync;
const fs = require('fs');
const temp = require('temp');
const { blue, green, red, gray, yellow } = require('chalk');
const path = require('path');
const glob = require('glob');
const cli = 'https://github.com/angular/angular-cli.git';
const cliBuilds = 'https://github.com/angular/cli-builds.git';
const ngToolsWebpackBuilds = 'https://github.com/angular/ngtools-webpack-builds.git';
class Executor {
constructor(cwd) { this._cwd = cwd; }
execute(command, ...args) {
args = args.filter(x => x !== undefined);
console.log(blue(`Running \`${command} ${args.map(x => `"${x}"`).join(' ')}\`...`));
console.log(blue(`CWD: ${this._cwd}`));
const runCommand = spawnSync(command, args, { cwd: this._cwd });
if (runCommand.status === 0) {
console.log(gray(runCommand.stdout.toString()));
return runCommand.stdout.toString();
} else {
throw new Error(
`Command returned status ${runCommand.status}. Details:\n${runCommand.stderr}`);
}
}
git(...args) { return this.execute('git', ...args); }
npm(...args) { return this.execute('npm', ...args); }
rm(...args) { return this.execute('rm', ...args); }
glob(pattern, options) {
return glob.sync(pattern, Object.assign({}, options || {}, { cwd: this._cwd }));
}
cp(root, destRoot) {
function mkdirp(p) {
if (fs.existsSync(p)) {
return;
}
mkdirp(path.dirname(p));
fs.mkdirSync(p);
}
this.glob(path.join(root, '**/*'), { nodir: true })
.forEach(name => {
const src = name;
const dest = path.join(destRoot, src.substr(root.length));
mkdirp(path.dirname(dest));
fs.writeFileSync(dest, fs.readFileSync(src));
});
}
read(p) {
return fs.readFileSync(path.join(this._cwd, p), 'utf-8');
}
write(p, content) {
fs.writeFileSync(path.join(this._cwd, p), content);
}
updateVersion(hash) {
const packageJson = JSON.parse(this.read('package.json'));
packageJson.version = `${packageJson.version}-${hash.substr(1, 7)}`;
this.write('package.json', JSON.stringify(packageJson, null, 2));
}
updateDependencies(hash) {
const packageJson = JSON.parse(this.read('package.json'));
packageJson.dependencies['@ngtools/webpack'] = ngToolsWebpackBuilds + '#' + hash;
this.write('package.json', JSON.stringify(packageJson, null, 2));
}
}
async function main() {
const cliPath = process.cwd();
const cliExec = new Executor(cliPath);
const tempRoot = temp.mkdirSync('angular-cli-builds');
const tempExec = new Executor(tempRoot);
console.log(green(`Cloning builds repos...\n`));
tempExec.git('clone', cliBuilds);
tempExec.git('clone', ngToolsWebpackBuilds);
console.log(green('Building...'));
const cliBuildsRoot = path.join(tempRoot, 'cli-builds');
const cliBuildsExec = new Executor(cliBuildsRoot);
const ngToolsWebpackBuildsRoot = path.join(tempRoot, 'ngtools-webpack-builds');
const ngToolsWebpackBuildsExec = new Executor(ngToolsWebpackBuildsRoot);
cliExec.npm('run', 'build');
const message = cliExec.git('log', '--format=%h %s', '-n', '1');
const hash = message.split(' ')[0];
console.log(green('Copying ng-tools-webpack-builds dist'));
ngToolsWebpackBuildsExec.git('checkout', '-B', process.env['TRAVIS_BRANCH']);
ngToolsWebpackBuildsExec.rm('-rf', ...ngToolsWebpackBuildsExec.glob('*'));
cliExec.cp('dist/@ngtools/webpack', ngToolsWebpackBuildsRoot);
console.log(green('Updating package.json version'));
ngToolsWebpackBuildsExec.updateVersion(hash);
ngToolsWebpackBuildsExec.git('add', '-A');
ngToolsWebpackBuildsExec.git('commit', '-m', message);
ngToolsWebpackBuildsExec.git('tag', hash);
ngToolsWebpackBuildsExec.git('config', 'credential.helper', 'store --file=.git/credentials');
ngToolsWebpackBuildsExec.write('.git/credentials',
`https://${process.env['GITHUB_ACCESS_TOKEN']}@github.com`);
console.log(green('Copying cli-builds dist'));
cliBuildsExec.git('checkout', '-B', process.env['TRAVIS_BRANCH']);
cliBuildsExec.rm('-rf', ...cliBuildsExec.glob('*'));
cliExec.cp('dist/@angular/cli', cliBuildsRoot);
console.log(green('Updating package.json version'));
cliBuildsExec.updateVersion(hash);
cliBuildsExec.updateDependencies(hash);
cliBuildsExec.git('add', '-A');
cliBuildsExec.git('commit', '-m', message);
cliBuildsExec.git('tag', hash);
cliBuildsExec.git('config', 'credential.helper', 'store --file=.git/credentials');
cliBuildsExec.write('.git/credentials',
`https://${process.env['GITHUB_ACCESS_TOKEN']}@github.com`);
console.log(green('Done. Pushing...'));
ngToolsWebpackBuildsExec.git('push', '-f');
ngToolsWebpackBuildsExec.git('push', '--tags');
cliBuildsExec.git('push', '-f');
cliBuildsExec.git('push', '--tags');
}
main()
.then(() => console.log(green('All good. Thank you.')))
.catch(err => console.log(red('Error happened. Details:\n' + err)));
| JavaScript | 0 | @@ -2491,14 +2491,8 @@
%7D%0A%0A%0A
-async
func
@@ -4906,134 +4906,6 @@
in()
-%0A .then(() =%3E console.log(green('All good. Thank you.')))%0A .catch(err =%3E console.log(red('Error happened. Details:%5Cn' + err)))
;%0A
|
41a0c7e7f640322b4373f2e53f4b2b118350d274 | clean up on map unload | layer/tile/Yandex.js | layer/tile/Yandex.js | // https://tech.yandex.com/maps/doc/jsapi/2.1/quick-start/index-docpage/
/* global ymaps: true */
L.Yandex = L.Layer.extend({
options: {
type: 'yandex#map', // 'map', 'satellite', 'hybrid', 'map~vector' | 'overlay', 'skeleton'
mapOptions: { // https://tech.yandex.com/maps/doc/jsapi/2.1/ref/reference/Map-docpage/#Map__param-options
// yandexMapDisablePoiInteractivity: true,
balloonAutoPan: false,
suppressMapOpenBlock: true
},
overlayOpacity: 0.8,
minZoom: 0,
maxZoom: 19
},
initialize: function (type, options) {
if (typeof type === 'object') {
options = type;
type = false;
}
options = L.Util.setOptions(this, options);
if (type) { options.type = type; }
this._isOverlay = options.type.indexOf('overlay') !== -1 ||
options.type.indexOf('skeleton') !== -1;
},
_setStyle: function (el, style) {
for (var prop in style) {
el.style[prop] = style[prop];
}
},
_initContainer: function (parentEl) {
var className = 'leaflet-yandex-layer leaflet-map-pane leaflet-pane '
+ (this._isOverlay ? 'leaflet-overlay-pane' : 'leaflet-tile-pane');
var _container = L.DomUtil.create('div', className);
_container.id = '_YMapContainer_' + L.Util.stamp(this);
var opacity = this.options.opacity || this._isOverlay && this.options.overlayOpacity;
if (opacity) {
L.DomUtil.setOpacity(_container, opacity);
}
var auto = { width: '100%', height: '100%' };
this._setStyle(parentEl, auto); // need to set this explicitly,
this._setStyle(_container, auto); // otherwise ymaps fails to follow container size changes
return _container;
},
onAdd: function (map) {
var mapPane = map.getPane('mapPane');
if (!this._container) {
this._container = this._initContainer(mapPane);
ymaps.ready(this._initMapObject, this);
}
mapPane.appendChild(this._container);
if (!this._yandex) { return; }
this._update();
},
beforeAdd: function (map) {
map._addZoomLimit(this);
},
onRemove: function (map) {
// do not remove container until api is initialized (ymaps API expects DOM element)
if (this._yandex) {
this._container.remove();
}
map._removeZoomLimit(this);
},
getEvents: function () {
var events = {
move: this._update
};
if (this._zoomAnimated) {
events.zoomanim = this._animateZoom;
}
return events;
},
_update: function () {
if (!this._yandex) { return; }
var map = this._map;
var center = map.getCenter();
this._yandex.setCenter([center.lat, center.lng], map.getZoom());
var offset = L.point(0,0).subtract(L.DomUtil.getPosition(map.getPane('mapPane')));
L.DomUtil.setPosition(this._container, offset); // move to visible part of pane
},
_animateZoom: function (e) {
if (!this._yandex) { return; }
var map = this._map;
var viewHalf = map.getSize()._divideBy(2);
var topLeft = map.project(e.center, e.zoom)._subtract(viewHalf)._round();
var offset = map.project(map.getBounds().getNorthWest(), e.zoom)._subtract(topLeft);
var scale = map.getZoomScale(e.zoom);
this._yandex.panes._array.forEach(function (el) {
if (el.pane instanceof ymaps.pane.MovablePane) {
var element = el.pane.getElement();
L.DomUtil.addClass(element, 'leaflet-zoom-animated');
L.DomUtil.setTransform(element, offset, scale);
}
});
},
_mapType: function () {
var shortType = this.options.type;
if (!shortType || shortType.indexOf('#') !== -1) {
return shortType;
}
return 'yandex#' + shortType;
},
_initMapObject: function () {
ymaps.mapType.storage.add('yandex#overlay', new ymaps.MapType('overlay', []));
ymaps.mapType.storage.add('yandex#skeleton', new ymaps.MapType('skeleton', ['yandex#skeleton']));
ymaps.mapType.storage.add('yandex#map~vector', new ymaps.MapType('map~vector', ['yandex#map~vector']));
var ymap = new ymaps.Map(this._container, {
center: [0, 0], zoom: 0, behaviors: [], controls: [],
type: this._mapType()
}, this.options.mapOptions);
if (this._isOverlay) {
ymap.container.getElement().style.background = 'transparent';
}
if (this.options.trafficControl) {
ymap.controls.add('trafficControl', { size: 'small' });
ymap.controls.get('trafficControl').state.set({ trafficShown: true });
}
this._container.remove(); // see onRemove comments
this._yandex = ymap;
if (this._map) { this.onAdd(this._map); }
//Reporting that map-object was initialized
this.fire('MapObjectInitialized', { mapObject: ymap });
}
});
L.yandex = function (type, options) {
return new L.Yandex(type, options);
};
| JavaScript | 0 | @@ -1755,16 +1755,60 @@
pPane);%0A
+%09%09%09map.once('unload', this._destroy, this);%0A
%09%09%09ymaps
@@ -2207,16 +2207,205 @@
);%0A%09%7D,%0A%0A
+%09_destroy: function (e) %7B%0A%09%09if (!this._map %7C%7C this._map === e.target) %7B%0A%09%09%09if (this._yandex) %7B%0A%09%09%09%09this._yandex.destroy();%0A%09%09%09%09delete this._yandex;%0A%09%09%09%7D%0A%09%09%09delete this._container;%0A%09%09%7D%0A%09%7D,%0A%0A
%09getEven
|
2cacfa9d99240383a82a2aff78d9973732186058 | Fix broken calls to data | challenge-completed.js | challenge-completed.js | #!/usr/bin/env node
var fs = require('fs')
var userData = require('./user-data.js')
// TODO what is this doing
var data
var disableVerifyButtons = function (boolean) {
document.getElementById('verify-challenge').disabled = boolean
var directoryButton = document.getElementById('select-directory')
if (directoryButton) { document.getElementById('select-directory').disabled = boolean }
}
var clearStatus = function (challenge) {
var clearStatusButton = document.getElementById('clear-completed-challenge')
clearStatusButton.addEventListener('click', function clicked (event) {
data[challenge].completed = false
fs.writeFileSync('./data.json', JSON.stringify(data, null, 2))
document.getElementById('challenge-completed').style.display = 'none'
disableVerifyButtons(false)
// if there is a list of passed parts of challenge, remove it
var element = document.getElementById('verify-list')
if (element) {
while (element.firstChild) {
element.removeChild(element.firstChild)
}
}
})
}
var completed = function (challenge) {
challenge = challenge
document.addEventListener('DOMContentLoaded', function (event) {
checkCompletedness()
})
function checkCompletedness () {
var data = userData.getData()
if (data.contents[challenge].completed) {
document.getElementById('challenge-completed').style.display = 'inherit'
clearStatus(challenge)
disableVerifyButtons(true)
}
}
}
module.exports.clearStatus = clearStatus
module.exports.completed = completed
module.exports.disableVerifyButtons = disableVerifyButtons
| JavaScript | 0.000129 | @@ -84,35 +84,8 @@
')%0A%0A
-// TODO what is this doing%0A
var
@@ -364,25 +364,31 @@
an %7D%0A%7D%0A%0Avar
-c
+enableC
learStatus =
@@ -567,20 +567,96 @@
) %7B%0A
-data
+// set challenge to uncomplted and update the user's data file%0A data.contents
%5Bchallen
@@ -744,16 +744,91 @@
ll, 2))%0A
+ // remove the completed status from the page and renable verify button%0A
docu
@@ -1373,20 +1373,16 @@
) %7B%0A
-var
data = u
@@ -1528,16 +1528,88 @@
it'%0A
-%0A
-c
+// If completed, show clear button and disable verify button%0A enableC
lear
@@ -1701,17 +1701,23 @@
tatus =
-c
+enableC
learStat
|
e26b1f7a87f11184e932425acd6d35a0ed50d685 | Tidy up onBeforeAction | client/main.js | client/main.js | Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading'
});
Router.onBeforeAction(function(pause) {
if (!Meteor.userId() && !Meteor.loggingIn()) {
this.render('login');
pause();
}
this.subscribe('messages').wait();
this.subscribe('students').wait();
this.subscribe('allUserData').wait();
}, {except: 'login'});
Router.map(function() {
this.route('home', {
path: '/',
data: {
messages: Messages.find({}, {sort: {created_at: -1}}),
students: Students.find({}, {sort: {name: 1}})
}
});
this.route('students', {
data: {
students: Students.find({}, {sort: {name: 1}})
}
});
this.route('tutors', {
data: {
tutors: Meteor.users.find({}, {sort: {'profile.name': 1}})
}
});
});
Template.home.helpers({
display_from: function() {
if (this.to) {
return this.from;
} else if (this.from) {
return Students.findOne(this.from);
}
},
recipients: function() {
return this.to.map(function(id) {
return Students.findOne(id);
});
},
display_date: function() {
return moment(this.created_at).calendar();
}
});
Template.home.events({
'submit form': function(e, t) {
e.preventDefault();
var to = _.pluck(t.findAll('option:selected'), 'value');
var text = t.find('textarea').value;
var message = {
from: Meteor.user().profile.name,
to: to,
text: text,
created_at: new Date()
};
Messages.insert(message);
e.target.reset();
},
'click label a': function(e, t) {
e.preventDefault();
t.findAll('option').prop('selected', true);
},
'click blockquote a': function(e, t) {
e.preventDefault();
t.findAll('option').prop('selected', false);
_.each(this.to ? this.to : [this.from], function(id) {
var option = t.find('option[value=' + id + ']');
if (option) {
option.selected = true;
}
});
}
});
Template.students.helpers({
phone: function() {
return this.phone.replace(/^44/, '0');
},
filereader: function() {
return !!window.FileReader;
}
});
Template.students.events({
'submit form': function(e, t) {
e.preventDefault();
var name = t.find('input[name=name]').value;
var phone = t.find('input[name=phone]').value.replace(/ /g, '').replace(/^0/, '44');
Students.insert({name: name, phone: phone});
e.target.reset();
},
'click a': function(e) {
e.preventDefault();
Students.remove(this._id);
},
'change input[type=file]': function(e) {
var reader = new FileReader();
reader.onload = function() {
reader.result.split(/BEGIN:VCARD/).forEach(function(vcard) {
var tel = vcard.match(/TEL;(?:TYPE=)CELL:([0-9-]+)/) || vcard.match(/TEL;(?:TYPE=)[A-Z]+:[+]?([0-9-]+)/);
if (tel) {
var phone = tel[1].replace(/-/g, '').replace(/^0/, '44');
if (!Students.findOne({phone: phone})) {
var fn = vcard.match(/FN:(.*)/);
if (fn) {
Students.insert({name: fn[1], phone: phone});
}
}
}
});
};
reader.readAsText(e.target.files[0]);
e.target.parentNode.parentNode.reset();
}
});
Template.tutors.events({
'submit form': function(e, t) {
e.preventDefault();
var name = t.find('input[name=name]').value;
var email = t.find('input[name=email]').value;
Meteor.call('addUser', name, email);
e.target.reset();
},
'click a': function(e) {
e.preventDefault();
if (this._id !== Meteor.userId()) {
Meteor.users.remove(this._id);
}
}
});
UI.registerHelper('eq', function(a, b) {
return a === b;
});
UI.registerHelper('lte', function(a, b) {
return a <= b;
});
UI.registerHelper('currentPage', function(path) {
return Router.current().path.substring(1) === path;
});
moment.lang(navigator.language || navigator.userLanguage);
| JavaScript | 0.00005 | @@ -42,38 +42,143 @@
out'
-,%0A loadingTemplate: 'loading'
+%0A%7D);%0ARouter.waitOn(function() %7B%0A return %5BMeteor.subscribe('messages'), Meteor.subscribe('students'), Meteor.subscribe('allUserData')%5D;
%0A%7D);
@@ -312,143 +312,102 @@
;%0A
-%7D%0A this.subscribe('messages').wait();%0A
+ return;%0A %7D%0A if (!this.ready()) %7B%0A
this.
-subscribe('students').wait();%0A this.subscribe('allUserData').wait();%0A%7D, %7Bexcept: 'login'
+render('loading');%0A pause();%0A return;%0A %7D%0A
%7D);%0A
|
f0d0350cbea0672adf16e3200457f40741fce9bf | Update login.js | Duplicati/Server/webroot/login/login.js | Duplicati/Server/webroot/login/login.js | $(document).ready(function() {
var processing = false;
$('#login-button').click(function() {
if (processing)
return;
processing = true;
// First we grab the nonce and salt
$.ajax({
url: './login.cgi',
type: 'POST',
dataType: 'json',
data: {'get-nonce': 1}
})
.done(function(data) {
var saltedpwd = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(CryptoJS.enc.Utf8.parse($('#login-password').val()) + CryptoJS.enc.Base64.parse(data.Salt)));
var noncedpwd = CryptoJS.SHA256(CryptoJS.enc.Hex.parse(CryptoJS.enc.Base64.parse(data.Nonce) + saltedpwd)).toString(CryptoJS.enc.Base64);
$.ajax({
url: './login.cgi',
type: 'POST',
dataType: 'json',
data: {'password': noncedpwd }
})
.done(function(data) {
window.location = '/';
})
.fail(function(data) {
var txt = data;
if (txt && txt.statusText)
txt = txt.statusText;
alert('Login failed: ' + txt);
processing = false;
});
})
.fail(function(data) {
var txt = data;
if (txt && txt.statusText)
txt = txt.statusText;
alert('Failed to get nonce: ' + txt);
processing = false;
});
return false;
});
});
| JavaScript | 0.007737 | @@ -961,16 +961,17 @@
tion = '
+.
/';%0A
|
9f2accdacf5692301533c062a7a1a4fc1e8951a8 | Fix Unfocus placement | client/menu.js | client/menu.js |
(function () {
$DOC.on('click', '.control', function (event) {
var $target = $(event.target);
if ($target.is('li')) {
var handler = menuHandlers[$target.text()];
if (handler)
handler(parent_post($target));
}
var $menu = $(this).find('ul');
if ($menu.length)
$menu.remove();
else {
$menu = $('<ul/>');
var opts = menuOptions.slice();
/* TODO: Use model lookup */
var $post = parent_post($target);
var num = $post.attr('id');
if ($post.length && !num)
opts = ['Focus']; /* Just a draft, can't do much */
if (lockTarget && lockTarget == num) {
opts.shift();
opts.unshift('Unfocus');
}
_.each(opts, function (opt) {
$('<li/>').text(opt).appendTo($menu);
});
$menu.appendTo(this);
}
});
$DOC.on('mouseleave', 'ul', function (event) {
var $ul = $(this);
if (!$ul.is('ul'))
return;
event.stopPropagation();
var timer = setTimeout(function () {
/* Using $.proxy() here breaks FF? */
$ul.remove();
}, 300);
/* TODO: Store in view instead */
$ul.data('closetimer', timer);
});
$DOC.on('mouseenter', 'ul', function (event) {
var $ul = $(this);
var timer = $ul.data('closetimer');
if (timer) {
clearTimeout(timer);
$ul.removeData('closetimer');
}
});
oneeSama.hook('headerFinish', function (info) {
info.header.unshift(safe('<span class="control"/>'));
});
oneeSama.hook('draft', function ($post) {
$post.find('header').prepend('<span class=control/>');
});
$('<span class=control/>').prependTo('header');
})();
| JavaScript | 0.000001 | @@ -567,18 +567,16 @@
== num)
- %7B
%0A%09%09%09opts
@@ -581,32 +581,40 @@
ts.s
-hift();%0A%09%09%09opts.unshift(
+plice(opts.indexOf('Focus'), 1,
'Unf
@@ -620,20 +620,16 @@
focus');
-%0A%09%09%7D
%0A%0A%09%09_.ea
|
6b4793bc657a164f234250a42f45a32a5575651d | Fix jshint issue | client/src/conflict.js | client/src/conflict.js | /**
* Utility functions for working with Conflicted Files.
*/
var Path = require('../../lib/filer.js').Path;
// Rename oldPath to newPath, deleting newPath if it exists
function forceRename(fs, oldPath, newPath, callback) {
fs.rename(oldPath, newPath, function(err) {
if(err) {
if(err.code !== 'EEXIST') {
return callback(err);
} else {
fs.rm(newPath, function(err) {
if(err) {
return callback(err);
}
forceRename(fs, oldPath, newPath, callback);
});
}
}
callback();
});
}
// Turn "/index.html" into "/index.html (Conflicted Copy 2014-07-23 12:00:00).html"
function generateConflictedPath(fs, path, callback) {
var dirname = Path.dirname(path);
var basename = Path.basename(path);
var extname = Path.extname(path);
var now = new Date;
var dateStamp = now.getFullYear() + '-' +
now.getMonth() + '-' +
now.getDay() + ' ' +
now.getHours() + ':' +
now.getMinutes() + ':' +
now.getSeconds();
var conflictedCopy = ' (Conflicted Copy ' + dateStamp + ')';
var conflictedPath = Path.join(dirname, basename + conflictedCopy + extname);
// Rename the path using the conflicted filename. If there is
// already a conflicted path, replace it with this one.
forceRename(fs, path, conflictedPath, function(err) {
if(err) {
return callback(err);
}
// Send the new path back on the callback
callback(null, conflictedPath);
});
}
function pathContainsConflicted(path) {
// Look for path to be a conflicted copy, e.g.,
// /dir/index (Conflicted Copy 2014-07-23 12:00:00).html
return /\(Conflicted Copy \d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}\)/.test(path);
}
function isConflicted(fs, path, callback) {
fs.getxattr(path, 'makedrive-conflict', function(err, value) {
if(err && err.code !== 'ENOATTR') {
return callback(err);
}
callback(null, !!value);
});
}
function markConflicted(fs, path, callback) {
generateConflictedPath(fs, path, function(err, conflictedPath) {
fs.setxattr(conflictedPath, 'makedrive-conflict', true, function(err) {
if(err) {
return callback(err);
}
callback(null, conflictedPath);
});
});
}
function removeConflict(fs, path, callback) {
fs.removexattr(path, 'makedrive-conflict', function(err) {
if(err && err.code !== 'ENOATTR') {
return callback(err);
}
callback();
});
}
module.exports = {
pathContainsConflicted: pathContainsConflicted,
isConflicted: isConflicted,
markConflicted: markConflicted,
removeConflict: removeConflict
};
| JavaScript | 0.000001 | @@ -841,16 +841,18 @@
new Date
+()
;%0A var
|
dc37be10cda56bbec51d8b0538fbb6ae973e8ead | Fix paddings of dynamic list item | lib/List/ListItem.js | lib/List/ListItem.js | import {
StyleSheet,
View,
Text,
TouchableWithoutFeedback,
TouchableNativeFeedback
} from 'react-native';
import { TYPO, COLOR } from '../config';
import Icon from '../Icon';
import IconToggle from '../IconToggle';
import React, { Component, PropTypes } from 'react';
const propTypes = {
// generally
dense: PropTypes.bool,
onPress: PropTypes.func,
onPressValue: PropTypes.any,
lines: React.PropTypes.oneOf([1, 2, 3, 'dynamic']),
style: PropTypes.object,
// left side
leftElement: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
]),
onLeftElementPress: PropTypes.func,
// center side
centerElement: PropTypes.oneOfType([
PropTypes.shape({
primaryText: PropTypes.string.isRequired,
secondaryText: PropTypes.string,
})
]),
// right side
rightElement: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
]),
onRightElementPress: PropTypes.func
};
const defaultProps = {
lines: 1,
style: {},
};
const defaultStyles = StyleSheet.create({
listItemContainer: {
backgroundColor: '#ffffff',
flex: 1,
flexDirection: 'row',
paddingVertical: 8,
},
contentViewContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
},
leftElementContainer: {
flexDirection: 'column',
width: 56,
},
centerElementContainer: {
paddingLeft: 16,
flex: 1,
},
textViewContainer: {
flex: 1,
},
primaryText: {
color: 'rgba(0,0,0,.87)',
lineHeight: 24,
...TYPO.paperFontSubhead,
},
firstLine: {
flexDirection: 'row'
},
primaryTextContainer: {
flex: 1
},
secondaryText: Object.assign({}, TYPO.paperFontBody1, {
lineHeight: 22,
fontSize: 14,
color: 'rgba(0,0,0,.54)',
}),
rightElementContainer: {
paddingLeft: 16,
},
icon: {
margin: 16,
},
});
/**
* Please see this: https://material.google.com/components/lists.html#lists-specs
*/
const getListItemHeight = ({ leftElement, dense, numberOfLines }) => {
if (numberOfLines === 'dynamic') {
return null;
}
if (!leftElement && numberOfLines === 1) {
return dense ? 40 : 48;
}
if (numberOfLines === 1) {
return dense ? 48 : 56;
} else if (numberOfLines === 2) {
return dense ? 60 : 72;
} else if (numberOfLines === 3) {
return dense ? 80 : 88;
}
return null;
};
class ListItem extends Component {
onListItemPressed = () => {
const { onPress, onPressValue } = this.props;
if (onPress) {
onPress(onPressValue);
}
};
onLeftElementPressed = () => {
const { onLeftElementPress, onPress, onPressValue } = this.props;
if (onLeftElementPress) {
onLeftElementPress(onPressValue);
}
if (onPress) {
onPress(onPressValue);
}
};
onRightElementPressed = () => {
const { onRightElementPress, onPressValue } = this.props;
if (onRightElementPress) {
onRightElementPress(onPressValue);
}
};
getDynamicStyle = (key) => {
const {
dense,
lines,
leftElement,
centerElement,
rightElement,
} = this.props;
const result = {};
if (key === 'listItemContainer' || key === 'contentViewContainer') {
let numberOfLines = lines;
if (centerElement && centerElement.secondaryText && (!lines || lines < 2)) {
numberOfLines = 2;
}
result.contentViewContainer = {};
result.listItemContainer = {
height: getListItemHeight({ dense, leftElement, numberOfLines })
};
if (numberOfLines === 3) {
result.listItemContainer.alignItems = 'center';
} else if (numberOfLines === 2) {
result.contentViewContainer.alignItems = 'center';
} else if (numberOfLines === 1) {
result.contentViewContainer.alignItems = 'center';
} else if (numberOfLines === 'dynamic') {
result.listItemContainer = {
alignItems: 'center',
paddingTop: 16,
paddingBottom: 16
};
}
if (typeof rightElement !== 'string') {
result.listItemContainer.paddingRight = 16;
}
} else if (key === 'leftElementContainer') {
result.leftElementContainer = {};
if (typeof leftElement !== 'string') {
result.leftElementContainer.paddingLeft = 16;
}
}
return result;
}
getStyle = (key) => {
const { style } = this.props;
const dynamicStyles = this.getDynamicStyle(key);
return [
defaultStyles[key],
dynamicStyles[key],
style[key],
];
}
renderLeftElement = () => {
const { leftElement } = this.props;
if (!leftElement) {
return null;
}
let content = null;
if (typeof leftElement === 'string') {
content = (
<TouchableWithoutFeedback onPress={this.onLeftElementPressed}>
<Icon name={leftElement} size={24} style={this.getStyle('icon')} />
</TouchableWithoutFeedback>
);
} else {
content = (
<TouchableWithoutFeedback onPress={this.onLeftElementPressed}>
<View>
{leftElement}
</View>
</TouchableWithoutFeedback>
);
}
return (
<View style={this.getStyle('leftElementContainer')}>
{content}
</View>
);
}
renderCenterElement = () => {
const {
lines,
centerElement
} = this.props;
const primaryText = centerElement && centerElement.primaryText;
const secondaryText = centerElement && centerElement.secondaryText;
let content = null;
content = (
<View style={this.getStyle('textViewContainer')}>
<View style={this.getStyle('firstLine')}>
<View style={this.getStyle('primaryTextContainer')}>
<Text
numberOfLines={lines && lines === 'dynamic' ? null : 1}
style={this.getStyle('primaryText')}
>
{primaryText}
</Text>
</View>
</View>
{secondaryText &&
<View>
<Text style={this.getStyle('secondaryText')}>
{secondaryText}
</Text>
</View>
}
</View>
);
return (
<View style={this.getStyle('centerElementContainer')}>
{content}
</View>
);
}
renderRightElement = () => {
const { rightElement } = this.props;
let content = null;
if (typeof rightElement === 'string') {
content = (
<IconToggle color={COLOR.paperGrey500.color} onPress={this.onRightElementPressed}>
<Icon name={rightElement} size={24} style={this.getStyle('icon')} />
</IconToggle>
);
} else {
content = (
<TouchableWithoutFeedback onPress={this.onRightElementPressed}>
<View>
{rightElement}
</View>
</TouchableWithoutFeedback>
);
}
return (
<View style={this.getStyle('rightElementContainer')}>
{content}
</View>
);
}
render() {
const { onPress } = this.props;
const content = (
<View style={this.getStyle('listItemContainer')}>
<View style={this.getStyle('contentViewContainer')}>
{this.renderLeftElement()}
{this.renderCenterElement()}
{this.renderRightElement()}
</View>
</View>
);
if (onPress) {
return (
<TouchableNativeFeedback onPress={this.onListItemPressed}>
{content}
</TouchableNativeFeedback>
);
}
return content;
}
}
ListItem.propTypes = propTypes;
ListItem.defaultProps = defaultProps;
export default ListItem;
| JavaScript | 0.000001 | @@ -4418,82 +4418,8 @@
r',%0A
- paddingTop: 16,%0A paddingBottom: 16%0A
|
16b481a816672c6d46610b6f58b1a84fa00b3db9 | fix option 'all' | app/javascript/pages/country/utils/filters.js | app/javascript/pages/country/utils/filters.js | import deburr from 'lodash/deburr';
import toUpper from 'lodash/toUpper';
import pick from 'lodash/pick';
import isEmpty from 'lodash/isEmpty';
import { createSelector } from 'reselect';
import INDICATORS from './indicators.json';
export function deburrUpper(string) {
return toUpper(deburr(string));
}
export const sortLabelByAlpha = array =>
array.sort((a, b) => {
if (a.label < b.label) return -1;
if (a.label > b.label) return 1;
return 0;
});
// get list data
const getAdmins = state => state.location || null;
const getCountries = state => state.countries || null;
const getRegions = state => state.regions || null;
const getSubRegions = state => state.subRegions || null;
const loadWhiteList = state => state.whitelist || null;
// get lists selected
export const getAdminsOptions = createSelector(
[getCountries, getRegions, getSubRegions],
(countries, regions, subRegions) => ({
countries: (countries && sortLabelByAlpha(countries)) || null,
regions:
(regions &&
[{ label: 'All Regions', value: null }].concat(
sortLabelByAlpha(regions)
)) ||
null,
subRegions:
(subRegions &&
[{ label: 'All Juristictions', value: null }].concat(
sortLabelByAlpha(subRegions)
)) ||
null
})
);
// get lists selected
export const getAdminsSelected = createSelector(
[getAdminsOptions, getAdmins],
(options, adminsSelected) => {
const country =
(options.countries &&
options.countries.find(i => i.value === adminsSelected.country)) ||
null;
const region =
(options.regions &&
options.regions.find(i => {
if (!adminsSelected.region) return options.regions[0];
return i.value === adminsSelected.region;
})) ||
null;
const subRegion =
(options.subRegions &&
options.subRegions.find(i => {
if (!adminsSelected.subRegion) return options.subRegions[0];
return i.value === adminsSelected.subRegion;
})) ||
null;
let current = country;
if (adminsSelected.subRegion) {
current = subRegion;
} else if (adminsSelected.region) {
current = region;
}
return {
country,
region,
subRegion,
current
};
}
);
export const getIndicators = createSelector(
[loadWhiteList, getAdminsSelected],
(whitelist, locationNames) => {
if (isEmpty(locationNames) || !locationNames.current) return null;
const selectedIndicators = pick(INDICATORS, whitelist);
const indicators = Object.keys(selectedIndicators).map(index => {
const indicator = selectedIndicators[index];
if (indicator.value === 'gadm28') {
indicator.label = indicator.label.replace(
'{location}',
locationNames.current.label
);
}
return indicator;
});
return indicators;
}
);
| JavaScript | 0.999999 | @@ -99,16 +99,52 @@
/pick';%0A
+import values from 'lodash/values';%0A
import i
@@ -2521,25 +2521,17 @@
const
-selectedI
+i
ndicator
@@ -2534,16 +2534,23 @@
ators =
+values(
pick(IND
@@ -2572,74 +2572,18 @@
ist)
-;%0A const indicators = Object.keys(selectedIndicators
).map(i
-ndex
+tem
=%3E
@@ -2612,33 +2612,12 @@
r =
-selectedIndicators%5Bindex%5D
+item
;%0A
@@ -2686,67 +2686,18 @@
l =
-indicator.label.replace(%0A '%7Blocation%7D',%0A
+%60All of $%7B
loca
@@ -2719,26 +2719,18 @@
nt.label
-%0A )
+%7D%60
;%0A
|
ffd1f2252750782f566def9f2d430e693ba057f5 | Fix bug where allegiance tree view nodes weren't clickable | vendor/assets/javascripts/tree.js | vendor/assets/javascripts/tree.js | var draw = function(selector, json, server_name, allegiance_name, options) {
var width = options.width || 800,
height = options.height || 800;
var svg = d3.select(selector).append("svg")
.attr("width", width)
.attr("height", height);
var g = svg.append("g");
var force = d3.layout.force()
.size([width, height])
.linkDistance(100)
.friction(0.8)
.charge(-500)
// .chargeDistance(100)
// .gravity(0.01)
// .theta(0.8)
.nodes(json.nodes)
.links(json.links)
.start();
var zoomed = function () {
g.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
}
var zoom = d3.behavior.zoom()
.translate([0,0])
.scale(.8)
.scaleExtent([.2, 2])
.on("zoom", zoomed);
svg.append("rect")
.attr("class", "overlay")
.attr("width", width)
.attr("height", height);
svg.
call(zoom).
call(zoom.event);
var link = g.selectAll(".link")
.data(json.links)
.enter().append("line")
.attr("class", "link");
var node = g.selectAll(".node")
.data(json.nodes)
.enter().append("g")
.attr("class", "node")
.call(force.drag);
node.append("a")
.attr("xlink:href", function(d) { return ["/", server_name, "/", d.name].join(""); })
.append("text")
.attr("dx", 12)
.attr("dy", ".35em")
.text(function(d) { return d.name });
node.append("a")
.attr("xlink:href", function(d) { return ["/", server_name, "/", d.name].join(""); })
.append("circle")
.attr("r", 4);
force.on("tick", function() {
link.attr("x1", function(d) { return d.source.x; })
.attr("y1", function(d) { return d.source.y; })
.attr("x2", function(d) { return d.target.x; })
.attr("y2", function(d) { return d.target.y; });
node.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; });
});
}
| JavaScript | 0.000002 | @@ -255,36 +255,8 @@
);%0A%0A
- var g = svg.append(%22g%22);%0A%0A
va
@@ -897,24 +897,54 @@
, height);%0A%0A
+ var g = svg.append(%22g%22);%0A%0A
svg.%0A
|
bd1fabd7ada89ffe8b0313024726a08db5612ed3 | update trello-integration | scripts/trello-api.js | scripts/trello-api.js | 'use strict'
var trello = require("node-trello");
var q = require('q');
// auth
var key = process.env.HUBOT_TRELLO_KEY;
var token = process.env.HUBOT_TRELLO_TOKEN;
var t = new trello(key, token);
module.exports ={
/*******************************************************************/
/* BOARDS */
/*******************************************************************/
getBoard: function(id, pars, callback){
var deferred = q.defer();
t.get("/1/board/"+id, pars, function(err, data){
if (err) {
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* MEMBERS */
/*******************************************************************/
getMembers: function(id, pars, callback){
var deferred = q.defer();
t.get("/1/members/"+id, function(err, data) {
if (err) {
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* LISTS */
/*******************************************************************/
getList: function(id, pars, callback){
var deferred = q.defer();
t.get("1/lists/"+id, pars, function(err, data){
if (err){
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* TESTING PURPOSES */
/*******************************************************************/
test: function(){
var k;
k = t.get("1/board/BE7seI7e",'', cb);
function cb(err, data){
if (err){
return err;
};
console.log(`cb: ${data}`);
return data;
}
console.log(`k - test: ${k}`);
return k;
}
}
| JavaScript | 0 | @@ -2069,16 +2069,20 @@
I7e%22,'',
+ k =
cb);%0A%0A%09
|
8a65fea36f4786f67d75e83745e36589e382cea8 | Fix auto scroll for tall messages | static/application.js | static/application.js | angular.module('grooveboat', ["LocalStorageModule"])
.config(["$routeProvider", "$locationProvider", function($routeProvider, $locationProvider) {
$routeProvider
.when("/", { controller: RoomListCtrl, templateUrl: "static/templates/room_list.html"})
.when("/room/:room", { controller: RoomCtrl, templateUrl: "static/templates/room.html"})
.otherwise({redirect_to: "/"});
$locationProvider.html5Mode(false).hashPrefix("!");
}])
.factory("groove", ["localStorageService", function(localStorageService) {
var groove = new Groove();
var name = localStorageService.get("user:name");
if (!name) {
name = "Guest " + Math.floor(Math.random()*101);
localStorageService.set("user:name", name);
}
groove.me.name = name;
return groove;
}])
.directive('autoScroll', function() {
return function(scope, elements, attrs) {
scope.$watch("(" + attrs.autoScroll + ").length", function() {
var el = elements[0];
var lastElHeight = el.lastElementChild.offsetHeight;
var isScrolledToBottom = (el.scrollHeight - el.scrollTop -
el.clientHeight - lastElHeight) < lastElHeight;
if (isScrolledToBottom) {
el.scrollTop = el.scrollHeight;
}
});
}
});
function RoomListCtrl($scope, $location, groove, localStorageService) {
var selected = -1;
$scope.currentUser = groove.me;
$scope.rooms = [
{ name: "Ambient Electronic", selected: false },
{ name: "Indie While You Slack", selected: false }
];
$scope.clickRoom = function(i) {
if(selected > -1) {
$scope.rooms[selected].selected = false;
}
document.getElementById("join-room").disabled = false;
$scope.rooms[i].selected = true;
selected = i;
}
$scope.clickJoinRoom = function() {
var room = $scope.rooms[selected];
var name = room.name.replace(/\s/g, "-");
localStorageService.set("user:name", groove.me.name);
$location.path("/room/" + name);
}
}
function RoomCtrl($scope, $routeParams, groove, localStorageService) {
groove.joinRoom($routeParams.room);
$scope.users = [];
$scope.djs = [];
$scope.current_track = {
title: "True Affection",
artist: "The Blow"
}
$scope.chat_messages = [];
$scope.currentUser = groove.me;
$scope.users.push(groove.me);
$scope.isDJ = function(user) {
return (user.dj == true);
}
$scope.isAudience = function(user) {
return (user.dj != true);
}
$scope.becomeDJ = function() {
groove.becomeDJ();
}
function watchUser(user) {
user.on("name", function(new_name) {
$scope.$digest();
});
}
$scope.newMessage = function() {
var text = $scope.message_text;
if (text && text.trim()) {
$scope.chat_messages.push({
from: groove.me,
text: text
});
groove.sendChat(text);
}
$scope.message_text = "";
};
$scope.$on("$destroy", function() {
groove.leaveRoom();
});
groove.on("chat", function(message) {
$scope.$apply(function($scope) {
$scope.chat_messages.push(message);
});
});
groove.on("djs", function(djs) {
$scope.$apply(function($scope) {
$scope.djs = djs;
});
});
groove.on("peerConnected", function(user) {
$scope.$apply(function($scope) {
$scope.users.push(user);
watchUser(user);
});
});
groove.on("peerDisconnected", function(user) {
$scope.$apply(function($scope) {
var i = $scope.users.indexOf(user);
if(i == -1) {
return;
}
$scope.users.splice(i, 1);
});
});
}
RoomListCtrl.$inject = ["$scope", "$location", "groove", "localStorageService"];
RoomCtrl.$inject = ["$scope", "$routeParams", "groove", "localStorageService"];
| JavaScript | 0 | @@ -953,24 +953,160 @@
s, attrs) %7B%0A
+ var el = elements%5B0%5D;%0A function scrollToBottom() %7B%0A el.scrollTop = el.scrollHeight;%0A %7D%0A
@@ -1172,46 +1172,8 @@
) %7B%0A
- var el = elements%5B0%5D;%0A
@@ -1438,35 +1438,32 @@
-el.
scrollTo
p = el.scrol
@@ -1450,35 +1450,76 @@
scrollTo
-p = el.scrollHeight
+Bottom();%0A setTimeout(scrollToBottom, 10)
;%0A
|
b13b03371049c3e85f46af4499b217af9d1ce629 | update trello-integration | scripts/trello-api.js | scripts/trello-api.js | 'use strict'
var trello = require("node-trello");
var q = require('q');
// auth
var key = process.env.HUBOT_TRELLO_KEY;
var token = process.env.HUBOT_TRELLO_TOKEN;
var t = new trello(key, token);
module.exports ={
/*******************************************************************/
/* BOARDS */
/*******************************************************************/
getBoard: function(id, pars, callback){
var deferred = q.defer();
t.get("/1/board/"+id, pars, function(err, data){
if (err) {
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* MEMBERS */
/*******************************************************************/
getMembers: function(id, pars, callback){
var deferred = q.defer();
t.get("/1/members/"+id, function(err, data) {
if (err) {
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* LISTS */
/*******************************************************************/
getList: function(id, pars, callback){
var deferred = q.defer();
t.get("1/lists/"+id, pars, function(err, data){
if (err){
deferred.reject(err);
};
deferred.resolve(data);
});
deferred.promise.nodeify(callback);
return deferred.promise;
},
/*******************************************************************/
/* TESTING PURPOSES */
/*******************************************************************/
test: function(){
var k;
t.get("1/board/BE7seI7e",'', function(err, data){
if (err){
k = err;
};
console.log(`cb: ${data}`);
k = data;
})
console.log(`k - test: ${k}`);
return k;
}
}
| JavaScript | 0 | @@ -2066,16 +2066,30 @@
7e%22,'',
+cb); %0A%0A%0A%09%09cb =
function
@@ -2171,23 +2171,29 @@
%0A%09%09%09
-%09k =
+return cb(
data
-;
+);%09
%0A%09%09%7D
-)
%0A%09%09c
|
ec7cdce40accb8132a74eca73add009d89960d1e | Refactor worker API | core/worker/index.js | core/worker/index.js | 'use strict'
const checkRequiredParams = require('../util/check-required-params')
const createProcessExit = require('../util/process-exit')
const providers = require('../providers')
const createLogger = require('../log')
const { waterfall } = require('async')
const { partial } = require('lodash')
const isUp = require('../util/is-up')
const db = require('../db')
const CONST = {
CHECK_HOSTS: require('config').check_hosts,
REQUIRED_PARAMS: [ 'provider' ]
}
function createWorker (opts) {
checkRequiredParams(opts, CONST.REQUIRED_PARAMS)
const { provider, type, category } = opts
const loggerKeyword = opts.loggerKeyword = `${provider}_${type}_${category}`
const hosts = CONST.CHECK_HOSTS[provider]
const log = createLogger({
keyword: loggerKeyword,
diff: true
})
const processExit = createProcessExit(log)
const worker = providers[provider]({category, type, loggerKeyword})
waterfall([
partial(isUp, hosts),
function clean (next) {
log.info('hosts reachability ✔ (1/3)')
const filters = `provider:${provider} AND type:${type} AND category:${category}`
return db.deleteByQuery('', {filters}, next)
},
function insert (next) {
log.info('cleaned old instances ✔ (2/3)')
return worker(next)
}
], function (err, stats) {
if (err) return processExit(err)
log.debug('stats', stats)
log.info('inserted new instances ✔ (3/3)')
return processExit()
})
}
module.exports = createWorker
| JavaScript | 0.000001 | @@ -452,16 +452,24 @@
rovider'
+, 'type'
%5D%0A%7D%0A%0Afu
@@ -485,197 +485,487 @@
eate
-Worker (opts) %7B%0A checkRequiredParams(opts, CONST.REQUIRED_PARAMS)%0A const %7B provider, type, category %7D = opts%0A const loggerKeyword = opts.loggerKeyword = %60$%7Bprovider%7D_$%7Btype%7D_$%7Bcategory%7D%60
+LoggerKeyword (opts) %7B%0A const %7B provider, type, category %7D = opts%0A let keyword = %60$%7Bprovider%7D_$%7Btype%7D%60%0A if (category) keyword += %60_$%7Bcategory%7D%60%0A return keyword%0A%7D%0A%0Afunction createFilter (opts) %7B%0A const %7B provider, type, category %7D = opts%0A let filter = %60provider:$%7Bprovider%7D AND type:$%7Btype%7D%60%0A if (category) filter += %60 AND category:$%7Bcategory%7D%60%0A return filter%0A%7D%0A%0Afunction createWorker (opts) %7B%0A checkRequiredParams(opts, CONST.REQUIRED_PARAMS)%0A const %7B provider %7D = opts
%0A c
@@ -1018,16 +1018,27 @@
st log =
+ opts.log =
createL
@@ -1058,17 +1058,23 @@
eyword:
-l
+createL
oggerKey
@@ -1077,16 +1077,22 @@
rKeyword
+(opts)
,%0A di
@@ -1191,54 +1191,31 @@
er%5D(
-%7Bcategory, type, loggerKeyword%7D)%0A%0A waterfall(
+opts)%0A%0A const tasks =
%5B%0A
@@ -1337,72 +1337,26 @@
s =
-%60provider:$%7Bprovider%7D AND type:$%7Btype%7D AND category:$%7Bcategory%7D%60
+createFilter(opts)
%0A
@@ -1522,16 +1522,35 @@
%7D%0A %5D
+%0A%0A waterfall(tasks
, functi
|
4d62bdfe368d2531b3e70a9f5cd3c230702f83cf | remove unnecessary _url | src/main/webapp/ui/app/main-view.js | src/main/webapp/ui/app/main-view.js | define(['app/details-view', 'app/dates-view', 'app/slots-view', 'app/managers', 'app/constants', 'app/utils'],
function(DetailsView, DatesView, SlotsView, Managers, Const, Utils) {
function MainView(_url, slotStatesCanvas, datesViewCanvas, detailsViewCanvas) {
var _this = this;
var mutableDims = false;
var uiModel = false;
var selectionManager = new Managers.SelectManager();
var zoomer = new Managers.ZoomManager(this);
var initialCanvasSizeUpdate = false;
var slotsView = new SlotsView(slotStatesCanvas, _this);
var datesView = new DatesView(datesViewCanvas, _this);
var detailsView = new DetailsView(detailsViewCanvas, _this);
var url = _url;
if (url.query.date) {
zoomer.setDate(new Date(url.query.date));
}
this.getUrl = function() {
return url;
};
this.getSelectionManager = function() {
return selectionManager;
};
this.getZoomer = function() {
return zoomer;
};
this.getMutableDims = function() {
return mutableDims;
};
this.setModel = function (_model) {
resetSelectedMarkers(_model);
uiModel = _model;
};
this.getModel = function() {
return uiModel;
};
this.repaintAll = function () {
if (!initialCanvasSizeUpdate) {
datesView.updateCanvasSize();
slotsView.updateCanvasSize();
initialCanvasSizeUpdate = true;
}
updateMutableDimensions();
detailsView.repaint();
datesView.repaint();
slotsView.repaint();
if (_this.getModel().showDate) {
_this.getUrl().query.date = Utils.toCelosUTCString(_this.getModel().showDate);
} else {
delete _this.getUrl().query.date;
}
window.history.replaceState(null, null, _this.getUrl().toString());
};
this.getWidthInCells = function () {
var panelWidth = slotStatesCanvas.stage.width() - _this.getMutableDims().cellDataOffset;
return Math.floor(panelWidth / Const.baseCellWidth);
};
this.getMetricsByDate = function(date) {
var currentDate = _this.getZoomer().getCurrentViewDate();
var millisInPixel = zoomer.getCurrentZoom().baseCellDuration / Const.baseCellWidth;
var relativeX = (currentDate.getTime() - date.getTime()) / millisInPixel;
var absoluteX = relativeX + mutableDims.cellDataOffset;
var leftCut = Math.abs(Math.min(relativeX, 0));
return {
millisInPixel: millisInPixel,
relativeX: relativeX,
absoluteX: absoluteX,
leftCut: leftCut
}
};
this.onResize = function () {
datesView.onResize();
slotsView.onResize();
};
function updateMutableDimensions() {
var maxWidth = Utils.getTextWidth(Const.SAMPLE_DATE, Const.dateTextFontSize);
for (var i = 0; i < uiModel.uiConfig.workflowToSlotMap.length; i++) {
var wfGroup = uiModel.uiConfig.workflowToSlotMap[i];
maxWidth = Math.max(maxWidth, Utils.getTextWidth(wfGroup.name, Const.workflowGroupNameFontSize));
for (var j = 0; j < wfGroup.workflows.length; j++) {
maxWidth = Math.max(maxWidth, Utils.getTextWidth(wfGroup.workflows[j], Const.workflowNameFontSize));
}
}
mutableDims = {
workflowNameWidth: maxWidth,
cellDataOffset: maxWidth + 2 * Const.workflowNameMargin
}
}
function resetSelectedMarkers(_model) {
function collectSelection(slotState) {
if (selectionManager.containsSlot(slotState)) {
slotState.selected = true;
selectionManager.addSlot(slotState);
}
}
_model.workflowToSlotMap.forEach(function (val, key) {
val.forEach(collectSelection);
});
}
this.triggerUpdate = function () {
$(document).trigger("rrman:request_data", _this.getZoomer().getPagingOffsetDate());
};
this.setupEventListeners = function () {
function showCellDetails(slotState) {
$('#bottomPanel').text(slotState.getDescription());
}
function clearCellDetails() {
$('#bottomPanel').text('');
}
slotStatesCanvas.stage.on('mouseover mousemove dragmove', function (evt) {
if (evt.target && evt.target.slotState) {
showCellDetails(evt.target.slotState);
} else {
clearCellDetails();
}
});
slotStatesCanvas.stage.on('mouseout', function (evt) {
if (evt.target && evt.target.slotState) {
clearCellDetails();
}
});
slotStatesCanvas.stage.on('click', function (evt) {
if (!evt.target || !evt.target.slotState) {
return;
}
var slotState = evt.target.slotState;
slotState.selected = !slotState.selected;
if (slotState.selected) {
_this.getSelectionManager().addSlot(slotState);
} else {
_this.getSelectionManager().removeSlot(slotState);
}
slotState.repaint();
detailsView.repaint();
});
document.getElementById("zoomIn").addEventListener("click", _this.getZoomer().zoomIn);
document.getElementById("zoomOut").addEventListener("click", _this.getZoomer().zoomOut);
document.getElementById("nextPage").addEventListener("click", function() {
_this.getZoomer().setDateNextPage();
_this.triggerUpdate();
});
document.getElementById("prevPage").addEventListener("click", function() {
_this.getZoomer().setDatePrevPage();
_this.triggerUpdate();
});
document.getElementById("gotoDate").addEventListener("click", function () {
var newDate = Utils.addMs(new Date(document.getElementById("datepicker").value), Const.DAY_MS);
_this.getZoomer().setDate(newDate);
_this.triggerUpdate();
});
document.getElementById("rerunSelected").addEventListener("click", function () {
var iter = _this.getSelectionManager().slotsIterator();
var next = iter.next();
while (!next.done) {
var slot = next.value;
if (slot.canBeRestarted()) {
$(document).trigger("rrman:slot_rerun", slot);
}
slot.selected = false;
slot.repaint();
_this.getSelectionManager().removeSlot(slot);
next = iter.next();
}
detailsView.repaint();
});
};
}
return MainView;
});
| JavaScript | 0.000014 | @@ -201,17 +201,16 @@
ainView(
-_
url, slo
@@ -714,33 +714,8 @@
);%0A%0A
- var url = _url;%0A%0A
|
236af130fe8549e5162379f09fc9622c73256df2 | fix API documentation for applyOperators | lib/adapter/index.js | lib/adapter/index.js | 'use strict'
var defineEnumerable = require('../common/define_enumerable')
/**
* Adapter is an abstract base class containing methods to be implemented. All
* records returned by the adapter must have the primary key `id`. The primary
* key **MUST** be a string or a number.
*/
function Adapter (properties) {
defineEnumerable(this, properties)
}
/**
* The Adapter should not be instantiated directly, since the constructor
* function accepts dependencies. The keys which are injected are:
*
* - `methods`: same as static property on Fortune class.
* - `errors`: same as static property on Fortune class.
* - `keys`: an object which enumerates reserved constants for record type
* definitions.
* - `recordTypes`: an object which enumerates record types and their
* definitions.
* - `options`: the options passed to the adapter.
* - `message`: a function with the signature (`id`, `language`, `data`).
* - `Promise`: the Promise implementation.
*
* These keys are accessible on the instance (`this`).
*/
Adapter.prototype.constructor = function () {
// This exists here only for documentation purposes.
}
delete Adapter.prototype.constructor
/**
* The responsibility of this method is to ensure that the record types
* defined are consistent with the backing data store. If there is any
* mismatch it should either try to reconcile differences or fail.
* This method **SHOULD NOT** be called manually, and it should not accept
* any parameters. This is the time to do setup tasks like create tables,
* ensure indexes, etc. On successful completion, it should resolve to no
* value.
*
* @return {Promise}
*/
Adapter.prototype.connect = function () {
return Promise.resolve()
}
/**
* Close the database connection.
*
* @return {Promise}
*/
Adapter.prototype.disconnect = function () {
return Promise.resolve()
}
/**
* Create records. A successful response resolves to the newly created
* records.
*
* **IMPORTANT**: the record must have initial values for each field defined
* in the record type. For non-array fields, it should be `null`, and for
* array fields it should be `[]` (empty array). Note that not all fields in
* the record type may be enumerable, such as denormalized inverse fields, so
* it may be necessary to iterate over fields using
* `Object.getOwnPropertyNames`.
*
* @param {String} type
* @param {Object[]} records
* @param {Object} [meta]
* @return {Promise}
*/
Adapter.prototype.create = function () {
return Promise.resolve([])
}
/**
* Find records by IDs and options. If IDs is undefined, it should try to
* return all records. However, if IDs is an empty array, it should be a
* no-op. The format of the options may be as follows:
*
* ```js
* {
* sort: { ... },
* fields: { ... },
* match: { ... },
*
* // Limit results to this number. Zero means no limit.
* limit: 0,
*
* // Offset results by this much from the beginning.
* offset: 0
* }
* ```
*
* The syntax of the `sort` object is as follows:
*
* ```js
* {
* age: false, // descending
* name: true // ascending
* }
* ```
*
* Fields can be specified to be either included or omitted, but not both.
* Use the values `true` to include, or `false` to omit. The syntax of the
* `fields` object is as follows:
*
* ```js
* {
* name: true, // include this field
* age: true // also include this field
* }
* ```
*
* The syntax of the `match` object is straightforward:
*
* ```js
* {
* name: 'value', // exact match or containment if array
* friends: [ 'joe', 'bob' ] // match any one of these values
* }
* ```
*
* The return value of the promise should be an array, and the array **MUST**
* have a `count` property that is the total number of records without limit
* and offset.
*
* @param {String} type
* @param {String[]|Number[]} [ids]
* @param {Object} [options]
* @param {Object} [meta]
* @return {Promise}
*/
Adapter.prototype.find = function () {
var results = []
results.count = 0
return Promise.resolve(results)
}
/**
* Update records by IDs. Success should resolve to the number of records
* updated. The `updates` parameter should be an array of objects that
* correspond to updates by IDs. Each update object must be as follows:
*
* ```js
* {
* // ID to update. Required.
* id: 1,
*
* // Replace a value of a field. Use a `null` value to unset a field.
* replace: { name: 'Bob' },
*
* // Append values to an array field. If the value is an array, all of
* // the values should be pushed.
* push: { pets: 1 },
*
* // Remove values from an array field. If the value is an array, all of
* // the values should be removed.
* pull: { friends: [ 2, 3 ] },
*
* // The `operate` object is specific to the adapter. This should take
* // precedence over all of the above. Warning: using this may bypass
* // field definitions and referential integrity. Use at your own risk.
* operate: { ... }
* }
* ```
*
* Things to consider:
*
* - `push` and `pull` can not be applied to non-arrays.
* - The same value in the same field should not exist in both `push` and
* `pull`.
*
* @param {String} type
* @param {Object[]} updates
* @param {Object} [meta]
* @return {Promise}
*/
Adapter.prototype.update = function () {
return Promise.resolve(0)
}
/**
* Delete records by IDs, or delete the entire collection if IDs are
* undefined or empty. Success should resolve to the number of records
* deleted.
*
* @param {String} type
* @param {String[]|Number[]} [ids]
* @param {Object} [meta]
* @return {Promise}
*/
Adapter.prototype.delete = function () {
return Promise.resolve(0)
}
/**
* Begin a transaction to write to the data store. This method is optional
* to implement, but useful for ACID. It should resolve to an object
* containing all of the adapter methods.
*
* @return {Promise}
*/
Adapter.prototype.beginTransaction = function () {
return Promise.resolve(this)
}
/**
* End a transaction. This method is optional to implement.
* It should return a Promise with no value if the transaction is
* completed successfully, or reject the promise if it failed.
*
* @param {Error} [error] - If an error is passed, roll back the transaction.
* @return {Promise}
*/
Adapter.prototype.endTransaction = function () {
return Promise.resolve()
}
/**
* Apply operators on a record, then return the record. If you make use of
* update operators, you should implement this method so that input transform
* functions get records in the correct state. This method is optional to
* implement.
*
* @param {Object} record
* @param {Object} operators - The `operate` field on an `update` object.
* @return {Object}
*/
Adapter.prototype.applyOperators = function (record) {
return record
}
module.exports = Adapter
| JavaScript | 0 | @@ -6507,35 +6507,56 @@
hat
-input transform%0A * function
+the internal%0A * implementation of update request
s ge
@@ -6587,24 +6587,27 @@
state. This
+%0A *
method is o
@@ -6616,19 +6616,16 @@
ional to
-%0A *
impleme
|
f885aae842e9621a3499daf90f2be725ec1a90d0 | fix auto focus on multiple lines on input boxes | static/js/input-ux.js | static/js/input-ux.js | $(document).ready(function() {
var inputs = $('form.guess .box input')
var button = $('form.guess button')
var timer = null
var beingPressed = false
inputs[0].focus()
$(window).keydown(function(event) {
if (event.metaKey || event.ctrlKey) {
return
}
if (event.target.tagName == 'BUTTON' && event.key == 'Backspace') {
inputs.last().focus()
} else if (
event.target.tagName != 'INPUT' &&
event.target.tagName != 'BUTTON'
) {
inputs.first().focus()
}
})
inputs.keydown(function(event) {
if (event.metaKey || event.ctrlKey) {
return
}
if (timer) {
clearTimeout(timer)
timer = null
}
values = []
inputs.each(function(i, input){
values.push($(input).val());
});
var input = $(this)
if (values.indexOf(event.key) > -1) {
event.preventDefault()
input.val(event.key)
timer = setTimeout(function() {
input.val('')
}, 100)
} else if (inputSet.indexOf(event.key) > -1) {
if (input.val().length) {
input.val('')
} else {
event.preventDefault()
}
input.val(event.key)
if (!!input.parent().next().find('input').length) {
input.parent().next().find('input').focus()
} else {
button.focus()
}
} else if (event.key.length == 1) {
event.preventDefault()
input.val(event.key)
timer = setTimeout(function() {
input.val('')
}, 100)
} else if (event.key == 'Backspace' && input.val().length == 0) {
if (!!input.parent().prev().find('input').length) {
event.preventDefault()
input.parent().prev().find('input').focus()
}
} else if (event.key == 'Backspace' && input.val().length == 0) {
if (!!input.parent().prev().find('input').length) {
event.preventDefault()
input.parent().prev().find('input').focus()
}
}
})
inputs.keyup(function(event) {
if (event.metaKey || event.ctrlKey) {
return
}
event.preventDefault()
})
button.focus(function() {
button.removeClass('primary')
button.addClass('orange')
})
button.blur(function() {
button.removeClass('orange')
button.addClass('primary')
})
})
| JavaScript | 0 | @@ -1264,24 +1264,168 @@
t').focus()%0A
+ %7D else if (!!input.parent().parent().next().is('.boxes')) %7B%0A input.parent().parent().next().find('.box:first-child input').focus()%0A
%7D else
@@ -1838,38 +1838,32 @@
.focus()%0A %7D
-%0A %7D
else if (event.
@@ -1860,117 +1860,53 @@
if (
-event.key == 'Backspace' && input.val().length == 0) %7B%0A if (!!input.parent().prev().find('input').length
+!!input.parent().parent().prev().is('.boxes')
) %7B%0A
@@ -1951,32 +1951,41 @@
input.parent().
+parent().
prev().find('inp
@@ -1973,32 +1973,48 @@
().prev().find('
+.box:last-child
input').focus()%0A
|
d2949aa9a75c7a5c6b613193926da5ed04212eaa | FIx prepare scritp | lib/after-prepare.js | lib/after-prepare.js | var fs = require('fs-extra');
var path = require('path');
var parser = require('xmldom').DOMParser;
var xcode = require('xcode');
var plist = require('simple-plist');
module.exports = function ($logger, $projectData, hookArgs) {
var platform = hookArgs.platform.toLowerCase(),
fabricJSON = path.join($projectData.projectDir, 'fabric.json');
return new Promise(function (resolve, reject) {
if (fs.existsSync(fabricJSON)) {
var fabricData = require(fabricJSON),
apiKey = fabricData.apiKey,
apiSecret = fabricData.apiSecret;
if (platform === 'android') {
var fabricProperties = path.join($projectData.projectDir, 'platforms', 'android', 'src', 'main', 'res', 'fabric.properties'),
fabricPropertiesData = '# Contains API Secret used to validate your application. Commit to internal source control; avoid making secret public.';
fabricPropertiesData += '\napiKey = ' + apiKey;
fabricPropertiesData += '\napiSecret = ' + apiSecret;
fs.ensureFile(fabricProperties, function (err) {
if (!err) {
fs.writeFile(fabricProperties, fabricPropertiesData);
$logger.trace('Written fabric.properties');
resolve();
} else {
console.error(err);
reject();
}
});
} else if (platform == 'ios') {
var appName = path.basename($projectData.projectDir);
var sanitizedName = appName.split('').filter(function (c) { return /[a-zA-Z0-9]/.test(c); }).join('');
var projectPath = path.join($projectData.projectDir, 'platforms', 'ios', sanitizedName + '.xcodeproj', 'project.pbxproj');
var plistPath = path.join($projectData.projectDir, 'platforms', 'ios', sanitizedName, sanitizedName + '-Info.plist');
$logger.trace('Using Xcode project', projectPath);
$logger.trace('Using Info plist', plistPath);
console.log(xcode)
var xcodeProject = xcode.project(projectPath);
xcodeProject.parseSync();
var options = { shellPath: '${PODS_ROOT}/Fabric/run', shellScript: apiKey + ' ' + apiSecret };
var buildPhase = xcodeProject.addBuildPhase([], 'PBXShellScriptBuildPhase', 'Configure Fabric', xcodeProject.getFirstTarget().uuid, options).buildPhase;
$logger.trace('Written Xcode project');
fs.writeFileSync(projectPath, xcodeProject.writeSync());
var appPlist = plist.readFileSync(plistPath);
plist.Fabric = {
APIKey: apiKey,
Kits: [
{
KitInfo: '',
KiteName: 'Crashlytics'
}, {
KitInfo: '',
KiteName: 'Answers'
}
]
}
plist.writeFileSync(plistPath, appPlist);
$logger.trace('Written Info plist');
} else if (platform == 'windows') {
//TODO PRs gladly accepted :P
reject();
}
} else {
$logger.error('Please create a fabric.json file in the root!');
reject();
}
});
};
| JavaScript | 0.000001 | @@ -2135,43 +2135,8 @@
h);%0A
- console.log(xcode)%0A
@@ -3210,32 +3210,59 @@
n Info plist');%0A
+ resolve();%0A
%7D el
|
6c27bf839bd6390e07e24813289e998ea9ff66b1 | Add var | static/js/panoptes.js | static/js/panoptes.js | var ws;
function WebSocketTest(server) {
var ws;
if ("WebSocket" in window) {
ws = new WebSocket("ws://" + server + "/ws/");
ws.onopen = function() {
ws.send('get_status');
};
ws.onmessage = function (evt) {
var type = evt.data.split(' ', 1)[0];
var received_msg = evt.data.substring(evt.data.indexOf(' ') + 1)
var msg = jQuery.parseJSON(received_msg);
switch(type.toUpperCase()){
case 'STATE':
change_state(msg['state']);
break;
case 'SYSTEM':
update_info(msg['system']);
break;
case 'STATUS':
change_state(msg['state']);
system = msg['observatory']['system'];
// Fix times
system['local_evening_astro_time'] = trim_time(system['local_morning_evening_time']);
system['local_morning_astro_time'] = trim_time(system['local_morning_astro_time']);
system['local_sun_set_time'] = trim_time(system['local_sun_set_time']);
system['local_sun_set_time'] = trim_time(system['local_sun_set_time']);
system['local_sun_rise_time'] = trim_time(system['local_sun_rise_time']);
update_info(system);
refresh_images();
break;
case 'ENVIRONMENT':
update_environment(msg['data']);
break;
case 'WEATHER':
update_info(msg['data']);
update_weather(msg['data']);
break;
case 'CAMERA':
update_cameras(msg);
break;
case 'SAYBOT':
case 'PANSHELL':
add_chat_item(type, msg.message, msg.timestamp);
break;
default:
break;
}
};
ws.onclose = function() {
toggle_status('off');
};
} else {
toggle_status('error');
}
return ws;
}
function trim_time(t){
return t.split(':').slice(0,-1).join(':');
}
function add_chat_item(name, msg, time){
item = '<div class="callout padded light-gray">';
item = item + ' <img src="/static/img/pan.png" alt="user image" class="avatar">';
item = item + ' <small class="float-right"><i class="fa fa-clock-o"></i> ' + time +' UTC</small>';
item = item + ' <p class="message">';
item = item + ' <a href="#" class="name">';
item = item + name;
item = item + ' </a>';
item = item + msg;
item = item + ' </p>';
item = item + '</div>';
$('#bot_chat').prepend(item);
}
function toggle_connection_icon(icon){
console.log('Should toggle status here');
// $(icon).toggleClass('success').toggleClass('danger');
// $(icon).toggleClass('fa-check-circle-o').toggleClass('fa-exclamation-triangle');
}
function update_environment(info){
var computer_info = info['computer_box'];
var camera_info = info['camera_box'];
$('.computer_box_humidity_00').html(computer_info['humidity']);
$('.camera_box_humidity_00').html(camera_info['humidity']);
$('.camera_box_temp_00').html(camera_info['temp_00']);
$('.computer_box_temp_00').html(computer_info['temp_00']);
$('.computer_box_temp_01').html(computer_info['temp_01']);
$('.computer_box_temp_02').html(computer_info['temp_02']);
$('.computer_box_temp_03').html(computer_info['temp_03']);
}
function update_weather(is_safe){
if(is_safe){
$('.safe_condition').html('Safe');
$('.title-bar').removeClass('danger');
$('.callout').removeClass('unsafe_borders').addClass('safe_borders');
} else {
$('.safe_condition').html('Unsafe');
$('.title-bar').addClass('danger');
$('.callout').addClass('unsafe_borders').removeClass('safe_borders');
}
}
function toggle_status(status){
var icon = $('.current_state i');
var text = $('.current_state span');
icon.removeClass().addClass('fa');
if (status == 'on'){
icon.addClass('fa-circle').addClass('success');
text.html('Online');
} else if (status == 'off'){
icon.addClass('fa-bolt').addClass('danger');
text.html('Offline').addClass('danger');
} else {
icon.addClass('fa-exclamation-triangle', 'danger').addClass('danger');
text.html('Error').addClass('danger');
}
}
function change_state(state){
var icon = $('.current_state i');
var text = $('.current_state span');
icon.removeClass().addClass('fa').addClass('success');
text.html(state.toUpperCase());
switch(state) {
case 'analyzing':
icon.addClass('fa-calculator');
break;
case 'tracking':
icon.addClass('fa-binoculars');
break;
case 'observing':
icon.addClass('fa-camera');
break;
case 'pointing':
icon.addClass('fa-bullseye');
break;
case 'slewing':
icon.addClass('fa-cog fa-spin');
break;
case 'scheduling':
icon.addClass('fa-tasks');
break;
case 'ready':
icon.addClass('fa-thumbs-o-up');
break;
case 'parking':
case 'parked':
icon.addClass('fa-car');
break;
case 'sleeping':
icon.addClass('fa-check-circle');
break;
default:
icon.addClass('fa-circle');
}
reload_img($('.state_img img'));
}
// Find all the elements with the class that matches a return value
// and update their html
function update_info(status){
$.each(status, function(key, val){
$('.' + key).each(function(idx, elem){
$(elem).html(val);
})
});
}
function update_cameras(cameras){
$.each(cameras, function(cam_name, props){
$.each(props, function(prop, val){
$('#' + cam_name + ' .' + prop).each(function(idx, elem){
$(elem).html(val);
});
if (prop == 'exptime'){
// Start the progress bar
var pb = $('#' + cam_name + ' .progress-bar');
pb.width('100%');
var exptime = $('#' + cam_name + ' .exptime');
exptime.html(val);
var total_time = val;
var count_time = val;
var exp_count = $('#' + cam_name + ' .exp_count');
// exp_count.timer('remove');
exp_count.timer({
duration: '2s',
callback: function(){
count_time = count_time - 2;
var perc = (count_time/total_time) * 100;
console.log(perc);
if (perc < 0){
pb.width('0%');
exp_count.timer('remove');
} else {
pb.width(perc + '%');
}
},
repeat: true,
});
var pb_count = function(cb, count){
var width_perc = (count / val) * 100;
pb.width(width_perc + '%');
setTimeout(cb, 1000, cb, --count);
};
setTimeout(pb_count, 1000, pb_count, val);
}
});
});
}
// Refresh all images with `img_refresh` container class
function refresh_images(){
$.each($('.img_refresh img'), function(idx, img){
reload_img(img);
});
}
// Reload individual image
function reload_img(img){
base = $(img).attr('src').split('?')[0];
// console.log("Reloading image: " + $(img).attr('src'));
// Hack for others
if(base.startsWith('http')){
new_src = $(img).attr('src');
} else {
new_src = base + '?' + Math.random()
}
$(img).attr('src', new_src);
}
| JavaScript | 0.00003 | @@ -783,24 +783,28 @@
+var
system = msg
|
ffcec0c6db11ff8af6deeca35aae6616acecbe66 | Access zaraz via window.zaraz | static/js/scat.web.js | static/js/scat.web.js | "use strict";
class ScatWeb {
// format number as $3.00 or ($3.00)
amount (val) {
if (typeof(val) == 'function') {
val= val()
}
if (typeof(val) == 'undefined' || val == null) {
return ''
}
if (typeof(val) == 'string') {
val= parseFloat(val)
}
if (val < 0.0) {
return '($' + Math.abs(val).toFixed(2) + ')'
} else {
return '$' + val.toFixed(2)
}
}
ecommerce (event, parameters) {
if (zaraz) {
zaraz.ecommerce(event, parameters)
}
if (window.uetq) {
switch (event) {
case 'Product Added':
window.uetq.push('event', 'add_to_cart', {
'ecomm_prodid': parameters.product_id,
'ecomm_pagetype': 'product',
'ecomm_totalvalue': parameters.price * parameters.quantity,
'revenue_value': parameters.price * parameters.quantity,
'currency': parameters.currency,
'items': [
{
'id': parameters.product_id,
'quantity': parameters.quantity,
'price': parameters.price,
},
]
});
break;
case 'Product Viewed':
window.uetq.push('event', '', {
'ecomm_prodid': parameters.product_id,
'ecomm_pagetype': 'product',
});
break;
case 'Order Completed':
window.uetq.push('event', 'purchase', {
'revenue_value' : parameters.total,
'currency' : parameters.currency,
});
break;
case 'Cart Viewed':
case 'Product List Viewed':
case 'Products Searched':
default:
console.log(`No handling for ${event} with Bing, ignoring`)
}
}
if (window.pintrk) {
switch (event) {
case 'Product Added':
window.pintrk('track', 'addtocart', {
'currency': parameters.currency,
'line_items': [
{
'product_id': parameters.product_id,
'product_quantity': parameters.quantity,
'product_price': parameters.price,
},
]
});
break;
case 'Product Viewed':
window.pintrk('track', 'pageview', {
'product_id': parameters.product_id,
});
break;
case 'Order Completed':
let items= parameters.products.map((x) => ({
'product_id' : x.product_id,
'product_quantity' : x.quantity,
'product_price' : x.price,
}));
window.pintrk('track', 'checkout', {
'value' : parameters.total,
'currency' : parameters.currency,
'line_items' : items,
});
break;
case 'Cart Viewed':
case 'Product List Viewed':
case 'Products Searched':
default:
console.log(`No handling for ${event} with Pinterest, ignoring`)
}
}
}
}
let scat= new ScatWeb()
| JavaScript | 0 | @@ -455,16 +455,23 @@
if (
+window.
zaraz) %7B
@@ -477,16 +477,23 @@
%7B%0A
+window.
zaraz.ec
|
c1e4dc5ccc7a40f7acb3a793eb73bc3f64bbbd54 | Rename enter_night_mode to switch_to_dark_theme. | static/js/zcommand.js | static/js/zcommand.js | import $ from "jquery";
import marked from "../third/marked/lib/marked";
import * as channel from "./channel";
import * as common from "./common";
import * as dark_theme from "./dark_theme";
import * as feedback_widget from "./feedback_widget";
import {$t} from "./i18n";
import * as scroll_bar from "./scroll_bar";
/*
What in the heck is a zcommand?
A zcommand is basically a specific type of slash
command where the client does almost no work and
the server just does something pretty simple like
flip a setting.
The first zcommand we wrote is for "/ping", and
the server just responds with a 200 for that.
Not all slash commands use zcommand under the hood.
For more exotic things like /poll see submessage.js
and widgetize.js
*/
export function send(opts) {
const command = opts.command;
const on_success = opts.on_success;
const data = {
command,
};
channel.post({
url: "/json/zcommand",
data,
success(data) {
if (on_success) {
on_success(data);
}
},
error() {
tell_user("server did not respond");
},
});
}
export function tell_user(msg) {
// This is a bit hacky, but we don't have a super easy API now
// for just telling users stuff.
$("#compose-send-status")
.removeClass(common.status_classes)
.addClass("alert-error")
.stop(true)
.fadeTo(0, 1);
$("#compose-error-msg").text(msg);
}
export function enter_day_mode() {
send({
command: "/day",
on_success(data) {
dark_theme.disable();
feedback_widget.show({
populate(container) {
const rendered_msg = marked(data.msg).trim();
container.html(rendered_msg);
},
on_undo() {
send({
command: "/night",
});
},
title_text: $t({defaultMessage: "Light theme"}),
undo_button_text: $t({defaultMessage: "Dark theme"}),
});
},
});
}
export function enter_night_mode() {
send({
command: "/night",
on_success(data) {
dark_theme.enable();
feedback_widget.show({
populate(container) {
const rendered_msg = marked(data.msg).trim();
container.html(rendered_msg);
},
on_undo() {
send({
command: "/day",
});
},
title_text: $t({defaultMessage: "Dark theme"}),
undo_button_text: $t({defaultMessage: "Light theme"}),
});
},
});
}
export function enter_fluid_mode() {
send({
command: "/fluid-width",
on_success(data) {
scroll_bar.set_layout_width();
feedback_widget.show({
populate(container) {
const rendered_msg = marked(data.msg).trim();
container.html(rendered_msg);
},
on_undo() {
send({
command: "/fixed-width",
});
},
title_text: $t({defaultMessage: "Fluid width mode"}),
undo_button_text: $t({defaultMessage: "Fixed width"}),
});
},
});
}
export function enter_fixed_mode() {
send({
command: "/fixed-width",
on_success(data) {
scroll_bar.set_layout_width();
feedback_widget.show({
populate(container) {
const rendered_msg = marked(data.msg).trim();
container.html(rendered_msg);
},
on_undo() {
send({
command: "/fluid-width",
});
},
title_text: $t({defaultMessage: "Fixed width mode"}),
undo_button_text: $t({defaultMessage: "Fluid width"}),
});
},
});
}
export function process(message_content) {
const content = message_content.trim();
if (content === "/ping") {
const start_time = new Date();
send({
command: content,
on_success() {
const end_time = new Date();
let diff = end_time - start_time;
diff = Math.round(diff);
const msg = "ping time: " + diff + "ms";
tell_user(msg);
},
});
return true;
}
const day_commands = ["/day", "/light"];
if (day_commands.includes(content)) {
enter_day_mode();
return true;
}
const night_commands = ["/night", "/dark"];
if (night_commands.includes(content)) {
enter_night_mode();
return true;
}
if (content === "/fluid-width") {
enter_fluid_mode();
return true;
}
if (content === "/fixed-width") {
enter_fixed_mode();
return true;
}
// It is incredibly important here to return false
// if we don't see an actual zcommand, so that compose.js
// knows this is a normal message.
return false;
}
| JavaScript | 0 | @@ -2183,31 +2183,35 @@
unction
-enter_night_mod
+switch_to_dark_them
e() %7B%0A
@@ -4952,23 +4952,27 @@
-enter_night_mod
+switch_to_dark_them
e();
|
44cbf1721056d11e0129d41ff03b348a7d43bda6 | Add ability to set show_tracklabels=0 in config or &tracklabels=0 in url | plugins/HideTrackLabels/js/main.js | plugins/HideTrackLabels/js/main.js | /*
HideTrackLabels JBrowse plugin CSS
*/
/*
Created on : Jul 15, 2015, 7:19:50 PM
Author : EY
*/
define([
'dojo/_base/declare',
'dojo/_base/lang',
'dojo/Deferred',
'dojo/dom-construct',
'dijit/form/Button',
'dojo/fx',
'dojo/dom',
'dojo/dom-style',
'dojo/on',
'dojo/query',
'dojo/dom-geometry',
'JBrowse/Plugin'
],
function(
declare,
lang,
Deferred,
domConstruct,
dijitButton,
coreFx,
dom,
style,
on,
query,
domGeom,
JBrowsePlugin
) {
return declare( JBrowsePlugin,
{
constructor: function( args ) {
console.log("plugin HideTracksButton constructor");
var baseUrl = this._defaultConfig().baseUrl;
var thisB = this;
// create the hide/show button after genome view initialization
this.browser.afterMilestone( 'initView', function() {
var navBox = dojo.byId("navbox");
thisB.browser.hideTitlesButton = new dijitButton(
{
title: "Hide/Show Track Titles",
id: "hidetitles-btn",
width: "24px",
onClick: dojo.hitch( thisB, function(event) {
thisB.browser.showTrackLabels("toggle");
dojo.stopEvent(event);
})
}, dojo.create('button',{},navBox)); //thisB.browser.navBox));
});
/* show or hide track labels
* showTrackLabels(param)
* @param {string} function "show", "hide", "toggle", or "hide-if"
* "hide-if" rehides if already hidden.
* @returns {undefined}
*/
this.browser.showTrackLabels = function(fn) {
// does the hide/show button exists yet?
if (dojo.byId('hidetitles-btn')==null) return;
var direction = 1;
if (fn=="show") {
dojo.removeAttr(dom.byId("hidetitles-btn"),"hidden-titles");
direction = 1;
}
if (fn=="hide") {
dojo.attr(dom.byId("hidetitles-btn"),"hidden-titles","");
direction = -1;
}
if (fn=="hide-if") {
if (dojo.hasAttr(dom.byId("hidetitles-btn"),"hidden-titles")) direction = -1;
else return;
}
if (fn=="toggle"){
if (dojo.hasAttr(dom.byId("hidetitles-btn"),"hidden-titles")) { // if hidden, show
dojo.removeAttr(dom.byId("hidetitles-btn"),"hidden-titles");
direction = 1;
}
else {
dojo.attr(dom.byId("hidetitles-btn"),"hidden-titles",""); // if shown, hide
direction = -1;
}
}
// protect Hide button from clicks durng animation
dojo.attr(dom.byId("hidetitles-btn"),"disabled","");
setTimeout(function(){
dojo.removeAttr(dom.byId("hidetitles-btn"),"disabled");
}, 200);
if(direction==-1) {
setTimeout(function() {
query('.track-label').style('visibility', 'hidden')
}, 200);
} else {
query('.track-label').style('visibility', 'visible')
}
// slide em
query(".track-label").forEach(function(node, index, arr){
var w = domGeom.getMarginBox(node).w;
coreFx.slideTo({
node: node,
duration: 200,
top: domGeom.getMarginBox(node).t.toString(),
left: (domGeom.getMarginBox(node).l + (w*direction) ).toString(),
unit: "px"
}).play();
});
};
// trap the redraw event for handling resize, scroll and zoom events
dojo.subscribe("/jbrowse/v1/n/tracks/redraw", function(data){
// hide track labels if necessary
thisB.browser.showTrackLabels("hide-if");
});
}
});
});
| JavaScript | 0 | @@ -946,16 +946,98 @@
= this;%0A
+ var queryParams = dojo.queryToObject( window.location.search.slice(1) );%0A%0A
%0A
@@ -1667,16 +1667,291 @@
vBox));%0A
+ %0A if(queryParams.tracklabels == 0 %7C%7C thisB.browser.config.show_tracklabels == 0) %7B%0A query('.track-label').style('visibility', 'hidden')%0A dojo.attr(dom.byId(%22hidetitles-btn%22),%22hidden-titles%22,%22%22); // if shown, hide%0A %7D%0A
|
84561efeb8465fbc3297faafa0eb7fbbb6cca4c0 | Update picker.js | resources/js/picker.js | resources/js/picker.js | $(document).on('ajaxComplete ready', function () {
// Initialize inputs
$('input[data-provides="anomaly.field_type.datetime"]:not([data-initialized])').each(function () {
var $this = $(this);
var inputMode = $this.data('input-mode');
var options = {
altInput: true,
allowInput: true,
minuteIncrement: $this.data('step') || 1,
dateFormat: $this.data('datetime-format'),
time_24hr: Boolean($this.data('datetime-format').match(/[GH]/)),
enableTime: inputMode !== 'date',
noCalendar: inputMode === 'time'
};
$this.attr('data-initialized', '').flatpickr(options);
});
});
| JavaScript | 0.000001 | @@ -278,16 +278,58 @@
ons = %7B%0A
+ locale: $this.data('locale'),%0A
|
548f8dc970f76b85d6cef89da5c12d910a950814 | use rtm.connect | lib/bot/connector.js | lib/bot/connector.js | /*
* slack-bot
* https://github.com/usubram/slack-bot
*
* Copyright (c) 2016 Umashankar Subramanian
* Licensed under the MIT license.
*/
'use strict';
const _ = require('lodash');
const http = require('https');
const path = require('path');
const querystring = require('querystring');
const root = '..';
const logger = require(path.join(root, 'utils/logger'));
const Socket = require(path.join(root, 'bot/socket'));
const internals = {
options: {
host: 'slack.com',
path: '/api/rtm.start',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Connection': 'keep-alive',
'agent': 'node-slack'
},
rejectUnauthorized: false
},
postData: {
scope: 'rtm:stream',
'simple_latest': true,
'no_unreads': true
}
};
var Connector = class {
constructor (token, options) {
this.options = options;
this.connected = false;
this.token = token;
this.retryCountStore = {};
this.retry = false;
this.socket = {};
}
connect () {
logger.info('Attempting to connect bot with token ending' +
' with ...', this.token.substring(this.token.length - 5));
let postData = '';
let options = {};
postData = querystring.stringify(_.assign(internals.postData, {
token: this.token
}));
options = _.assign(internals.options, {
'Content-Length': postData.length
});
if (this.options.httpAgent) {
options.agent = this.options.httpAgent;
}
return this.makeRequest(options, postData).then((slackData) => {
return this.setupSocket(slackData);
}).then((socket) => {
this.connected = true;
this.retry = false;
this.retryCountStore = {};
this.socket = socket;
this.options.socketEventEmitter.emit('connect');
}).catch((err) => {
if (err.error === 'invalid_auth') {
return Promise.reject(err);
}
this.retry = false;
this.reconnect();
});
}
reconnect () {
if (this.retry || this.isShutdown) {
this.isShutdown = false;
logger.info('Connection retry in progress...');
return;
}
let tokenLastFourDigit = this.token.substring(this.token.length - 5);
this.retry = true;
if (!this.retryCountStore[tokenLastFourDigit]) {
this.retryCountStore[tokenLastFourDigit] = 1;
}
this.retryCountStore[tokenLastFourDigit] =
this.retryCountStore[tokenLastFourDigit] * 2;
/*
Initial retry is 5 seconds and consecutive
retry is mulitple of number of retries to allow
enough time for network recovery or for something bad.
*/
var timer = 200 * this.retryCountStore[tokenLastFourDigit];
logger.info('No connection, will attempt to retry for bot token ' +
tokenLastFourDigit + ' in ' + timer / 1000 + ' seconds');
setTimeout(() => {
logger.info('Retrying to connect for ' + tokenLastFourDigit);
return this.connect();
}, timer);
}
makeRequest (options, postData) {
return internals.handleRequest(options, postData);
}
setupSocket (slackData) {
return Promise.resolve(new Socket(slackData, {
agent: this.options.socketAgent,
socketEventEmitter: this.options.socketEventEmitter
}));
}
close () {
this.socket.close();
}
shutdown () {
this.isShutdown = true;
this.socket.shutdown();
}
};
internals.handleRequest = function (options, postData) {
return Promise.resolve({
then: (onFulfill, onReject) => {
let req = http.request(options, function (response) {
let responseStr = '';
response.on('data', function (chunk) {
responseStr += chunk;
});
response.on('end', function () {
let slackData = internals.handleResponse(responseStr);
if (slackData.error) {
return onReject(slackData.error);
}
return onFulfill(slackData);
});
}).on('error', function (err) {
logger.info('Unknown error on connecting to slack ', err);
onReject({ 'error': 'unkown_error'});
});
req.write('' + postData);
req.end();
}
});
};
internals.handleResponse = function (responseStr) {
let slackData = {};
try {
slackData = JSON.parse(responseStr);
} catch (err) {
logger.debug('Slack response corrupted ', slackData);
slackData.error = 'invalid_slack_response';
}
if (_.get(slackData, 'error') === 'invalid_auth') {
logger.info('Invalid auth token. Unable to connect');
slackData.error = 'invalid_auth';
} else if (_.get(slackData, 'error')) {
logger.info('Error connecting to slack ', _.get(slackData, 'error'));
slackData.error = 'invalid_connection_string';
} else if (!_.get(slackData, 'url')) {
slackData.error = _.get(slackData, 'error');
logger.info('Something wrong', slackData.error);
}
return slackData;
};
module.exports = Connector;
| JavaScript | 0.000001 | @@ -500,12 +500,14 @@
rtm.
-star
+connec
t',%0A
|
247efe2dfbd2762628415137ac1a2f9023cabbf3 | Add cleaning of tmp into nodejs | boot/kernal/index.js | boot/kernal/index.js | var mkdirp = require('mkdirp');
var clicolour = require("cli-color");
var exec = require('child_process').exec;
exports.createTmp = function createTmp(argument) {
mkdirp("./tmp", function(err){
console.log(clicolour.cyanBright('Created ./tmp...')+clicolour.greenBright("OK"));
})
}
exports.clean = function clean(x) {
console.log('Cleaning out files');
console.log('Cleaned out ./tmp...'+clicolour.greenBright("OK"));
}
| JavaScript | 0.000002 | @@ -327,43 +327,92 @@
%7B%0A
-console.log('Cleaning out files');%0A
+// clean out ./tmp%0A exec(%22rm -rfv ./tmp/*%22, function (error, stdout, stderr) %7B%0A
co
@@ -474,10 +474,16 @@
%22OK%22));%0A
+ %7D);%0A
%7D%0A
|
697c7c96d34729ad19c8db4062d90ad5c190a596 | fix bot not found | bot/commands/game.js | bot/commands/game.js |
/**
* This method should return the response directly to the channel
* @param {*string array} params
* @param {*message} message
*/
const settings = require('./../../settings.json');
async function command(params, message) {
const member = bot.guilds.get("184536578654339072").member(message.author);
if (!member) {
await message.reply("Revive Network Members only");
return false;
}
if (settings["game-roles"][params[0]]) {
if (member.roles.get(settings["game-roles"][params[0]])) {
await message.reply('You already have the role');
return false;
}
await member.addRole(settings["game-roles"][params[0]]);
await message.reply("Added " + settings["game-roles"][params[0]]);
return true;
}
else {
await message.reply("Game not found");
return false;
}
return false;
}
/**
* description of the command
*/
const description = "adds a game related channel to your channel list";
/**
* Define Exports
*/
module.exports = {
execute: command,
description: description,
custom: true
};
| JavaScript | 0 | @@ -182,16 +182,49 @@
json');%0A
+const bot = require('./../bot');%0A
async fu
|
c380eb124c4dd02fc8231278e1f6378ff6aef11f | Use Promise.resolve when normalizing | lib/bundles/index.js | lib/bundles/index.js |
module.exports = function(loader){
var bundles = {"@global": {}};
var parentMap = loader.__ssrParentMap = {};
function setAsBundle(name, parentName){
return loader.normalize(name, parentName).then(function(name) {
if(!bundles[name]) {
bundles[name] = {};
}
});
}
function findBundleName(moduleName) {
var parent = parentMap[moduleName],
bundleName = parent;
while(parent) {
parent = parentMap[parent];
if(parent) {
bundleName = parent;
}
}
return bundleName;
}
function findBundle(moduleName){
var bundleName = findBundleName(moduleName);
return bundles[bundleName];
}
function assetRegister(moduleName, type, makeAsset) {
if(arguments.length === 2) {
makeAsset = type;
moduleName = type = moduleName;
bundle = bundles["@global"];
} else {
bundle = findBundle(moduleName);
}
// If it's not in an existing bundle maybe it's a loader.bundle
if(!bundle) {
var loaderBundle = loader.bundles[moduleName];
if(loaderBundle){
bundle = bundles[moduleName] = {};
loaderBundle.forEach(function(childName){
bundle = findBundle(childName);
if(bundle) {
bundle[childName] = {
id: moduleName,
type: type,
value: makeAsset
};
}
});
}
// If we still haven't found one, set the bundleName as a bundle.
if(!bundle) {
var bundleName = findBundleName(moduleName);
bundle = bundles[bundleName] = {};
}
}
bundle[moduleName] = {
id: moduleName,
type: type,
value: makeAsset
};
}
if(loader.main) {
setAsBundle(loader.main);
}
loader.set("asset-register", loader.newModule({
__useDefault: true,
"default": assetRegister
}));
var loaderImport = loader.import;
loader.import = function(name, options){
var loader = this, args = arguments;
var parentName = options ? options.name : undefined;
return setAsBundle(name, parentName).then(function(){
return loaderImport.apply(loader, args);
});
};
var normalize = loader.normalize;
loader.normalize = function(name, parentName){
var promise = Promise.resolve(normalize.apply(this, arguments));
return promise.then(function(normalizedName){
if(parentName && parentMap[normalizedName] !== false) {
parentMap[normalizedName] = parentName;
}
return normalizedName;
});
};
return {
bundles: bundles,
findBundle: findBundle
};
};
| JavaScript | 0.000002 | @@ -150,23 +150,40 @@
ame)%7B%0A%09%09
-return
+var p = Promise.resolve(
loader.n
@@ -200,32 +200,45 @@
ame, parentName)
+);%0A%09%09return p
.then(function(n
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.