text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Change a port number of harp
'use strict'; let gulp = require('gulp'); let requireDir = require('require-dir'); let gulpLoadPlugin = require('gulp-load-plugins'); let $ = gulpLoadPlugin(); let runSequence = require('run-sequence'); let config = require('./gulp/config'); let exec = require('child_process').exec; requireDir('./gulp/task', {recurse: true}); gulp.task('watch', () => { $.watch(config.style.src, () => { gulp.start(['style', 'lint:style', 'minify:style']); }); $.watch(config.script.src, () => { gulp.start(['script', 'lint:script']); }); }); gulp.task('serve', (cb) => { exec('./node_modules/.bin/harp server test --port 3000', (err, stdout, stderr) => { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('develop', ['watch', 'serve']); gulp.task('default', () => { return runSequence( 'lint', 'style', 'minify', 'watch' ); });
'use strict'; let gulp = require('gulp'); let requireDir = require('require-dir'); let gulpLoadPlugin = require('gulp-load-plugins'); let $ = gulpLoadPlugin(); let runSequence = require('run-sequence'); let config = require('./gulp/config'); let exec = require('child_process').exec; requireDir('./gulp/task', {recurse: true}); gulp.task('watch', () => { $.watch(config.style.src, () => { gulp.start(['style', 'lint:style', 'minify:style']); }); $.watch(config.script.src, () => { gulp.start(['script', 'lint:script']); }); }); gulp.task('serve', (cb) => { exec('./node_modules/.bin/harp server test --port 5000', (err, stdout, stderr) => { console.log(stdout); console.log(stderr); cb(err); }); }); gulp.task('develop', ['watch', 'serve']); gulp.task('default', () => { return runSequence( 'lint', 'style', 'minify', 'watch' ); });
Remove invalid class extension test
'use strict'; module.exports = function () { var set, iterator, result; if (typeof Set !== 'function') return false; if (String(Set.prototype) !== '[object Set]') return false; set = new Set(['raz', 'dwa', 'trzy']); if (set.size !== 3) return false; if (typeof set.add !== 'function') return false; if (typeof set.clear !== 'function') return false; if (typeof set.delete !== 'function') return false; if (typeof set.entries !== 'function') return false; if (typeof set.forEach !== 'function') return false; if (typeof set.has !== 'function') return false; if (typeof set.keys !== 'function') return false; if (typeof set.values !== 'function') return false; iterator = set.values(); result = iterator.next(); if (result.done !== false) return false; if (result.value !== 'raz') return false; if (!set) return false; if (set.size !== 3) return false; return true; };
'use strict'; var d = require('d') , create = Object.create, setPrototypeOf = Object.setPrototypeOf; module.exports = function () { var set, iterator, result, SubSet; if (typeof Set !== 'function') return false; if (String(Set.prototype) !== '[object Set]') return false; set = new Set(['raz', 'dwa', 'trzy']); if (set.size !== 3) return false; if (typeof set.add !== 'function') return false; if (typeof set.clear !== 'function') return false; if (typeof set.delete !== 'function') return false; if (typeof set.entries !== 'function') return false; if (typeof set.forEach !== 'function') return false; if (typeof set.has !== 'function') return false; if (typeof set.keys !== 'function') return false; if (typeof set.values !== 'function') return false; iterator = set.values(); result = iterator.next(); if (result.done !== false) return false; if (result.value !== 'raz') return false; if (!set) return false; if (set.size !== 3) return false; // Extendable if (setPrototypeOf) { SubSet = function () { Set.apply(this, arguments); }; setPrototypeOf(SubSet, Set); SubSet.prototype = create(Set.prototype, { constructor: d(SubSet) }); try { set = new SubSet([1, 2, 3]); } catch (e) { return false; } try { if (set.size !== 3) return false; } catch (e) { return false; } } return true; };
Fix minor typing issue in union find test.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_union_find ---------------------------------- Tests for `python_algorithms.union_find` module. """ import unittest from python_algorithms.basic.union_find import UF class TestUnionFind(unittest.TestCase): def setUp(self): self.N = 10 self.uf = UF(self.N) self.pairs = ((0, 1), (1, 2), (4, 5), (7, 8), (8, 9)) def test_count(self): self.assertEqual(self.uf.count(), self.N) self.assertEqual(self.count_sets(), self.N) for x, y in self.pairs: self.uf.union(x, y) n = self.N - len(self.pairs) self.assertEqual(self.uf.count(), n) self.assertEqual(self.count_sets(), n) def test_str_empty_uf(self): self.assertEqual(str(UF(0)), "") def test_str_uf(self): self.assertEqual(str(self.uf), " ".join([str(x) for x in range(self.N)])) def count_sets(self): return len(set([self.uf.find(x) for x in range(self.N)])) def tearDown(self): pass if __name__ == '__main__': unittest.main()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_union_find ---------------------------------- Tests for `python_algorithms.union_find` module. """ import unittest from python_algorithms.basic.union_find import UF class TestUnionFind(unittest.TestCase): def setUp(self): self.N = 10 self.uf = UF(self.N) self.pairs = ((0, 1), (1, 2), (4, 5), (7, 8), (8, 9)) def test_count(self): self.assertEqual(self.uf.count(), self.N) self.assertEqual(self.count_sets(), self.N) for x, y in self.pairs: self.uf.union(x, y) n = self.N - len(self.pairs) self.assertEqual(self.uf.count(), n) self.assertEqual(self.count_sets(), n) def test_str_empty_uf(self): self.assertEqual(str(UF(0)), "") def test_str_stack(self): self.assertEqual(str(self.uf), " ".join([str(x) for x in range(self.N)])) def count_sets(self): return len(set([self.uf.find(x) for x in range(self.N)])) def tearDown(self): pass if __name__ == '__main__': unittest.main()
Update player season retrieval function
#!/usr/bin/env python # -*- coding: utf-8 -*- import concurrent.futures from db.common import session_scope from db.player import Player from utils.player_data_retriever import PlayerDataRetriever def create_player_seasons(simulation=False): data_retriever = PlayerDataRetriever() with session_scope() as session: players = session.query(Player).all()[:] with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads: future_tasks = { threads.submit( data_retriever.retrieve_player_seasons, player.player_id, simulation ): player for player in players } for future in concurrent.futures.as_completed(future_tasks): try: plr_seasons = future.result() except Exception as e: print("Concurrent task generated an exception: %s" % e)
#!/usr/bin/env python # -*- coding: utf-8 -*- import concurrent.futures from db.common import session_scope from db.player import Player from utils.player_data_retriever import PlayerDataRetriever def create_player_seasons(simulation=False): data_retriever = PlayerDataRetriever() with session_scope() as session: players = session.query(Player).all()[:25] with concurrent.futures.ThreadPoolExecutor(max_workers=8) as threads: future_tasks = { threads.submit( data_retriever.retrieve_player_seasons, player.player_id, simulation ): player for player in players } for future in concurrent.futures.as_completed(future_tasks): try: plr_seasons = future.result() print(len(plr_seasons)) except Exception as e: print("Concurrent task generated an exception: %s" % e)
Set up services to contain logic and inject in date wrapper
'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { templateUrl: 'view1/view1.html', controller: 'View1Ctrl' }); }]) .controller('View1Ctrl', ['$scope', 'timeSlotService', function($scope, timeSlotService) { // inject time object? // test output? Against scope? $scope.timeSlotOptions = [ { label: '06:30am', value: '06:30' }, { label: '07:00am', value: '07:00' } ]; $scope.timeSlotSelected = $scope.timeSlotOptions[0]; }]) .factory('timeSlotService', ['$window', 'currentTimeService', function(win, currentTimeService) { var timeSlotServiceInstance; // factory function body that constructs shinyNewServiceInstance win.console.log(currentTimeService); return timeSlotServiceInstance; }]) .factory('currentTimeService', ['$window', function(win) { return new Date(); // easier way to inject in a date? }]) ;
'use strict'; angular.module('myApp.view1', ['ngRoute']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/view1', { templateUrl: 'view1/view1.html', controller: 'View1Ctrl' }); }]) .controller('View1Ctrl', ['$scope', function(sc) { sc.timeSlotOptions = [ { label: '06:30am', value: '06:30' }, { label: '07:00am', value: '07:00' } ]; sc.timeSlotSelected = sc.timeSlotOptions[0]; //this.slots = ["06:00am", "06:30am", "07:00am"]; // create and initialise function that is called on page load // generate an array of time slots and bind to a model }]); //var slots = ["06:00am", "06:30am", "07:00am"];
Increase delay for loading toolbarbutton so that other components have a chance to load.
var self = require("sdk/self"); var panel = require("sdk/panel"); var initToolbar = function(freedom) { // create toolbarbutton var tbb = require("pathfinder/ui/toolbarbutton").ToolbarButton({ id: "UProxyItem", label: "UProxy", image: self.data.url("common/ui/icons/uproxy-19.png"), panel: initPanel(freedom.communicator) }); tbb.moveTo({ toolbarID: "nav-bar", forceMove: false // only move from palette }); }; var initPanel = function(freedomCommunicator) { var l10n = JSON.parse(self.data.load("l10n/en/messages.json")); var uproxyPanel = panel.Panel({ contentURL: self.data.url("common/ui/popup.html"), width: 450, height: 300 }); freedomCommunicator.addContentContext(uproxyPanel); uproxyPanel.port.on("show", function() { uproxyPanel.port.emit("l10n", l10n); }); return uproxyPanel; }; var freedomEnvironment = require('./init_freedom').InitFreedom(); // TODO: Remove when uproxy.js no longer uses setTimeout // and replace with the line: // initToolbar(freedomEnvironment); require('sdk/timers').setTimeout(initToolbar, 500, freedomEnvironment);
var self = require("sdk/self"); var panel = require("sdk/panel"); var initToolbar = function(freedom) { // create toolbarbutton var tbb = require("pathfinder/ui/toolbarbutton").ToolbarButton({ id: "UProxyItem", label: "UProxy", image: self.data.url("common/ui/icons/uproxy-19.png"), panel: initPanel(freedom.communicator) }); tbb.moveTo({ toolbarID: "nav-bar", forceMove: false // only move from palette }); }; var initPanel = function(freedomCommunicator) { var l10n = JSON.parse(self.data.load("l10n/en/messages.json")); var uproxyPanel = panel.Panel({ contentURL: self.data.url("common/ui/popup.html"), width: 450, height: 300 }); freedomCommunicator.addContentContext(uproxyPanel); uproxyPanel.port.on("show", function() { uproxyPanel.port.emit("l10n", l10n); }); return uproxyPanel; }; var freedomEnvironment = require('./init_freedom').InitFreedom(); // TODO: Remove when uproxy.js no longer uses setTimeout // and replace with the line: // initToolbar(freedomEnvironment); require('sdk/timers').setTimeout(initToolbar, 20, freedomEnvironment);
Add default value for map center
import Ember from 'ember'; import layout from '../templates/components/flexberry-map'; import ContainerMixin from 'ember-flexberry-gis/mixins/layercontainer'; export default Ember.Component.extend(ContainerMixin, { layout, model: undefined, center: Ember.computed('model.lat', 'model.lng', function () { return L.latLng(this.get('model.lat') || 0, this.get('model.lng') || 0); }), zoom: Ember.computed('model.zoom', function() { return this.get('model.zoom'); }), leafletMap: undefined, didInsertElement() { this._super(...arguments); let map = L.map(this.element, this.get('options')); map.setView(this.get('center'), this.get('zoom')); this.set('leafletMap', map); this.buildLayers(map); this.setOrder({ index: 0 }); }, willDestoryElement() { var leafletMap = this.get('leafletMap'); if (leafletMap) { leafletMap.remove(); this.set('leafletMap', null); } } });
import Ember from 'ember'; import layout from '../templates/components/flexberry-map'; import ContainerMixin from 'ember-flexberry-gis/mixins/layercontainer'; export default Ember.Component.extend(ContainerMixin, { layout, model: undefined, center: Ember.computed('model.lat', 'model.lng', function () { return L.latLng(this.get('model.lat'), this.get('model.lng')); }), zoom: Ember.computed('model.zoom', function() { return this.get('model.zoom'); }), leafletMap: undefined, didInsertElement() { this._super(...arguments); let map = L.map(this.element, this.get('options')); map.setView(this.get('center'), this.get('zoom')); this.set('leafletMap', map); this.buildLayers(map); this.setOrder({ index: 0 }); }, willDestoryElement() { var leafletMap = this.get('leafletMap'); if (leafletMap) { leafletMap.remove(); this.set('leafletMap', null); } } });
Modify testing code to work if executed from above its own directory
""" The code this example is all based on is from http://tinyurl.com/pmmnbxv Some notes on this in the oommf-devnotes repo """ import os import pytest # Need to call Makefile in directory where this test file is def call_make(target): # where is this file this_file = os.path.realpath(__file__) this_dir = os.path.split(this_file)[0] cd_command = "cd {}".format(this_dir) make_command = "make {}".format(target) command = '{}; {}'.format(cd_command, make_command) print("About to execute: '{}'".format(command)) os.system(command) call_make('all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 call_make('alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 call_make('clean')
""" The code this example is all based on is from http://tinyurl.com/pmmnbxv Some notes on this in the oommf-devnotes repo """ import os import pytest #print("pwd:") #os.system('pwd') #import subprocess #subprocess.check_output('pwd') os.system('make all') import example1 def test_f(): assert example1.f(1) - 1 <= 10 ** -7 def test_myfun(): """Demonstrate that calling code with wrong object type results in TypeError exception.""" with pytest.raises(TypeError): assert example1.myfun(example1.f, 2.0) - 4.0 <= 10 ** -7 os.system('make alternate') import example2 def test2_f(): assert example2.f(1) - 1 <= 10 ** -7 def test2_myfun(): assert example2.myfun(example2.f, 2.0) - 4.0 <= 10 ** -7 os.system('make clean')
Fix content type bug (415 error from server). - The server doesn't recognize the POST as type application/json, but adding an empty JSON object {} solves that.
'use strict'; angular.module('confRegistrationWebApp') .factory('currentRegistrationInterceptor', function ($q, $injector) { return { 'responseError': function (rejection) { var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/; if (rejection.status === 404 && regExp.test(rejection.config.url)) { var url = rejection.config.url.split('/'); if (_.isEmpty(_.last(url))) { url.pop(); } url.pop(); return $injector.get('$http').post(url.join('/'), {}); } return $q.reject(rejection); } }; });
'use strict'; angular.module('confRegistrationWebApp') .factory('currentRegistrationInterceptor', function ($q, $injector) { return { 'responseError': function (rejection) { var regExp = /conferences\/[-a-zA-Z0-9]+\/registrations\/current\/?$/; if (rejection.status === 404 && regExp.test(rejection.config.url)) { var url = rejection.config.url.split('/'); if (_.isEmpty(_.last(url))) { url.pop(); } url.pop(); return $injector.get('$http').post(url.join('/')); } return $q.reject(rejection); } }; });
Fix built-in server for PHP > 5.4.1
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * This file implements rewrite rules for PHP built-in web server. * * See: http://www.php.net/manual/en/features.commandline.webserver.php * * If you have custom directory layout, then you have to write your own router * and pass it as a value to 'router' option of server:run command. * * @author: Michał Pipa <michal.pipa.xsolve@gmail.com> * @author: Albert Jessurum <ajessu@gmail.com> */ if (is_file($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . $_SERVER['REQUEST_URI'])) { return false; } $_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'app_dev.php'; require 'app_dev.php';
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ /* * This file implements rewrite rules for PHP built-in web server. * * See: http://www.php.net/manual/en/features.commandline.webserver.php * * If you have custom directory layout, then you have to write your own router * and pass it as a value to 'router' option of server:run command. * * @author: Michał Pipa <michal.pipa.xsolve@gmail.com> */ if (isset($_SERVER['SCRIPT_FILENAME'])) { return false; } $_SERVER['SCRIPT_FILENAME'] = $_SERVER['DOCUMENT_ROOT'].DIRECTORY_SEPARATOR.'app_dev.php'; require 'app_dev.php';
Use both keyup and keypress if input unsupported
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keypress keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { $(this).bind(inputEvents, function(e) { $(this).val(sanitizationFunc($(this).val())); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); } })(jQuery);
/* * Every time the form field is changed, sanitize its contents with the given * function to only allow input of a certain form. */ (function ($) { var inputEvents = "input"; if (!("oninput" in document || "oninput" in $("<input>")[0])) { inputEvents += " keyup"; } jQuery.fn.restrict = function(sanitizationFunc) { $(this).bind(inputEvents, function(e) { $(this).val(sanitizationFunc($(this).val())); }); }; /* * Every time the form field is changed, modify its contents by eliminating * matches for the given regular expression within the field. */ jQuery.fn.regexRestrict = function(regex){ var sanitize = function(text) { return text.replace(regex, ''); }; $(this).restrict(sanitize); } })(jQuery);
Add comments and pseudocode to sort function
"use strict"; // Program that sorts a stack such that smallest items are on top // create Stack class function Stack() { this.top = null; } // push value into stack Stack.prototype.push = function(val) { this.top = { data: val, next: this.top }; }; // pop value from stack Stack.prototype.pop = function() { var top = this.top; if(top) { var popData = top.data; top = top.next; return popData; } return; }; // sort stack in ascending order (main function in exercise) Stack.prototype.sort = function() { // create output stack var stackTwo = new Stack(); while(this.top) { var placeHolder = this.pop(); while(stackTwo.top && stackTwo.top.data > placeHolder) { // push the top element in output stack (larger value) into original stack stackOne.push(stackTwo.pop()); } // push element in placeholder into output stack stackTwo.push(placeHolder); } console.log(stackTwo); };
"use strict"; // Program that sorts a stack such that smallest items are on top // create Stack class function Stack() { this.top = null; } // push value into stack Stack.prototype.push = function(val) { this.top = { data: val, next: this.top }; }; // pop value from stack Stack.prototype.pop = function() { var top = this.top; if(top) { var popData = top.data; top = top.next; return popData; } return; }; // sort stack in ascending order (main function in exercise) Stack.prototype.sort = function() { var stackTwo = new Stack(); while(this.top) { var placeHolder = this.pop(); while(stackTwo.top && stackTwo.top.data > placeHolder) { stackOne.push(stackTwo.pop()); } stackTwo.push(placeHolder); } console.log(stackTwo); };
Make sure dirty state is detected appropriately during a promote
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2014 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.server.service.persistence.module.provider.extension; import org.broadleafcommerce.common.extension.ExtensionHandler; import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.common.media.domain.Media; /** * For internal usage. Allows extending API calls without subclassing the entity. * * @author Jeff Fischer */ public interface MediaFieldPersistenceProviderExtensionHandler extends ExtensionHandler { ExtensionResultStatusType transformId(Media media, ExtensionResultHolder<Long> resultHolder); ExtensionResultStatusType postAdd(Media media); ExtensionResultStatusType postUpdate(Media media); ExtensionResultStatusType checkDirtyState(Media oldMedia, Media newMedia, ExtensionResultHolder<Boolean> resultHolder); public static final int DEFAULT_PRIORITY = Integer.MAX_VALUE; }
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2014 Broadleaf Commerce * %% * 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. * #L% */ package org.broadleafcommerce.openadmin.server.service.persistence.module.provider.extension; import org.broadleafcommerce.common.extension.ExtensionHandler; import org.broadleafcommerce.common.extension.ExtensionResultHolder; import org.broadleafcommerce.common.extension.ExtensionResultStatusType; import org.broadleafcommerce.common.media.domain.Media; /** * For internal usage. Allows extending API calls without subclassing the entity. * * @author Jeff Fischer */ public interface MediaFieldPersistenceProviderExtensionHandler extends ExtensionHandler { ExtensionResultStatusType transformId(Media media, ExtensionResultHolder<Long> resultHolder); ExtensionResultStatusType postAdd(Media media); ExtensionResultStatusType postUpdate(Media media); public static final int DEFAULT_PRIORITY = Integer.MAX_VALUE; }
Add route to register users
'use strict'; var path = process.cwd(); var Graphriend = require(path + '/app/controllers/Graphriend.server.js'); var sess; module.exports = function (app) { function isLoggedIn (req, res, next) { sess = req.session; if (sess.user) { return next(); } else { res.redirect('/'); } } var graPhriend = new Graphriend(); var user = { isLogged: false, name: 'Jinme', username: 'mirabalj' } app.route('/') .get(function (req, res) { res.render('main', { user: user, page: 'index' }); }); app.post('/api/signup', graPhriend.signUp); /* Example Authenticated verify app.route('/profile') .get(isLoggedIn, function (req, res) { res.render('main', { user: sess.user, page: 'profile' }); }); */ /* Example REST api app.route('/friends') .get(isLoggedIn, graPhriend.getFriend) .post(isLoggedIn, graPhriend.addFriend) .delete(isLoggedIn, graPhriend.delFriend); */ };
'use strict'; var path = process.cwd(); var Graphriend = require(path + '/app/controllers/Graphriend.server.js'); var sess; module.exports = function (app) { function isLoggedIn (req, res, next) { sess = req.session; if (sess.user) { return next(); } else { res.redirect('/'); } } var graPhriend = new Graphriend(); var user = { isLogged: false, name: 'Jinme', username: 'mirabalj' } app.route('/') .get(function (req, res) { res.render('main', { user: user, page: 'index' }); }); /* Example Authenticated verify app.route('/profile') .get(isLoggedIn, function (req, res) { res.render('main', { user: sess.user, page: 'profile' }); }); */ /* Example REST api app.route('/friends') .get(isLoggedIn, graPhriend.getFriend) .post(isLoggedIn, graPhriend.addFriend) .delete(isLoggedIn, graPhriend.delFriend); */ };
Build for production with options -p and --bail
/* jshint node:true */ /* jshint -W034 */ /* jshint -W097 */ 'use strict'; let exec = require('child_process').exec; let path = require('path'); let cmdLine = path.join('.', 'node_modules', '.bin', 'webpack'); cmdLine += ' -p --bail --progress --colors'; let env = !!process.argv[2] ? process.argv[2].toLowerCase() : 'production'; if (process.platform === 'win32') { cmdLine = 'set NODE_ENV=' + env + '&& ' + cmdLine; } else { cmdLine = 'NODE_ENV=' + env + ' ' + cmdLine; } let command = exec(cmdLine, error => process.exit(error === null ? 0 : error.code)); command.stdout.on('data', data => process.stdout.write(data)); command.stderr.on('data', data => process.stderr.write(data)); command.on('error', err => process.stderr.write(err));
/* jshint node:true */ /* jshint -W034 */ /* jshint -W097 */ 'use strict'; let exec = require('child_process').exec; let path = require('path'); let cmdLine = path.join('.', 'node_modules', '.bin', 'webpack'); cmdLine += ' --progress --colors'; let env = !!process.argv[2] ? process.argv[2].toLowerCase() : 'production'; if (process.platform === 'win32') { cmdLine = 'set NODE_ENV=' + env + '&& ' + cmdLine; } else { cmdLine = 'NODE_ENV=' + env + ' ' + cmdLine; } let command = exec(cmdLine, error => process.exit(error === null ? 0 : error.code)); command.stdout.on('data', data => process.stdout.write(data)); command.stderr.on('data', data => process.stderr.write(data)); command.on('error', err => process.stderr.write(err));
Enable drf_yasg in test settings
# # Django Tests # .......................... TEST = True CELERY_ALWAYS_EAGER = True TEST_EXCLUDE = ('django',) INSTALLED_APPS += ( 'geotrek.diving', 'geotrek.sensitivity', 'geotrek.outdoor', 'drf_yasg', ) LOGGING['handlers']['console']['level'] = 'CRITICAL' LANGUAGE_CODE = 'en' MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it') LAND_BBOX_AREAS_ENABLED = True class DisableMigrations(): def __contains__(self, item): return True def __getitem__(self, item): return None MIGRATION_MODULES = DisableMigrations() ADMINS = ( ('test', 'test@test.com'), ) MANAGERS = ADMINS TEST_RUNNER = 'geotrek.test_runner.TestRunner'
# # Django Tests # .......................... TEST = True CELERY_ALWAYS_EAGER = True TEST_EXCLUDE = ('django',) INSTALLED_APPS += ( 'geotrek.diving', 'geotrek.sensitivity', 'geotrek.outdoor', ) LOGGING['handlers']['console']['level'] = 'CRITICAL' LANGUAGE_CODE = 'en' MODELTRANSLATION_DEFAULT_LANGUAGE = 'en' MODELTRANSLATION_LANGUAGES = ('en', 'es', 'fr', 'it') LAND_BBOX_AREAS_ENABLED = True class DisableMigrations(): def __contains__(self, item): return True def __getitem__(self, item): return None MIGRATION_MODULES = DisableMigrations() ADMINS = ( ('test', 'test@test.com'), ) MANAGERS = ADMINS TEST_RUNNER = 'geotrek.test_runner.TestRunner'
Fix authenticator - refresh was broken
import Ember from 'ember'; import Authenticator from 'simple-auth-oauth2/authenticators/oauth2'; import ENV from '../config/environment'; export default Authenticator.extend({ makeRequest: function (url, data) { var client_id = ENV['simple-auth']['client-id']; var client_secret = ENV['simple-auth']['client-secret']; return Ember.$.ajax({ url: url, type: 'POST', data: data, dataType: 'json', contentType: 'application/x-www-form-urlencoded', crossDomain: true, headers: { Authorization: "Basic " + btoa(client_id + ":" + client_secret) } }); } });
import Ember from 'ember'; import Authenticator from 'simple-auth-oauth2/authenticators/oauth2'; import ENV from '../config/environment'; export default Authenticator.extend({ makeRequest: function (url, data) { var client_id = ENV['simple-auth']['client-id']; var client_secret = ENV['simple-auth']['client-secret']; data.grant_type = "password"; return Ember.$.ajax({ url: url, type: 'POST', data: data, dataType: 'json', contentType: 'application/x-www-form-urlencoded', crossDomain: true, headers: { Authorization: "Basic " + btoa(client_id + ":" + client_secret) } }); } });
Use next to make endless scroll work.
const nest = require('depnest') const pull = require('pull-stream') const Scroller = require('pull-scroll') const next = require('../../../junk/next-stepper') exports.gives = nest('router.html.page') exports.needs = nest({ 'keys.sync.id': 'first', 'feed.pull.mentions': 'first', 'feed.pull.public': 'first', 'message.html': { render: 'first' }, 'main.html.scroller': 'first' }) exports.create = function (api) { return nest('router.html.page', (path) => { if (path !== '/mentions') return const id = api.keys.sync.id() const mentions = api.feed.pull.mentions(id) const { container, content } = api.main.html.scroller({}) pull( next(mentions, {old: false, limit: 100}), Scroller(container, content, api.message.html.render, true, false) ) pull( next(mentions, {reverse: true, limit: 100, live: false}), Scroller(container, content, api.message.html.render, false, false) ) return container }) }
const nest = require('depnest') const pull = require('pull-stream') const Scroller = require('pull-scroll') const next = require('../../../junk/next-stepper') exports.gives = nest('router.html.page') exports.needs = nest({ 'keys.sync.id': 'first', 'feed.pull.mentions': 'first', 'feed.pull.public': 'first', 'message.html': { render: 'first' }, 'main.html.scroller': 'first' }) exports.create = function (api) { return nest('router.html.page', (path) => { if (path !== '/notifications') return const id = api.keys.sync.id() const mentions = api.feed.pull.mentions(id) const { container, content } = api.main.html.scroller({}) pull( mentions({old: false, limit: 100}), Scroller(container, content, api.message.html.render, true, false) ) pull( mentions({reverse: true, limit: 100, live: false}), Scroller(container, content, api.message.html.render, false, false) ) return container }) }
Copy changes for the sdk package description
from setuptools import setup import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'hellosign_sdk')) def readme(): with open('README.md') as f: return f.read() setup(name='hellosign-python-sdk', version='3.0', description="A Python wrapper for the HelloSign API (http://www.hellosign.com/api)", long_description=readme(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='hellosign python sdk', url='https://github.com/HelloFax/hellosign-python-sdk', author='HelloSign', author_email='apisupport@hellosign.com', license='MIT', packages=[ 'hellosign_sdk', 'hellosign_sdk.utils', 'hellosign_sdk.resource', ], install_requires=[ 'requests' ], test_suite='nose.collector', tests_require=['nose'], include_package_data=True, zip_safe=False)
from setuptools import setup import sys import os sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'hellosign_sdk')) def readme(): with open('README.md') as f: return f.read() setup(name='hellosign-python-sdk', version='3.0', description="An API wrapper written in Python to interact with HelloSign's API (http://www.hellosign.com)", long_description=readme(), classifiers=[ 'Development Status :: 1', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python :: 2.7', ], keywords='hellosign python sdk', url='https://github.com/HelloFax/hellosign-python-sdk', author='HelloSign', author_email='apisupport@hellosign.com', license='MIT', packages=[ 'hellosign_sdk', 'hellosign_sdk.utils', 'hellosign_sdk.resource', ], install_requires=[ 'requests' ], test_suite='nose.collector', tests_require=['nose'], include_package_data=True, zip_safe=False)
Set release version to 0.2.0
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="supercast", author_email="gamzabaw@gmail.com", version="0.2.0", license="MIT", zip_safe=False, include_package_data=True, install_requires=["future"], url="https://github.com/caststack/python-mpegdash", tests_require=["unittest2"], test_suite="tests.my_module_suite", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], )
from os.path import dirname, abspath, join, exists from setuptools import setup long_description = None if exists("README.md"): long_description = open("README.md").read() setup( name="mpegdash", packages=["mpegdash"], description="MPEG-DASH MPD(Media Presentation Description) Parser", long_description=long_description, author="supercast", author_email="gamzabaw@gmail.com", version="0.1.6", license="MIT", zip_safe=False, include_package_data=True, install_requires=["future"], url="https://github.com/caststack/python-mpegdash", tests_require=["unittest2"], test_suite="tests.my_module_suite", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 3", "Environment :: Other Environment", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Software Development :: Libraries :: Python Modules", ], )
Use xsel instead of xclip Prevents indefinite hang on linux
/*! * to-clipboard <https://github.com/jonschlinkert/to-clipboard> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var cp = require('child_process'); function toClipboard(args, cb) { var proc = cp.spawn(program(), { stdio: ['pipe', 'ignore', 'ignore'] }); if (cb) { proc.on('error', cb); proc.on('exit', function() { cb(null); }); } proc.stdin.write(args); proc.stdin.end(); } toClipboard.sync = function toClipboardSync(args) { return cp.execSync(program(), {input: args}); }; function program() { switch (process.platform) { case 'win32': return 'clip'; case 'linux': return 'xsel -bi'; case 'android': return 'termux-clipboard-set' case 'darwin': default: { return 'pbcopy'; } } } /** * Expose `toClipboard` */ module.exports = toClipboard;
/*! * to-clipboard <https://github.com/jonschlinkert/to-clipboard> * * Copyright (c) 2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; var cp = require('child_process'); function toClipboard(args, cb) { var proc = cp.spawn(program(), { stdio: ['pipe', 'ignore', 'ignore'] }); if (cb) { proc.on('error', cb); proc.on('exit', function() { cb(null); }); } proc.stdin.write(args); proc.stdin.end(); } toClipboard.sync = function toClipboardSync(args) { return cp.execSync(program(), {input: args}); }; function program() { switch (process.platform) { case 'win32': return 'clip'; case 'linux': return 'xclip -selection clipboard'; case 'android': return 'termux-clipboard-set' case 'darwin': default: { return 'pbcopy'; } } } /** * Expose `toClipboard` */ module.exports = toClipboard;
Move DOMURL into browserImageSize function Allows isomorphic code to require browser-image-size Calling browserImageSize will still throw an error
/** * Get an image's width and height * @param {(File|blob|string)} File, blob, or URL string * @returns {Promise} resolved with object containing image width and height */ module.exports = function browserImageSize (image) { /* istanbul ignore next */ var DOMURL = require('object-url') return new Promise(function (resolve, reject) { var url = typeof image === 'string' ? image : DOMURL.create(image) if (!url) throw new Error('Must use a valid image') var img = document.createElement('img') img.onload = function onload () { if (typeof image !== 'string') DOMURL.revoke(url) resolve({width: img.width, height: img.height}) } img.onerror = function onerror (err) { if (typeof image !== 'string') DOMURL.revoke(url) reject(err) } img.src = url }) }
/* istanbul ignore next */ var DOMURL = require('object-url') /** * Get an image's width and height * @param {(File|blob|string)} File, blob, or URL string * @returns {Promise} resolved with object containing image width and height */ module.exports = function browserImageSize (image) { return new Promise(function (resolve, reject) { var url = typeof image === 'string' ? image : DOMURL.create(image) if (!url) throw new Error('Must use a valid image') var img = document.createElement('img') img.onload = function onload () { if (typeof image !== 'string') DOMURL.revoke(url) resolve({width: img.width, height: img.height}) } img.onerror = function onerror (err) { if (typeof image !== 'string') DOMURL.revoke(url) reject(err) } img.src = url }) }
Make the Environment object available to build.bfg files
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) result['env'] = env return result
import functools import glob import os import pkgutil _all_builtins = {} _loaded_builtins = False class Binder(object): def __init__(self, fn): self.fn = fn def bind(self, build_inputs, env): return functools.partial(self.fn, build_inputs, env) def builtin(fn): bound = Binder(fn) _all_builtins[fn.__name__] = bound return bound def _load_builtins(): for loader, name, ispkg in pkgutil.walk_packages(__path__, __name__ + '.'): loader.find_module(name).load_module(name) def bind(build_inputs, env): global _loaded_builtins if not _loaded_builtins: _load_builtins() _loaded_builtins = True result = {} for k, v in _all_builtins.iteritems(): result[k] = v.bind(build_inputs, env) return result
Use https when getting the info from the server
// Allows to get the video of the url through the api_url (optional) function BaseVideoInfo(url, api_url) { this.url = url || 'null'; this.api_url = api_url || "https://youtube-dl.appspot.com/api/"; } BaseVideoInfo.prototype = { log: function () { console.log("VideoInfo:\n\t=> URL: " + this.url + "\n\t=> API URL: " + this.api_url); }, // Get the info of the url get_info: function () { $.getJSON( this.api_url, {'url': this.url}, this.process_video_info ).error(this.api_call_failed); }, // This function will be called when the video data is received process_video_info: function (data) { console.error("Nothing to be done with the data"); }, api_call_failed: function (jqXHR, textStatus, errorThrown) { console.error("Error on the api call"); } };
// Allows to get the video of the url through the api_url (optional) function BaseVideoInfo(url, api_url) { this.url = url || 'null'; this.api_url = api_url || "http://youtube-dl.appspot.com/api/"; } BaseVideoInfo.prototype = { log: function () { console.log("VideoInfo:\n\t=> URL: " + this.url + "\n\t=> API URL: " + this.api_url); }, // Get the info of the url get_info: function () { $.getJSON( this.api_url, {'url': this.url}, this.process_video_info ).error(this.api_call_failed); }, // This function will be called when the video data is received process_video_info: function (data) { console.error("Nothing to be done with the data"); }, api_call_failed: function (jqXHR, textStatus, errorThrown) { console.error("Error on the api call"); } };
Remove engine specific global exports from ember-views.
/** @module ember @submodule ember-views */ // BEGIN IMPORTS import Ember from 'ember-runtime'; import jQuery from 'ember-views/system/jquery'; import { isSimpleClick, getViewClientRects, getViewBoundingClientRect } from 'ember-views/system/utils'; import 'ember-views/system/ext'; // for the side effect of extending Ember.run.queues import EventDispatcher from 'ember-views/system/event_dispatcher'; import ViewTargetActionSupport from 'ember-views/mixins/view_target_action_support'; import ComponentLookup from 'ember-views/component_lookup'; import TextSupport from 'ember-views/mixins/text_support'; // END IMPORTS /** Alias for jQuery @method $ @for Ember @public */ // BEGIN EXPORTS Ember.$ = jQuery; Ember.ViewTargetActionSupport = ViewTargetActionSupport; const ViewUtils = Ember.ViewUtils = {}; ViewUtils.isSimpleClick = isSimpleClick; ViewUtils.getViewClientRects = getViewClientRects; ViewUtils.getViewBoundingClientRect = getViewBoundingClientRect; Ember.TextSupport = TextSupport; Ember.ComponentLookup = ComponentLookup; Ember.EventDispatcher = EventDispatcher; // END EXPORTS export default Ember;
/** @module ember @submodule ember-views */ // BEGIN IMPORTS import Ember from 'ember-runtime'; import jQuery from 'ember-views/system/jquery'; import { isSimpleClick, getViewClientRects, getViewBoundingClientRect } from 'ember-views/system/utils'; import 'ember-views/system/ext'; // for the side effect of extending Ember.run.queues import { Renderer } from 'ember-htmlbars/renderer'; import Component from 'ember-htmlbars/component'; import EventDispatcher from 'ember-views/system/event_dispatcher'; import ViewTargetActionSupport from 'ember-views/mixins/view_target_action_support'; import ComponentLookup from 'ember-views/component_lookup'; import Checkbox from 'ember-htmlbars/components/checkbox'; import TextSupport from 'ember-views/mixins/text_support'; import TextField from 'ember-htmlbars/components/text_field'; import TextArea from 'ember-htmlbars/components/text_area'; // END IMPORTS /** Alias for jQuery @method $ @for Ember @public */ // BEGIN EXPORTS Ember.$ = jQuery; Ember.ViewTargetActionSupport = ViewTargetActionSupport; const ViewUtils = Ember.ViewUtils = {}; ViewUtils.isSimpleClick = isSimpleClick; ViewUtils.getViewClientRects = getViewClientRects; ViewUtils.getViewBoundingClientRect = getViewBoundingClientRect; Ember._Renderer = Renderer; Ember.Checkbox = Checkbox; Ember.TextField = TextField; Ember.TextArea = TextArea; Ember.TextSupport = TextSupport; Ember.ComponentLookup = ComponentLookup; Ember.Component = Component; Ember.EventDispatcher = EventDispatcher; // END EXPORTS export default Ember;
Fix action name and prop setting
import { repeat, take, splitAt, map } from 'ramda'; import { handleActions } from 'redux-actions'; import { buildTrie, tokenizer } from '../parser/parser'; import dubliners from '../texts/dubliners'; const source = take(2000, tokenizer(dubliners)); const filter = repeat(true, source.length); const sourceTrie = buildTrie(source); const initialState = { source, filter, sourceTrie, highlighted: [], cursor: 0, }; const selectFromFilter = (index, state) => { const [head, tail] = splitAt(index - 1, state.filter); const [unchanged, alter] = splitAt(state.cursor, head); const deselected = map(() => false, alter); return unchanged.concat(deselected).concat(tail); }; export const editor = handleActions({ SELECT_WORD: (state, action) => ({ filter: selectFromFilter(action.index, state), ...state, }), HIGHLIGHT_WORDS: (state, action) => ({ ...state, }), }, initialState);
import { repeat, take, splitAt, map } from 'ramda'; import { handleActions } from 'redux-actions'; import { buildTrie, tokenizer } from '../parser/parser'; import dubliners from '../texts/dubliners'; const source = take(2000, tokenizer(dubliners)); const filter = repeat(true, source.length); const sourceTrie = buildTrie(source); const initialState = { source, filter, sourceTrie, highlighted: [], cursor: 0, }; const selectFromSource = (index, state) => { const [head, tail] = splitAt(index - 1, state.filter); const [unchanged, alter] = splitAt(state.cursor, head); const deselected = map(() => false, alter); return unchanged.concat(deselected).concat(tail); }; export const editor = handleActions({ SELECT_WORD: (state, action) => ({ source: selectFromSource(action.index, state), ...state, }), HIGHLIGHT_WORDS: (state, action) => ({ ...state, }), }, initialState);
Sort flags by country code
import Ember from 'ember'; import countries from './countries'; export default Ember.Component.extend({ i18n: Ember.inject.service(), countries: countries, languages: Ember.computed('countries', function() { var langs = []; this.get('countries').forEach((country) => { country.languages.forEach((lang) => { langs.push({ countryCode: country.code, name: lang.name, code: lang.code }); }); }); langs.sort(function(a, b) { if (a.countryCode > b.countryCode) { return 1; } if (a.countryCode < b.countryCode) { return -1; } return 0; }); return langs; }), onPick: null, country: null, actions: { pickLanguage(language, code) { this.get('onPick')(language, code); this.set('i18n.locale', code); } } });
import Ember from 'ember'; import countries from './countries'; export default Ember.Component.extend({ i18n: Ember.inject.service(), countries: countries, languages: Ember.computed('countries', function() { var langs = []; this.get('countries').forEach((country) => { country.languages.forEach((lang) => { langs.push({ countryCode: country.code, name: lang.name, code: lang.code }); }); }); langs.sort(function(a, b) { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } return 0; }); return langs; }), onPick: null, country: null, actions: { pickLanguage(language, code) { this.get('onPick')(language, code); this.set('i18n.locale', code); } } });
Update spec for 5.6 to handle additional Refleciton call
<?php namespace spec\Elfiggo\Brobdingnagian\Detector; use Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use ReflectionClass; class ClassSizeSpec extends ObjectBehavior { const LESS_THAN_300 = 299; const GREATER_THAN_300 = 301; function let(ReflectionClass $sus) { $this->beConstructedWith($sus); } function it_is_initializable() { $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\ClassSize'); } function it_does_not_complain_if_the_class_size_is_not_too_large(ReflectionClass $sus) { $sus->getEndLine()->willReturn(self::LESS_THAN_300); $this->check(); } function it_complains_if_class_size_is_too_large(ReflectionClass $sus) { $sus->getEndLine()->willReturn(self::GREATER_THAN_300); $sus->getName()->willReturn("Elfiggo/Brobdingnagian/Detector/ClassSize"); $this->shouldThrow(ClassSizeTooLarge::class)->duringCheck(); } }
<?php namespace spec\Elfiggo\Brobdingnagian\Detector; use Elfiggo\Brobdingnagian\Exception\ClassSizeTooLarge; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use ReflectionClass; class ClassSizeSpec extends ObjectBehavior { const LESS_THAN_300 = 299; const GREATER_THAN_300 = 301; function let(ReflectionClass $sus) { $this->beConstructedWith($sus); } function it_is_initializable() { $this->shouldHaveType('Elfiggo\Brobdingnagian\Detector\ClassSize'); } function it_does_not_complain_if_the_class_size_is_not_too_large(ReflectionClass $sus) { $sus->getEndLine()->willReturn(self::LESS_THAN_300); $this->check(); } function it_complains_if_class_size_is_too_large(ReflectionClass $sus) { $sus->getEndLine()->willReturn(self::GREATER_THAN_300); $this->shouldThrow(ClassSizeTooLarge::class)->duringCheck(); } }
Send calback is now set correctly when underloading arguments.g
module.exports = (function () { 'use strict'; function SGSServerErrorLogger (config, saveCallback, sendCallback) { if (sendCallback === undefined) { sendCallback = saveCallback; saveCallback = config; config = {}; } config = config || {}; this.save = saveCallback || function () {}; this.send = sendCallback; return this.middleware.bind(this); } SGSServerErrorLogger.prototype.middleware = function (error, req, res, next) { if (!(error instanceof Error)) { error = new Error(error); } this.save({ pid: process.pid, reqId: req.data.id, name: error.name, stack: error.stack, message: error.message }); if (this.send === undefined) { return res .status(500) .json({ error: { id: req.data.id, code: error.code, status: 500 } }); } this.send(error, req, res, next); }; return SGSServerErrorLogger; })();
module.exports = (function () { 'use strict'; function SGSServerErrorLogger (config, saveCallback, sendCallback) { if (sendCallback === undefined) { saveCallback = config; sendCallback = saveCallback; config = {}; } config = config || {}; this.save = saveCallback || function () {}; this.send = sendCallback; return this.middleware.bind(this); } SGSServerErrorLogger.prototype.middleware = function (error, req, res, next) { if (!(error instanceof Error)) { error = new Error(error); } this.save({ pid: process.pid, reqId: req.data.id, name: error.name, stack: error.stack, message: error.message }); if (this.send === undefined) { return res.status(500).json({ error: { id: req.data.id, code: error.code, status: 500 } }); } this.send(error, req, res, next); }; return SGSServerErrorLogger; })();
Fix to give x to lorentzian in lorentzian_unnormalized
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) __author__ = "Yuji Ikeda" import numpy as np def lorentzian(x, position, width): return 1.0 / (np.pi * width * (1.0 + ((x - position) / width) ** 2)) def lorentzian_unnormalized(x, position, width, norm): return norm * lorentzian(x, position, width) def gaussian(x, position, width): sigma = width / np.sqrt(2.0 * np.log(2.0)) tmp = np.exp(- (x - position) ** 2 / (2.0 * sigma ** 2)) return 1.0 / np.sqrt(2.0 * np.pi) / sigma * tmp
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function, unicode_literals) __author__ = "Yuji Ikeda" import numpy as np def lorentzian(x, position, width): return 1.0 / (np.pi * width * (1.0 + ((x - position) / width) ** 2)) def lorentzian_unnormalized(x, position, width, norm): return norm * lorentzian(position, width) def gaussian(x, position, width): sigma = width / np.sqrt(2.0 * np.log(2.0)) tmp = np.exp(- (x - position) ** 2 / (2.0 * sigma ** 2)) return 1.0 / np.sqrt(2.0 * np.pi) / sigma * tmp
Update pyrax, and make it stop reverting if the version is too new
#!/usr/bin/env python import os from setuptools import setup, find_packages # Use the docstring of the __init__ file to be the description short_description = " ".join(__import__("cumulus").__doc__.splitlines()).strip() # Use part of the sphinx docs index for the long description doc_dir = os.path.join(os.path.dirname(__file__), "docs") index_filename = os.path.join(doc_dir, "index.rst") long_description = open(index_filename).read().split("split here", 1)[1] setup( name="django-cumulus", version=__import__("cumulus").get_version().replace(" ", "-"), packages=find_packages(), install_requires=[ "pyrax>=1.5.0", ], author="Rich Leland", author_email="rich@richleland.com", license="BSD", description=short_description, long_description=long_description, url="https://github.com/richleland/django-cumulus/", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
#!/usr/bin/env python import os from setuptools import setup, find_packages # Use the docstring of the __init__ file to be the description short_description = " ".join(__import__("cumulus").__doc__.splitlines()).strip() # Use part of the sphinx docs index for the long description doc_dir = os.path.join(os.path.dirname(__file__), "docs") index_filename = os.path.join(doc_dir, "index.rst") long_description = open(index_filename).read().split("split here", 1)[1] setup( name="django-cumulus", version=__import__("cumulus").get_version().replace(" ", "-"), packages=find_packages(), install_requires=[ "pyrax==1.4.11", ], author="Rich Leland", author_email="rich@richleland.com", license="BSD", description=short_description, long_description=long_description, url="https://github.com/richleland/django-cumulus/", classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Programming Language :: Python", "Framework :: Django", ] )
Remove flow typchecking from InstrumentCard - Removed typchecking from AttachedInstrumentCard since mock data is currently being used.
// RobotSettings card for wifi status import * as React from 'react' import InstrumentInfo from './InstrumentInfo' import {Card} from '@opentrons/components' const TITLE = 'Pipettes' export default function AttachedInstrumentsCard (props) { // TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes // here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo // delete channels and volume in either elft or right to view value and button message change // apologies for the messy logic, hard to anticipate what is returned just yet const attachedInstruments = { left: { mount: 'left', channels: 8, volume: 300 }, right: { mount: 'right', channels: 1, volume: 10 } } return ( <Card title={TITLE} > <InstrumentInfo {...attachedInstruments.left}/> <InstrumentInfo {...attachedInstruments.right} /> </Card> ) }
// @flow // RobotSettings card for wifi status import * as React from 'react' import {type StateInstrument} from '../../robot' import InstrumentInfo from './InstrumentInfo' import {Card} from '@opentrons/components' type Props = { left: StateInstrument, right: StateInstrument } const TITLE = 'Pipettes' export default function AttachedInstrumentsCard (props: Props) { // TODO (ka 2018-3-14): not sure where this will be comining from in state so mocking it up for styling purposes // here I am assuming they key and mount will always exist and some sort of presence of a pipette indicator will affect InstrumentInfo // delete channels and volume in either elft or right to view value and button message change // apologies for the messy logic, hard to anticipate what is returned just yet const attachedInstruments = { left: { mount: 'left', channels: 8, volume: 300 }, right: { mount: 'right', channels: 1, volume: 10 } } return ( <Card title={TITLE} > <InstrumentInfo {...attachedInstruments.left}/> <InstrumentInfo {...attachedInstruments.right} /> </Card> ) }
Use dateTime for passwordResetExpires field in user migration table
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('users', function(table) { table.increments(); table.string('name'); table.string('email').unique(); table.string('password'); table.string('passwordResetToken'); table.dateTime('passwordResetExpires'); table.string('gender'); table.string('location'); table.string('website'); table.string('picture'); table.string('facebook'); table.string('twitter'); table.string('google'); table.timestamps(); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.schema.dropTable('users') ]) };
exports.up = function(knex, Promise) { return Promise.all([ knex.schema.createTable('users', function(table) { table.increments(); table.string('name'); table.string('email').unique(); table.string('password'); table.string('passwordResetToken'); table.date('passwordResetExpires'); table.string('gender'); table.string('location'); table.string('website'); table.string('picture'); table.string('facebook'); table.string('twitter'); table.string('google'); table.timestamps(); }) ]); }; exports.down = function(knex, Promise) { return Promise.all([ knex.schema.dropTable('users') ]) };
Clean up page index test
<?php namespace Backend\Modules\Pages\Tests\Actions; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; final class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { $this->assertAuthenticationIsNeeded($client, '/private/en/pages/index'); } public function testIndexContainsPages(Client $client): void { $this->login($client); $this->assertPageLoadedCorrectly( $client, '/private/en/pages/index', [ 'Home', 'Add page', 'Recently edited', ] ); } }
<?php namespace Backend\Modules\Pages\Tests\Actions; use Backend\Core\Tests\BackendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; final class IndexTest extends BackendWebTestCase { public function testAuthenticationIsNeeded(Client $client): void { $this->assertAuthenticationIsNeeded($client, '/private/en/pages/index'); } public function testIndexContainsPages(): void { $client = static::createClient(); $this->login($client); $client->request('GET', '/private/en/pages/index'); self::assertContains( 'Home', $client->getResponse()->getContent() ); // some stuff we also want to see on the blog index self::assertContains( 'Add page', $client->getResponse()->getContent() ); self::assertContains( 'Recently edited', $client->getResponse()->getContent() ); } }
Fix error message when failing to convert a Path When a parameter is of type Path, the PathConverter is used. If the path is not a valid Path, for instance when the user input is an uri, a stack trace is shown, where a proper error message is expected. When converting a path, catch the InvalidPathException that can be thrown, and format the message as it is done in other converters.
/** * Copyright (C) 2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.jcommander.converters; import com.beust.jcommander.ParameterException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; /** * Convert a string into a path. * * @author samvv */ public class PathConverter extends BaseConverter<Path> { public PathConverter(String optionName) { super(optionName); } public Path convert(String value) { try { return Paths.get(value); } catch (InvalidPathException e) { throw new ParameterException(getErrorString(value, "a path")); } } }
/** * Copyright (C) 2010 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.jcommander.converters; import com.beust.jcommander.IStringConverter; import java.nio.file.Path; import java.nio.file.Paths; /** * Convert a string into a path. * * @author samvv */ public class PathConverter implements IStringConverter<Path> { public Path convert(String value) { return Paths.get(value); } }
Fix stop description generator using route destination (api)
const _ = require('lodash'); const db = require('../../db.js'); module.exports = async () => { const stops = await db.query(` SELECT stop_id, GROUP_CONCAT(type, ':', trip.destination) AS destinations FROM stop_times JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id GROUP BY stop_id `); let query = 'START TRANSACTION;'; // Get the most common destination for all trips serving a stop with coaches having the least priority. for (const stop of stops) { if (!stop.destinations) continue; let destinations = stop.destinations.split(','); if (destinations.reduce((prev, curr) => prev + Number(curr.startsWith('coach')), 0) !== destinations.length) destinations = destinations.filter((destination) => !destination.startsWith('coach')); query += `UPDATE stops SET description = '${_(destinations.map((destination) => destination.split(':')[1])).countBy().entries().maxBy('[1]')[0]}' WHERE id = '${stop.stop_id}';`; } await db.query(`${query}COMMIT;`); };
const _ = require('lodash'); const db = require('../../db.js'); module.exports = async () => { const stops = await db.query(` SELECT stop_id, GROUP_CONCAT(type, ':', route.destination) AS destinations FROM stop_times JOIN trips AS trip ON trip.id = trip_id JOIN routes AS route ON route.id = route_id GROUP BY stop_id `); let query = 'START TRANSACTION;'; // Get the most common destination for all trips serving a stop with coaches having the least priority. for (const stop of stops) { if (!stop.destinations) continue; let destinations = stop.destinations.split(','); if (destinations.reduce((prev, curr) => prev + Number(curr.startsWith('coach')), 0) !== destinations.length) destinations = destinations.filter((destination) => !destination.startsWith('coach')); query += `UPDATE stops SET description = '${_(destinations.map((destination) => destination.split(':')[1])).countBy().entries().maxBy('[1]')[0]}' WHERE id = '${stop.stop_id}';`; } await db.query(`${query}COMMIT;`); };
Make Sonar stop insisting that a console command should output messages using a log framework.
/* * Copyright 2016-2017 Steinar Bang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package no.priv.bang.ukelonn.impl; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import no.priv.bang.ukelonn.UkelonnDatabase; @Command(scope="ukelonn", name="release-liquibase-lock", description = "Forcibly release the Liquibase changelog lock") @Service public class KarafReleaseLiquibaseLockCommand implements Action { @Reference UkelonnDatabase database; @Override public Object execute() throws Exception { database.forceReleaseLocks(); System.out.println("Forcibly unlocked the Liquibase changelog lock"); // NOSONAR return null; } }
/* * Copyright 2016-2017 Steinar Bang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package no.priv.bang.ukelonn.impl; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import no.priv.bang.ukelonn.UkelonnDatabase; @Command(scope="ukelonn", name="release-liquibase-lock", description = "Forcibly release the Liquibase changelog lock") @Service public class KarafReleaseLiquibaseLockCommand implements Action { @Reference UkelonnDatabase database; @Override public Object execute() throws Exception { database.forceReleaseLocks(); System.out.println("Forcibly unlocked the Liquibase changelog lock"); return null; } }
Set unsupported ES6 features to false
module.exports = { 'env': { 'es6': true }, 'ecmaFeatures': { 'arrowFunctions': true, 'blockBindings': true, 'classes': true, 'defaultParams': true, 'destructuring': false, 'forOf': true, 'generators': false, 'modules': true, 'objectLiteralComputedProperties': true, 'objectLiteralDuplicateProperties': false, 'objectLiteralShorthandMethods': true, 'objectLiteralShorthandProperties': true, 'restParams': false, 'spread': false, 'superInFunctions': true, 'templateStrings': true, 'jsx': true }, 'rules': { // disallow modifying variables that are declared using const 'no-const-assign': 2, // require let or const instead of var 'no-var': 2, // suggest using of const declaration for variables that are never modified after declared 'prefer-const': 1 } };
module.exports = { 'env': { 'es6': true }, 'ecmaFeatures': { 'arrowFunctions': true, 'blockBindings': true, 'classes': true, 'destructuring': true, 'forOf': true, 'generators': false, 'modules': true, 'objectLiteralComputedProperties': true, 'objectLiteralDuplicateProperties': false, 'objectLiteralShorthandMethods': true, 'objectLiteralShorthandProperties': true, 'superInFunctions': true, 'templateStrings': true, 'jsx': true }, 'rules': { // disallow modifying variables that are declared using const 'no-const-assign': 2, // require let or const instead of var 'no-var': 2, // suggest using of const declaration for variables that are never modified after declared 'prefer-const': 1 } };
Fix issue with multi dimensional arrays
import layout from '../../config/layout' const fixLocalAsset = assets => ( (Array.isArray(assets) ? assets : [assets]).map(asset => `/${asset}`) ) const normalizeAssets = assets => { let normalized = [] assets.forEach(item => { if (Array.isArray(item)) { item.forEach(asset => { normalized.push(asset) }) } else { normalized.push(item) } }) return normalized } export const getAssets = (localAssets = []) => ( Array.concat( layout.script.map(item => item.src), layout.link.map(item => item.href), normalizeAssets(localAssets.map(asset => fixLocalAsset(asset))) ) ) export const getAssetsByExtension = (extension, localAssets = []) => ( getAssets(localAssets).filter(asset => new RegExp('.(' + extension + ')$').test(asset)) ) export const getScripts = (localAssets = []) => ( getAssetsByExtension('js', localAssets) ) export const getStyles = (localAssets = []) => ( getAssetsByExtension('css', localAssets) )
import layout from '../../config/layout' const fixLocalAsset = assets => ( (Array.isArray(assets) ? assets : [assets]).map(asset => `/${asset}`) ) export const getAssets = (localAssets = []) => ( Array.concat( layout.script.map(item => item.src), layout.link.map(item => item.href), localAssets.map(asset => fixLocalAsset(asset)) ) ) export const getAssetsByExtension = (extension, localAssets = []) => ( getAssets(localAssets).filter(asset => new RegExp('.(' + extension + ')$').test(asset)) ) export const getScripts = (localAssets = []) => ( getAssetsByExtension('js', localAssets) ) export const getStyles = (localAssets = []) => ( getAssetsByExtension('css', localAssets) )
Test commit for conflict resolution
var app = angular.module('at', ['pascalprecht.translate']); app.config(function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: '/json/', suffix: '.json' }); /*$translateProvider.translations('en', { TITLE: 'Hello', FOO: 'This is a paragraph.', BUTTON_LANG_EN: 'english', BUTTON_LANG_DE: 'german' }); $translateProvider.translations('de', { TITLE: 'Hallo', FOO: 'Dies ist ein Paragraph.', BUTTON_LANG_EN: 'englisch', BUTTON_LANG_DE: 'deutsch' });*/ $translateProvider.preferredLanguage('po'); });
var app = angular.module('at', ['pascalprecht.translate']); app.config(function ($translateProvider) { $translateProvider.useStaticFilesLoader({ prefix: '/json/', suffix: '.json' }); $translateProvider.translations('en', { TITLE: 'Hello', FOO: 'This is a paragraph.', BUTTON_LANG_EN: 'english', BUTTON_LANG_DE: 'german' }); $translateProvider.translations('de', { TITLE: 'Hallo', FOO: 'Dies ist ein Paragraph.', BUTTON_LANG_EN: 'englisch', BUTTON_LANG_DE: 'deutsch' }); $translateProvider.preferredLanguage('po'); });
Fix import post merge to project directory
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = items.DatasetItem() dataset['url'] = response.url dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract() dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract() return dataset
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1/text()").extract() dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract() return dataset
Implement xref tooltip using ReferencesAPI.
import { NodeComponent } from 'substance' import { getXrefLabel, getXrefTargets } from '../../editor/util/xrefHelpers' export default class ReaderXrefComponent extends NodeComponent { render($$) { let node = this.props.node let refType = node.getAttribute('ref-type') let label = getXrefLabel(node) let el = $$('span').addClass('sc-reader-xref sm-'+refType).append(label) // Add a preview if refType is bibr if (refType === 'bibr') { el.append( this._renderPreview($$) ) } return el } /* Render preview only for references. */ _renderPreview($$) { let references = this.context.api.getReferences() let el = $$('div').addClass('se-preview') let xrefTargets = getXrefTargets(this.props.node) xrefTargets.forEach(refId => { let label = references.getLabel(refId) let html = references.renderReference(refId) el.append( $$('div').addClass('se-ref').append( $$('div').addClass('se-label').append(label), $$('div').addClass('se-text').html(html) ).attr('data-id', refId) ) }) return el } }
import { NodeComponent } from 'substance' import { getXrefLabel, getXrefTargets } from '../../editor/util/xrefHelpers' export default class ReaderXrefComponent extends NodeComponent { render($$) { let node = this.props.node let refType = node.getAttribute('ref-type') let label = getXrefLabel(node) let el = $$('span').addClass('sc-xref sm-'+refType).append(label) // Add a preview if refType is bibr if (refType === 'bibr') { el.append( this._renderPreview($$) ) } return el } /* Only for references */ _renderPreview($$) { let xrefTargets = getXrefTargets(this.props.node) } }
Fix issues with resolving server relative URLs when bundling with JSPM
/*global System:false, exports:false */ function santiseSource( source ) { return source.replace( /(['\\])/g, '\\$1' ) .replace( /[\f]/g, '\\f' ) .replace( /[\b]/g, '\\b' ) .replace( /[\n]/g, '\\n' ) .replace( /[\t]/g, '\\t' ) .replace( /[\r]/g, '\\r' ) .replace( /[\u2028]/g, '\\u2028' ) .replace( /[\u2029]/g, '\\u2029' ); } function resolveUrl( address, baseUrl ) { if ( baseUrl && address.indexOf( baseUrl ) === 0 ) { return address.substr( baseUrl.length ); } return address; } exports.translate = function translate( load ) { var baseUrl = typeof System.baseURL === 'string' ? System.baseURL : '', options = System.ngTemplatePlugin || {}, url = resolveUrl( load.address, baseUrl ); return 'var url = ' + ( options.serverRelative ? "System.baseURL.replace(/^\\w+:\\/\\/[^\\/]*/,'')+" : '' ) + "'" + url + "';" + "require('angular').module('ng')" + ".run(['$templateCache', function(c) { c.put(" + "url, '" + santiseSource( load.source ) + "'); }]);" + 'module.exports = { templateUrl: url };'; };
/*global System:false, exports:false */ var serverRelativeRegexp = /^\w+:\/\/[^\/]*/; function santiseSource( source ) { return source.replace( /(['\\])/g, '\\$1' ) .replace( /[\f]/g, '\\f' ) .replace( /[\b]/g, '\\b' ) .replace( /[\n]/g, '\\n' ) .replace( /[\t]/g, '\\t' ) .replace( /[\r]/g, '\\r' ) .replace( /[\u2028]/g, '\\u2028' ) .replace( /[\u2029]/g, '\\u2029' ); } function resolveUrl( address, baseUrl, useServerRelative ) { if ( useServerRelative ) { return address.replace( serverRelativeRegexp, '' ); } else if ( baseUrl && address.indexOf( baseUrl ) === 0 ) { return address.substr( baseUrl.length ); } return address; } exports.translate = function( load ) { var baseUrl = typeof System.baseURL === 'string' ? System.baseURL : '', options = System.ngTemplatePlugin || {}, url = resolveUrl( load.address, baseUrl, !!options.serverRelative ); return "require('angular').module('ng')" + ".run(['$templateCache', function(c) { c.put('" + url + "', '" + santiseSource( load.source ) + "') }]);" + "module.exports = { templateUrl: '" + url + "' };"; };
Remove useless parameter from promise
'use strict'; var kss = require('kss'); module.exports = function(grunt) { grunt.registerMultiTask('kss', 'Generate style guide with KSS.', function() { var done = this.async(); var options = this.options({}); // Add source and destination from Grunt. options.source = []; this.files.forEach(function(file) { options.destination = file.dest; for (var i = 0; i < file.src.length; i++) { options.source.push(file.src[i]); } }); // Use promise to make sure done() is called when kss() ends Promise.all([kss(options)]).then(function() { done(); }).catch(error => { // Kss prints the error itself, otherwise use grunt.log.error(error); done(false); }); }); };
'use strict'; var kss = require('kss'); module.exports = function(grunt) { grunt.registerMultiTask('kss', 'Generate style guide with KSS.', function() { var done = this.async(); var options = this.options({}); // Add source and destination from Grunt. options.source = []; this.files.forEach(function(file) { options.destination = file.dest; for (var i = 0; i < file.src.length; i++) { options.source.push(file.src[i]); } }); // Use promise to make sure done() is called when kss() ends Promise.all([kss(options)]).then(function(values) { done(); }).catch(error => { // Kss prints the error itself, otherwise use grunt.log.error(error); done(false); }); }); };
Add test for __get magic method in AdministrativeArea class
<?php use Galahad\LaravelAddressing\Country; use Galahad\LaravelAddressing\LaravelAddressing; /** * Class AdministrativeAreaTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaTest extends PHPUnit_Framework_TestCase { public function testMinasGeraisStateInBrazil() { $country = new Country; $brazil = $country->getByCode('BR'); $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG'); $this->assertEquals($minasGerais->getName(), 'Minas Gerais'); } public function testAlabamaCodeByName() { $country = new Country; $us = $country->getByCode('US'); $alabama = $us->getAdministrativeAreas()->getByName('Alabama'); $alabama2 = $us->states()->name('Alabama'); $this->assertEquals($alabama->getCode(), 'AL'); $this->assertEquals($alabama2->getCode(), 'AL'); } public function testGetMagicMethod() { $maker = new LaravelAddressing(); $firstState = $maker->country('US')->states()->getByKey(0); $this->assertEquals($firstState->name, 'Alabama'); } }
<?php use Galahad\LaravelAddressing\Country; /** * Class AdministrativeAreaTest * * @author Junior Grossi <juniorgro@gmail.com> */ class AdministrativeAreaTest extends PHPUnit_Framework_TestCase { public function testMinasGeraisStateInBrazil() { $country = new Country; $brazil = $country->getByCode('BR'); $minasGerais = $brazil->getAdministrativeAreas()->getByCode('MG'); $this->assertEquals($minasGerais->getName(), 'Minas Gerais'); } public function testAlabamaCodeByName() { $country = new Country; $us = $country->getByCode('US'); $alabama = $us->getAdministrativeAreas()->getByName('Alabama'); $alabama2 = $us->states()->name('Alabama'); $this->assertEquals($alabama->getCode(), 'AL'); $this->assertEquals($alabama2->getCode(), 'AL'); } }
Revert "move isCorrectUrl outside of findCorrectUrls" This reverts commit 6d3cc349eaba6ac2fa4671fd4a67111911c2ec48.
const fetch = require('node-fetch'); const composeDictionaryEntry = require('./utils/composeDictionaryEntry.js'); const fs = require('fs'); fs.readFile('./words.txt', 'utf8', function (err, data) { if (err) { throw err; } const words = data .split(',') .map(item => item.trim()) Promise.all( findCorrectUrls(words) ) .then(urls => Promise.all( urls.map(url => fetch(url) .then(res => res.text()) ) ) ) .then(bodies => bodies.map(composeDictionaryEntry)) .then(entries => entries.reduce( (body, acc) => `${acc}${body}` )) .then(result => fs.writeFileSync('result.txt', result)) .catch(err => console.log(err)); }); function findCorrectUrls(words) { return words .map(word => `http://www.ldoceonline.com/dictionary/${word}`) .map(url => fetch(url) .then(resp => { return resp.ok ? url : `${url}_1`} ) .catch(err => console.log(err)) ) }
const fetch = require('node-fetch'); const composeDictionaryEntry = require('./utils/composeDictionaryEntry.js'); const fs = require('fs'); fs.readFile('./words.txt', 'utf8', function (err, data) { if (err) { throw err; } const words = data .split(',') .map(item => item.trim()) Promise.all( findCorrectUrls(words) ) .then(urls => Promise.all( urls.map(url => fetch(url) .then(res => res.text()) ) ) ) .then(bodies => bodies.map(composeDictionaryEntry)) .then(entries => entries.reduce( (body, acc) => `${acc}${body}` )) .then(result => fs.writeFileSync('result.txt', result)) .catch(err => console.log(err)); }); function findCorrectUrls(words) { return words .map(word => `http://www.ldoceonline.com/dictionary/${word}`) .map(url => isCorrectUrl(url) ? url : `${url}_1`) } function isCorrectUrl(url) { fetch(url) .then(resp => resp.ok) .catch(err => console.log(err)) }
Remove last reference to generators
import re # A regular expression is a string like what you see below between the quote # marks, and the ``re`` module interprets it as a pattern. Each regular # expression describes a small program that takes another string as input and # returns information about that string. See # http://docs.python.org/library/re.html. The ``re`` module provides the # ``compile`` function, which prepares regex patterns for use in searching input # strings. # # We put an ``r`` before the string so that Python doesn't interpret the # backslashes before the ``re`` module gets to see them. (E.g., ``\n`` means a # newline character, so ``\n`` is a single character, not two as they appear in # the source code.) # # The Unicode flag lets us handle words with accented characters. FIRST_LAST = re.compile(r"(\w*)\s+((?:\w|\s|['-]){2,})", flags=re.UNICODE) def split_name(name): '''Return ("First", "Last") tuple from a string like "First Last". ``name`` is a string. This function returns a tuple of strings. When a non-matching string is encoutered, we return ``None``. ''' match = FIRST_LAST.search(name) return None if match is None else (match.group(1), match.group(2))
import re # A regular expression is a string like what you see below between the quote # marks, and the ``re`` module interprets it as a pattern. Each regular # expression describes a small program that takes another string as input and # returns information about that string. See # http://docs.python.org/library/re.html. The ``re`` module provides the # ``compile`` function, which prepares regex patterns for use in searching input # strings. # # We put an ``r`` before the string so that Python doesn't interpret the # backslashes before the ``re`` module gets to see them. (E.g., ``\n`` means a # newline character, so ``\n`` is a single character, not two as they appear in # the source code.) # # The Unicode flag lets us handle words with accented characters. FIRST_LAST = re.compile(r"(\w*)\s+((?:\w|\s|['-]){2,})", flags=re.UNICODE) def split_name(name): '''Return ("First", "Last") tuple from a string like "First Last". ``name`` is a string. This function returns a tuple of strings. When a non-matching string is encoutered, we yield ``None``. ''' match = FIRST_LAST.search(name) return None if match is None else (match.group(1), match.group(2))
Fix Germany's number cleaner to correctly support the trunk number '0'
<?php if (!defined('CALLERID')) { // This check helps protect against security problems; // your code file can't be executed directly from the web. exit(1); } class DeNumberCleaner extends NumberCleaner { public $international_calling_prefix = '00'; function clean_number($number){ if(preg_match('/^(0\d{2,11})$/', $number, $matches)){ return array('number' => '+49' . $matches[1], 'country' => 'de'); }else if(preg_match('/^\+49(\d{2,11})$/', $number, $matches)){ return array('number' => '+49' . $matches[1], 'country' => 'de'); }else{ return false; } } }
<?php if (!defined('CALLERID')) { // This check helps protect against security problems; // your code file can't be executed directly from the web. exit(1); } class DeNumberCleaner extends NumberCleaner { public $international_calling_prefix = '00'; function clean_number($number){ if(preg_match('/^(\d{3,12})$/', $number, $matches)){ return array('number' => '+49' . $matches[1], 'country' => 'de'); }else if(preg_match('/^\+49(\d{3,12})$/', $number, $matches)){ return array('number' => '+49' . $matches[1], 'country' => 'de'); }else{ return false; } } }
Fix up output by including endls.
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh, p.endl class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')', p.endl class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(compose(tree).encode(ENCODING)) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- '''A CMakeLists parser using funcparserlib. The parser is based on [examples of the CMakeLists format][1]. [1]: http://www.vtk.org/Wiki/CMake/Examples ''' from __future__ import unicode_literals, print_function import re import pypeg2 as p import list_fix class Arg(p.str): grammar = re.compile(r'[${}_a-zA-Z0-9.]+') class Comment(p.str): grammar = p.comment_sh class Command(list_fix.List): grammar = p.name(), '(', p.some([Arg, Comment]), ')' class File(list_fix.List): grammar = p.some([Command, Comment]) def parse(s): return p.parse(s, File) # Inverse of parse compose = p.compose def main(): import sys ENCODING = 'utf-8' input = sys.stdin.read().decode(ENCODING) tree = parse(input) print(str(tree).encode(ENCODING)) if __name__ == '__main__': main()
Modify so that sort order of literals doesn't matter.
/* * Copyright (c) 2017 Robert 'Bobby' Zenz * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.bonsaimind.arbitrarylines.lines; import org.eclipse.swt.SWT; public enum LineStyle { DASH(SWT.LINE_DASH), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT), DOT(SWT.LINE_DOT), SOLID(SWT.LINE_SOLID); private static final String[] styleStrings = new String[] { SOLID.toString(), DASH.toString(), DOT.toString(), DASHDOT.toString(), DASHDOTDOT.toString() }; private final int swtStyle; private LineStyle(int swtEquivalent) { swtStyle = swtEquivalent; } public static final String[] getStyleStrings() { return styleStrings; } public int getSwtStyle() { return swtStyle; } }
/* * Copyright (c) 2017 Robert 'Bobby' Zenz * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.bonsaimind.arbitrarylines.lines; import org.eclipse.swt.SWT; public enum LineStyle { SOLID(SWT.LINE_SOLID), DASH(SWT.LINE_DASH), DOT(SWT.LINE_DOT), DASHDOT(SWT.LINE_DASHDOT), DASHDOTDOT(SWT.LINE_DASHDOTDOT); private static final String[] styleStrings = new String[DASHDOTDOT.ordinal() + 1]; private final int swtStyle; static { for (LineStyle type : LineStyle.values()) { styleStrings[type.ordinal()] = type.toString(); } } private LineStyle(int swtEquivalent) { swtStyle = swtEquivalent; } public static final String[] getStyleStrings() { return styleStrings; } public int getSwtStyle() { return swtStyle; } }
Fix mistake in path in warning when config file is missing
import ConfigParser import os import yaml class Database(object): """ Generic class for handling database-related tasks. """ def select_config_for_environment(self): """ Read the value of env variable and load the property database configuration based on the value of DB_ENV. Takes no input and returns a string like 'production' or 'testing'.""" return os.getenv('DB_ENV', 'development') def load_config(self): """ Pull the configuration off disk and parse the yml. Returns a dict containing a subset of the yml from the 'database' section. """ environment = self.select_config_for_environment() config_src = ("%s/config/cmdb.%s.yml" % ( (os.path.join(os.path.dirname(__file__), '..')), environment)) config = open(config_src) try: return yaml.load(config)['database'] except: print ("Ensure config/cmdb.%s.yml exists" % environment) return None
import ConfigParser import os import yaml class Database(object): """ Generic class for handling database-related tasks. """ def select_config_for_environment(self): """ Read the value of env variable and load the property database configuration based on the value of DB_ENV. Takes no input and returns a string like 'production' or 'testing'.""" return os.getenv('DB_ENV', 'development') def load_config(self): """ Pull the configuration off disk and parse the yml. Returns a dict containing a subset of the yml from the 'database' section. """ environment = self.select_config_for_environment() config_src = ("%s/config/cmdb.%s.yml" % ( (os.path.join(os.path.dirname(__file__), '..')), environment)) config = open(config_src) try: return yaml.load(config)['database'] except: print ("Ensure config/cmdb.%s.yml exists" % config_src) return None
Correct rules registry addition via plugin (refs GH-2404)
""" sentry.rules ~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from .base import * # NOQA from .registry import RuleRegistry # NOQA def init_registry(): from sentry.constants import SENTRY_RULES from sentry.plugins import plugins from sentry.utils.imports import import_string from sentry.utils.safe import safe_execute registry = RuleRegistry() for rule in SENTRY_RULES: cls = import_string(rule) registry.add(cls) for plugin in plugins.all(version=2): for cls in (safe_execute(plugin.get_rules) or ()): registry.add(cls) return registry rules = init_registry()
""" sentry.rules ~~~~~~~~~~~~ :copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import from .base import * # NOQA from .registry import RuleRegistry # NOQA def init_registry(): from sentry.constants import SENTRY_RULES from sentry.plugins import plugins from sentry.utils.imports import import_string from sentry.utils.safe import safe_execute registry = RuleRegistry() for rule in SENTRY_RULES: cls = import_string(rule) registry.add(cls) for plugin in plugins.all(version=2): for cls in (safe_execute(plugin.get_rules) or ()): register.add(cls) return registry rules = init_registry()
Remove spaces from credit card
const { GraphQLScalarType } = require('graphql') const cc = require('credit-card') function parse (value) { const { card, validCardNumber, validCvv: validCVV, validExpiryMonth, validExpiryYear, isExpired } = cc.validate(getPayload()) if (validCardNumber) { return Object.assign(card, { validCVV, validExpiryMonth, validExpiryYear, isExpired }) } function getPayload () { switch (typeof value) { case 'string': case 'number': { const number = value.toString().replace(/\D/g, '') const cardType = cc.determineCardType(number) return { number, cardType } } default: return Object.assign({}, value, { number: value.number.toString().replace(/\D/g, ''), cardType: value.cardType || value.type }) } } } module.exports = new GraphQLScalarType({ name: 'CreditCard', serialize: parse, parseValue: parse, parseLiteral (ast) { return parse(ast.value) } })
const { GraphQLScalarType } = require('graphql') const cc = require('credit-card') function parse (value) { const { card, validCardNumber, validCvv: validCVV, validExpiryMonth, validExpiryYear, isExpired } = cc.validate(getPayload()) if (validCardNumber) { return Object.assign(card, { validCVV, validExpiryMonth, validExpiryYear, isExpired }) } function getPayload () { switch (typeof value) { case 'string': case 'number': { const cardType = cc.determineCardType(value.toString()) return { number: value.toString(), cardType } } default: return Object.assign({ cardType: value.cardType || value.type }, value) } } } module.exports = new GraphQLScalarType({ name: 'CreditCard', serialize: parse, parseValue: parse, parseLiteral (ast) { return parse(ast.value) } })
Make lightwindow work after ajax load
var scroll_lock = false; var last_page = false; var current_page = 1; function checkScroll() { if(!last_page && !scroll_lock && nearBottomOfPage()) { scroll_lock = true; current_page++; var qs = $H(location.search.toQueryParams()); qs.each(function(pair) { qs.set(pair.key, pair.value.replace("+", " ")); }); var url = location.pathname + "?" + qs.merge({ 'page' : current_page }).toQueryString(); new Ajax.Request(url, { asynchronous: true, evalScripts: true, method: 'get', onSuccess: function(req) { scroll_lock = false; myLightWindow._setupLinks(); } }); } } function nearBottomOfPage() { return scrollDistanceFromBottom() < 500; } function scrollDistanceFromBottom() { return pageHeight() - (window.pageYOffset + self.innerHeight); } function pageHeight() { return $$("body")[0].getHeight(); } document.observe('dom:loaded', function() { setInterval("checkScroll()", 250); });
var scroll_lock = false; var last_page = false; var current_page = 1; function checkScroll() { if(!last_page && !scroll_lock && nearBottomOfPage()) { scroll_lock = true; current_page++; var qs = $H(location.search.toQueryParams()); qs.each(function(pair) { qs.set(pair.key, pair.value.replace("+", " ")); }); var url = location.pathname + "?" + qs.merge({ 'page' : current_page }).toQueryString(); new Ajax.Request(url, { asynchronous: true, evalScripts: true, method: 'get', onSuccess: function(req) { setTimeout(function() { scroll_lock = false; }, 500); } }); } } function nearBottomOfPage() { return scrollDistanceFromBottom() < 500; } function scrollDistanceFromBottom() { return pageHeight() - (window.pageYOffset + self.innerHeight); } function pageHeight() { return $$("body")[0].getHeight(); } document.observe('dom:loaded', function() { setInterval("checkScroll()", 250); });
Comment out test that does nothing and fails.
const app = require('../../tools/app.js') const request = require('supertest') const assert = require('assert') // describe('Sign functionality', () => { // let sessionID // before(() => { // return request(app) // .post('/resources/cgi-bin/scrollery-cgi.pl') // .send({ // USER_NAME: 'test', // PASSWORD: 'asdf', // SCROLLVERSION: 1, // transaction: 'validateSession', // }) // .then(res => { // sessionID = res.body.SESSION_ID // }) // }) // const send = payload => // request(app) // .post('/resources/cgi-bin/scrollery-cgi.pl') // .send({ // ...payload, // SESSION_ID: sessionID, // }) // it('should attempt to get the text of a fragment', () => { // return send({ // transaction: 'getTextOfFragment', // scroll_version_id: 808, // col_id: 9111, // }) // .expect(200) // .then(res => { // console.log('Response:') // console.log(res.body) // }) // }) // })
const app = require('../../tools/app.js') const request = require('supertest') const assert = require('assert') describe('Sign functionality', () => { let sessionID before(() => { return request(app) .post('/resources/cgi-bin/scrollery-cgi.pl') .send({ USER_NAME: 'test', PASSWORD: 'asdf', SCROLLVERSION: 1, transaction: 'validateSession', }) .then(res => { sessionID = res.body.SESSION_ID }) }) const send = payload => request(app) .post('/resources/cgi-bin/scrollery-cgi.pl') .send({ ...payload, SESSION_ID: sessionID, }) it('should attempt to get the text of a fragment', () => { return send({ transaction: 'getTextOfFragment', scroll_version_id: 808, col_id: 9111, }) .expect(200) .then(res => { console.log('Response:') console.log(res.body) }) }) })
Call same methods on parent class.
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_append_rows() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_insert_rows() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_delete_rows() def test_clear(self): with self.assertRaises(ValueError): super().test_clear() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_row_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
import unittest import numpy as np from scipy.sparse import csr_matrix, lil_matrix from Orange import data from Orange.tests import test_table as tabletests class InterfaceTest(tabletests.InterfaceTest): def setUp(self): super().setUp() self.table = data.Table.from_numpy( self.domain, csr_matrix(self.table.X), csr_matrix(self.table.Y), ) def test_append_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_insert_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_delete_rows(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_clear(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_row_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment() def test_value_assignment(self): with self.assertRaises(ValueError): super().test_value_assignment()
Use the database seeds from the Feature spec
var assert = require('assert'); var seeds = require('../seeds'); var Feature = require('../feature'); describe('Feature', function () { before(function (done) { seeds(done); }); describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
var assert = require('assert'); var Feature = require('../feature'); describe('Feature', function () { describe('schema', function () { it('successfully creates a valid document'); it('fails at creating an invalid document'); }); describe('.search()', function () { it('performs an empty search, returning all commands', function (done) { Feature.search('', function (docs) { assert.equal(7, docs.length); done(); }); }); it('performs a case-insensitive search for a command', function (done) { Feature.search('git ADD', function (docs) { assert.equal(1, docs.length) done(); }); }); it('performs a search for a command that does not exist', function (done) { Feature.search('git yolo', function (docs) { assert.equal(0, docs.length); done(); }); }); }); });
Add filter tags to stories actions on js app
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const TAGS = ['NDC', 'ndcsdg', 'esp', 'climate watch']; const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch(`/api/v1/stories?tags=${TAGS}`) .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
import { createAction } from 'redux-actions'; import { createThunkAction } from 'utils/redux'; const fetchStoriesInit = createAction('fetchStoriesInit'); const fetchStoriesReady = createAction('fetchStoriesReady'); const fetchStoriesFail = createAction('fetchStoriesFail'); const fetchStories = createThunkAction('fetchStories', () => dispatch => { dispatch(fetchStoriesInit()); fetch('/api/v1/stories') .then(response => { if (response.ok) return response.json(); throw Error(response.statusText); }) .then(data => { dispatch(fetchStoriesReady(data)); }) .catch(error => { console.info(error); dispatch(fetchStoriesFail()); }); }); export default { fetchStories, fetchStoriesInit, fetchStoriesReady, fetchStoriesFail };
Make pageUri equal to process.cwd() in Node.js
/** * The fake sandbox of browser environment */ exports.document = { getElementById: function(id) { // Return the fake loader script node if (id === "seajsnode") { return { hasAttribute: true, getAttribute: function() {}, src: __filename } } }, getElementsByTagName: function(tag) { // Return the fake head node if (tag === "head") { return [{ getElementsByTagName: function() { return [] } }] } return [] } } exports.location = { href: process.cwd() + "/index.js", search: "" } exports.navigator = { userAgent: "" } exports.console = console exports.process = process
/** * The fake sandbox of browser environment */ exports.document = { getElementById: function(id) { // Return the fake loader script node if (id === "seajsnode") { return { hasAttribute: true, getAttribute: function() {}, src: __filename } } }, getElementsByTagName: function(tag) { // Return the fake head node if (tag === "head") { return [{ getElementsByTagName: function() { return [] } }] } return [] } } exports.location = { href: __filename, search: "" } exports.navigator = { userAgent: "" } exports.console = console exports.process = process
Convert inline predicate to predicate generator
"use babel"; import _ from "lodash"; function isMappedToGrammer(grammar) { return (builder) => { console.log(builder); return _.includes(builder.grammars, grammar); }; } export default { activate() { this.commands = atom.commands.add("atom-workspace", { "gluon:build": () => { this.build(); }, }); }, deactivate() { this.commands.dispose(); }, build() { const builder = this.builderForActiveTextEditor(); if (!builder) { return; } builder.buildFunction(); }, provideBuildService() { const self = this; return { register(registration) { if (!registration) { return; } if (!self.builders) { self.builders = {}; } self.builders[registration.name] = registration; }, }; }, builderForActiveTextEditor() { const grammar = this.getActiveGrammar(); if (!grammar) { return null; } const builder = _.find(this.builders, isMappedToGrammer(grammar)); return builder; }, getActiveGrammar() { const editor = this.getActiveTextEditor(); if (editor) { return editor.getGrammar().scopeName; } return null; }, getActiveTextEditor() { return atom.workspace.getActiveTextEditor(); }, };
"use babel"; import _ from "lodash"; export default { activate() { this.commands = atom.commands.add("atom-workspace", { "gluon:build": () => { this.build(); }, }); }, deactivate() { this.commands.dispose(); }, build() { const builder = this.builderForActiveTextEditor(); if (!builder) { return; } builder.buildFunction(); }, provideBuildService() { const self = this; return { register(registration) { if (!registration) { return; } if (!self.builders) { self.builders = {}; } self.builders[registration.name] = registration; }, }; }, builderForActiveTextEditor() { const grammar = this.getActiveGrammar(); if (!grammar) { return null; } const isMappedToGrammer = (b) => { _.includes(b.grammars, grammar); }; const builder = _.find(this.builders, isMappedToGrammer); return builder; }, getActiveGrammar() { const editor = this.getActiveTextEditor(); if (editor) { return editor.getGrammar().scopeName; } return null; }, getActiveTextEditor() { return atom.workspace.getActiveTextEditor(); }, };
Update to React instead of react.
/** * Created by sbardian on 5/16/17. */ import { React } from 'react'; class openTrivia extends React.Component { constructor (props) { super(props); this.state = { test: 'test', } } componentWillReceiveProps (newProps) { // When component gets props } componentWillUnmount () { // When component mounts } render () { return ( <div> <div>This is a state ${this.state.test}</div> <div>This is a props ${this.props.test}</div> </div> ) } } openTrivia.propTypes = { // set default props the component will expect }; openTrivia.defaultProps = { // set value of default props test: 'test', }; export default openTrivia;
/** * Created by sbardian on 5/16/17. */ import react from 'react'; class openTrivia extends react.Component { constructor (props) { super(props); this.state = { test: 'test', } } componentWillReceiveProps (newProps) { // When component gets props } componentWillUnmount () { // When component mounts } render () { return ( <div> <div>This is a state ${this.state.test}</div> <div>This is a props ${this.props.test}</div> </div> ) } } openTrivia.propTypes = { // set default props the component will expect }; openTrivia.defaultProps = { // set value of default props test: 'test', }; export default openTrivia;
Add float extractor, fix extractors rules
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None extract_float = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() Ree._extract_float_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(sep=',.'): Ree.float = re.compile('(?P<float>-?\d+([{}]\d+)?)'.format(sep)) @staticmethod def _is_number(): Ree.number = re.compile('^-?\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>-?\d+).*$') @staticmethod def _extract_float_compile(sep=',.'): Ree.extract_float = re.compile('^.*?(?P<float>-?\d+([{}]\d+)?).*$'.format(sep))
# re_set.py # Module for generating regex rules # r1 import re class Ree: float = None number = None page_number = None extract_int = None @staticmethod def init(): Ree._is_float() Ree._is_number() Ree._is_page_number('') Ree._extract_int_compile() @staticmethod def _is_page_number(page_param): Ree.page_number = re.compile('(?P<param>{})=(?P<page>\d+)'.format(page_param)) @staticmethod def _is_float(price_sep=',.'): Ree.float = re.compile('(?P<price>-?\d+([{}]\d+)?)'.format(price_sep)) @staticmethod def _is_number(): Ree.number = re.compile('^\d+$') @staticmethod def _extract_int_compile(): Ree.extract_int = re.compile('^.*?(?P<int>\d+).+$')
Use event instead of e
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { console.log(event.target.value); this.setState({term: event.target.value}) } onFormSubmit(event) { event.preventDefault(); // need to fetch weather data this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Get a five day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { fetchWeather } from '../actions/index'; class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' }; this.onInputChange = this.onInputChange.bind(this); this.onFormSubmit = this.onFormSubmit.bind(this); } onInputChange(event) { console.log(event.target.value); this.setState({term: event.target.value}) } onFormSubmit(event) { e.preventDefault(); // need to fetch weather data this.props.fetchWeather(this.state.term); this.setState({ term: '' }); } render() { return ( <form onSubmit={this.onFormSubmit} className="input-group"> <input placeholder="Get a five day forecast in your favorite cities" className="form-control" value={this.state.term} onChange={this.onInputChange} /> <span className="input-group-btn"> <button type="submit" className="btn btn-secondary">Submit</button> </span> </form> ); } } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchWeather }, dispatch); } export default connect(null, mapDispatchToProps)(SearchBar);
Enable pending HTTP requests to get list of SAML2 identity providers.
import template from './auth-saml2-dialog.html'; const authSaml2Dialog = { template, bindings: { dismiss: '&', close: '&', }, controller: class AuthSaml2DialogController { // @ngInject constructor(Saml2Service, ncUtilsFlash, $rootScope) { this.Saml2Service = Saml2Service; this.ncUtilsFlash = ncUtilsFlash; this.$rootScope = $rootScope; } $onInit() { this.loginUrl = this.Saml2Service.getLoginUrl(); this.initialized = false; this.$rootScope.$broadcast('enableRequests'); this.refreshChoices().catch(() => { this.error = true; this.ncUtilsFlash.error(gettext('Could not load a list of identity providers. Please try again.')); }).finally(() => { this.initialized = true; }); } refreshChoices(name) { return this.Saml2Service.getProviders(name).then(response => { this.providers = response.data; }); } isProviderSelected() { return !!this.provider; } } }; export default authSaml2Dialog;
import template from './auth-saml2-dialog.html'; const authSaml2Dialog = { template, bindings: { dismiss: '&', close: '&', }, controller: class AuthSaml2DialogController { // @ngInject constructor($sce, ENV, Saml2Service, ncUtilsFlash) { this.Saml2Service = Saml2Service; this.ncUtilsFlash = ncUtilsFlash; } $onInit() { this.loginUrl = this.Saml2Service.getLoginUrl(); this.initialized = false; this.refreshChoices().then(() => { this.initialized = true; }).catch(() => { this.error = true; this.ncUtilsFlash.error(gettext('Could not load a list of identity providers. Please try again.')); }); } refreshChoices(name) { return this.Saml2Service.getProviders(name).then(response => { this.providers = response.data; }); } isProviderSelected() { return !!this.provider; } } }; export default authSaml2Dialog;
Implement express routes using app.get combining directory and filename location
// import necessary packages // path fs and express // create app // instantiate var app equal to express() // define view engine // app.set view engine to html // app.engine(html function(path options callbacks)) // fs. readfile(path standard utf 8 encoding and callback to be used on contents of file) // middle ware to accept requests and processes them // tell express to return static files at root folder where bundle.js exists // app.use express.static file path // routes // app.get at root '/' function(request response) // return index.html file using res.sendFile (path.join current path, and index html file) // error handler for other types of requests // app.use (function error, request, response, next) // if errors, respond with error status or 500 // server // tell server to run on some port e.g. 8000 // tell server to listen on that point // log message to console to confirm listening on port var path = require('path'); var fs = require('fs'); var express = require('express'); // create app var app = express(); // view engine app.set('view engine', 'html'); app.engine('html', function(path, options, callbacks){ fs.readFile(path, 'utf-8', callback); }); // middleware app.use(express.static(__dirname)); // routes app.get('/', function(req, res){ res.sendFile(path.join(__dirname, 'index.html')); });
// import necessary packages // path fs and express // create app // instantiate var app equal to express() // define view engine // app.set view engine to html // app.engine(html function(path options callbacks)) // fs. readfile(path standard utf 8 encoding and callback to be used on contents of file) // middle ware to accept requests and processes them // tell express to return static files at root folder where bundle.js exists // app.use express.static file path // routes // app.get at root '/' function(request response) // return index.html file using res.sendFile (path.join current path, and index html file) // error handler for other types of requests // app.use (function error, request, response, next) // if errors, respond with error status or 500 // server // tell server to run on some port e.g. 8000 // tell server to listen on that point // log message to console to confirm listening on port var path = require('path'); var fs = require('fs'); var express = require('express'); // create app var app = express(); // view engine app.set('view engine', 'html'); app.engine('html', function(path, options, callbacks){ fs.readFile(path, 'utf-8', callback); }); // middleware app.use(express.static(__dirname));
Remove the error suppression operator
<?php namespace Disque\Queue\Marshal; use Disque\Queue\Job; use Disque\Queue\JobInterface; /** * Serialize and deserialize the job body * * Serialize the job body when adding the job to the queue, * deserialize it and instantiate a new Job object when reading the job * from the queue. * * This marshaler uses JSON serialization for the whole Job body. */ class JobMarshaler implements MarshalerInterface { /** * @inheritdoc */ public function unmarshal($source) { $body = json_decode($source, true); if (is_null($body)) { throw new MarshalException("Could not deserialize {$source}"); } return new Job($body); } /** * @inheritdoc */ public function marshal(JobInterface $job) { return json_encode($job->getBody()); } }
<?php namespace Disque\Queue\Marshal; use Disque\Queue\Job; use Disque\Queue\JobInterface; /** * Serialize and deserialize the job body * * Serialize the job body when adding the job to the queue, * deserialize it and instantiate a new Job object when reading the job * from the queue. * * This marshaler uses JSON serialization for the whole Job body. */ class JobMarshaler implements MarshalerInterface { /** * @inheritdoc */ public function unmarshal($source) { $body = @json_decode($source, true); if (is_null($body)) { throw new MarshalException("Could not deserialize {$source}"); } return new Job($body); } /** * @inheritdoc */ public function marshal(JobInterface $job) { return json_encode($job->getBody()); } }
fix: Fix path to react-select css file
import React from 'react' import { render } from 'react-dom' import App from './app' import { navigate } from './api' import 'babel-polyfill' import 'react-datepicker/dist/react-datepicker.css' import 'react-select/dist/react-select.css' import './index.css' function init(element) { if (typeof element === 'string') { element = document.getElementById(element) } const style = document.createElement('style') style.id = 'ct-styles' document.head.appendChild(style) render(<App />, element) } document.addEventListener('DOMContentLoaded', () => { const element = document.querySelector('[data-endpoint]') if (element) { Cignium.init(element) const url = element.getAttribute('data-endpoint') if (url) { Cignium.navigate(url) } } }) export default { init, navigate, }
import React from 'react' import { render } from 'react-dom' import App from './app' import { navigate } from './api' import 'babel-polyfill' import 'react-datepicker/dist/react-datepicker.css' import 'react-select/dist/default.css' import './index.css' function init(element) { if (typeof element === 'string') { element = document.getElementById(element) } const style = document.createElement('style') style.id = 'ct-styles' document.head.appendChild(style) render(<App />, element) } document.addEventListener('DOMContentLoaded', () => { const element = document.querySelector('[data-endpoint]') if (element) { Cignium.init(element) const url = element.getAttribute('data-endpoint') if (url) { Cignium.navigate(url) } } }) export default { init, navigate, }
Revert "remove erroneous items() call" This reverts commit 8c6a79f668901dad2a0c47fa80a6ccbd1264066b.
class WitEmulator(object): def __init__(self): self.name='wit' def normalise_request_json(self,data): _data = {} _data["text"]=data['q'][0] return _data def normalise_response_json(self,data): print('plain response {0}'.format(data)) return [ { "_text": data["text"], "confidence": None, "intent": data["intent"], "entities" : {key:{"confidence":None,"type":"value","value":val} for key,val in data["entities"].items()} } ]
class WitEmulator(object): def __init__(self): self.name='wit' def normalise_request_json(self,data): _data = {} _data["text"]=data['q'][0] return _data def normalise_response_json(self,data): print('plain response {0}'.format(data)) return [ { "_text": data["text"], "confidence": None, "intent": data["intent"], "entities" : {key:{"confidence":None,"type":"value","value":val} for key,val in data["entities"]} } ]
Add source maps to tests
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine', 'browserify'], files: [ 'test/*' ], reporters: ['progress', 'coverage'], port: 9876, runnerPort: 9100, colors: true, logLevel: config.LOG_DEBUG, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: false, browserify: { watch: true, debug: true, transform: ['browserify-shim', 'browserify-istanbul'] }, preprocessors: { 'test/*': ['browserify'], 'lib/*': ['coverage'] }, coverageReporter: { type : 'html', dir : 'coverage/' } }); };
module.exports = function(config) { config.set({ basePath: '', frameworks: ['jasmine', 'browserify'], files: [ 'test/*' ], reporters: ['progress', 'coverage'], port: 9876, runnerPort: 9100, colors: true, logLevel: config.LOG_DEBUG, autoWatch: true, browsers: ['PhantomJS'], captureTimeout: 60000, singleRun: false, browserify: { watch: true, transform: ['browserify-shim', 'browserify-istanbul'] }, preprocessors: { 'test/*': ['browserify'], 'lib/*': ['coverage'] }, coverageReporter: { type : 'html', dir : 'coverage/' } }); };
Update pika requirement in /python_apps/airtime_analyzer Updates the requirements on [pika](https://github.com/pika/pika) to permit the latest version. - [Release notes](https://github.com/pika/pika/releases) - [Commits](https://github.com/pika/pika/compare/1.1.0...1.2.0) --- updated-dependencies: - dependency-name: pika dependency-type: direct:production ... Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>
import os from setuptools import setup # Change directory since setuptools uses relative paths os.chdir(os.path.dirname(os.path.realpath(__file__))) setup( name="libretime-analyzer", version="0.1", description="Libretime Analyzer Worker and File Importer", url="https://libretime.org", author="LibreTime Contributors", license="AGPLv3", packages=["airtime_analyzer"], entry_points={ "console_scripts": [ "libretime-analyzer=airtime_analyzer.cli:main", ] }, install_requires=[ "mutagen==1.42.0", "pika>=1.0.0", "file-magic", "requests>=2.7.0", "rgain3==1.0.0", "pycairo==1.19.1", ], zip_safe=False, )
import os from setuptools import setup # Change directory since setuptools uses relative paths os.chdir(os.path.dirname(os.path.realpath(__file__))) setup( name="libretime-analyzer", version="0.1", description="Libretime Analyzer Worker and File Importer", url="https://libretime.org", author="LibreTime Contributors", license="AGPLv3", packages=["airtime_analyzer"], entry_points={ "console_scripts": [ "libretime-analyzer=airtime_analyzer.cli:main", ] }, install_requires=[ "mutagen==1.42.0", "pika~=1.1.0", "file-magic", "requests>=2.7.0", "rgain3==1.0.0", "pycairo==1.19.1", ], zip_safe=False, )
Fix issue with test breaking when loading known hosts
package com.atsebak.raspberrypi.protocol.ssh; import lombok.Builder; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import java.io.IOException; @Builder public class SSH { private int timeout; private int connectionTimeout; /** * Build an SSHJ SSH Client * * @return */ public SSHClient toClient() { SSHClient sshClient = new SSHClient(); try { sshClient.addHostKeyVerifier(new PromiscuousVerifier()); sshClient.setConnectTimeout(connectionTimeout); sshClient.setTimeout(timeout); sshClient.loadKnownHosts(); } catch (IOException e) { } return sshClient; } }
package com.atsebak.raspberrypi.protocol.ssh; import lombok.Builder; import net.schmizz.sshj.SSHClient; import net.schmizz.sshj.transport.verification.PromiscuousVerifier; import java.io.IOException; @Builder public class SSH { private int timeout; private int connectionTimeout; /** * Build an SSHJ SSH Client * * @return */ public SSHClient toClient() { SSHClient sshClient = new SSHClient(); try { sshClient.addHostKeyVerifier(new PromiscuousVerifier()); sshClient.loadKnownHosts(); sshClient.setConnectTimeout(connectionTimeout); sshClient.setTimeout(timeout); } catch (IOException e) { } return sshClient; } }
Fix script name in instruction comment
<?php // A very simple helper script used to generate self-signed certificates. // Accepts the CN and an optional passphrase to encrypt the private key. // // $ php examples/99-generate-self-signed.php localhost swordfish > secret.pem // certificate details (Distinguished Name) // (OpenSSL applies defaults to missing fields) $dn = array( "commonName" => isset($argv[1]) ? $argv[1] : "localhost", // "countryName" => "AU", // "stateOrProvinceName" => "Some-State", // "localityName" => "London", // "organizationName" => "Internet Widgits Pty Ltd", // "organizationalUnitName" => "R&D", // "emailAddress" => "admin@example.com" ); // create certificate which is valid for ~10 years $privkey = openssl_pkey_new(); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 3650); // export public and (optionally encrypted) private key in PEM format openssl_x509_export($cert, $out); echo $out; $passphrase = isset($argv[2]) ? $argv[2] : null; openssl_pkey_export($privkey, $out, $passphrase); echo $out;
<?php // A very simple helper script used to generate self-signed certificates. // Accepts the CN and an optional passphrase to encrypt the private key. // // $ php 10-generate-self-signed.php localhost swordfish > secret.pem // certificate details (Distinguished Name) // (OpenSSL applies defaults to missing fields) $dn = array( "commonName" => isset($argv[1]) ? $argv[1] : "localhost", // "countryName" => "AU", // "stateOrProvinceName" => "Some-State", // "localityName" => "London", // "organizationName" => "Internet Widgits Pty Ltd", // "organizationalUnitName" => "R&D", // "emailAddress" => "admin@example.com" ); // create certificate which is valid for ~10 years $privkey = openssl_pkey_new(); $cert = openssl_csr_new($dn, $privkey); $cert = openssl_csr_sign($cert, null, $privkey, 3650); // export public and (optionally encrypted) private key in PEM format openssl_x509_export($cert, $out); echo $out; $passphrase = isset($argv[2]) ? $argv[2] : null; openssl_pkey_export($privkey, $out, $passphrase); echo $out;
Fix resource loading on android
package org.javarosa.core.model.instance.utils; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Collection of static form loading methods * * @author Phillip Mates */ public class FormLoadingUtils { public static FormInstance loadFormInstance(String formFilepath) throws InvalidStructureException, IOException { TreeElement root = xmlToTreeElement(formFilepath); return new FormInstance(root, null); } public static TreeElement xmlToTreeElement(String xmlFilepath) throws InvalidStructureException, IOException { InputStream is = FormLoadingUtils.class.getResourceAsStream(xmlFilepath); TreeElementParser parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); try { return parser.parse(); } catch (XmlPullParserException e) { throw new IOException(e.getMessage()); } catch (UnfullfilledRequirementsException e) { throw new IOException(e.getMessage()); } } }
package org.javarosa.core.model.instance.utils; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.model.instance.TreeElement; import org.javarosa.xml.ElementParser; import org.javarosa.xml.TreeElementParser; import org.javarosa.xml.util.InvalidStructureException; import org.javarosa.xml.util.UnfullfilledRequirementsException; import org.xmlpull.v1.XmlPullParserException; import java.io.IOException; import java.io.InputStream; /** * Collection of static form loading methods * * @author Phillip Mates */ public class FormLoadingUtils { public static FormInstance loadFormInstance(String formFilepath) throws InvalidStructureException, IOException { TreeElement root = xmlToTreeElement(formFilepath); return new FormInstance(root, null); } public static TreeElement xmlToTreeElement(String xmlFilepath) throws InvalidStructureException, IOException { InputStream is = System.class.getResourceAsStream(xmlFilepath); TreeElementParser parser = new TreeElementParser(ElementParser.instantiateParser(is), 0, "instance"); try { return parser.parse(); } catch (XmlPullParserException e) { throw new IOException(e.getMessage()); } catch (UnfullfilledRequirementsException e) { throw new IOException(e.getMessage()); } } }
Increase archive record limit to 10000 for demo to allow reduction information to be seen
const knex = require('../../../knex').archive module.exports = function () { var selectColumns = [ 'unique_identifier AS uniqueIdentifier', 'ldu_name AS lduName', 'team_name AS teamName', 'om_name AS omName', 'total_cases AS totalCases', 'total_points AS totalPoints', 'sdr_points AS sdrPoints', 'sdr_conversion_points AS sdrConversionPoints', 'paroms_points AS paromsPoints', 'nominal_target AS nominalTarget', 'contracted_hours AS contractedHours', 'hours_reduction AS hoursReduction', 'reduction', 'comments', 'om_type_id AS omTypeId' ] return knex.raw('SELECT TOP 10000 ' + selectColumns.join(', ') + ' FROM archive_view') }
const knex = require('../../../knex').archive module.exports = function () { var selectColumns = [ 'unique_identifier AS uniqueIdentifier', 'ldu_name AS lduName', 'team_name AS teamName', 'om_name AS omName', 'total_cases AS totalCases', 'total_points AS totalPoints', 'sdr_points AS sdrPoints', 'sdr_conversion_points AS sdrConversionPoints', 'paroms_points AS paromsPoints', 'nominal_target AS nominalTarget', 'contracted_hours AS contractedHours', 'hours_reduction AS hoursReduction', 'reduction', 'comments', 'om_type_id AS omTypeId' ] return knex.raw('SELECT TOP 100 ' + selectColumns.join(', ') + ' FROM archive_view') }
Make "clean" command work again
const fs = require('fs') const path = require('path') exports.exists = function (path) { try { fs.statSync(path) return true } catch (err) { return false } } exports.deleteDir = function (filePath, leaveDist, callback) { const me = this; fs.readdirSync(filePath).forEach(function (file, index) { var curPath = filePath + '/' + file const details = path.parse(curPath) if (fs.statSync(curPath).isDirectory()) { if (details.name !== '.git') { me.deleteDir(curPath) } } else if (details.base !== '.gitignore') { fs.unlinkSync(curPath) } }) if (!leaveDist) { fs.unlinkSync(filePath + '/.gitignore') fs.rmdirSync(filePath) } if (typeof(callback) == 'function') { callback() } } exports.isSite = function () { const pkgPath = process.cwd() + '/package.json' if (!exports.exists(pkgPath)) { return false } const package = require(pkgPath) if (!package.scripts || !package.scripts.start) { return false } const startScript = package.scripts.start return startScript.includes('cory') }
const fs = require('fs') const path = require('path') exports.exists = function (path) { try { fs.statSync(path) return true } catch (err) { return false } } exports.deleteDir = function (filePath, leaveDist, callback) { const me = this; fs.readdirSync(filePath).forEach(function (file, index) { var curPath = filePath + '/' + file const details = path.parse(curPath) if (fs.statSync(curPath).isDirectory()) { if (details.name !== '.git') { me.deleteDir(curPath) } } else if (details.base !== '.gitignore') { fs.unlinkSync(curPath) } }) if (!leaveDist) { fs.rmdirSync(filePath) } if (typeof(callback) == 'function') { callback() } } exports.isSite = function () { const pkgPath = process.cwd() + '/package.json' if (!exports.exists(pkgPath)) { return false } const package = require(pkgPath) if (!package.scripts || !package.scripts.start) { return false } const startScript = package.scripts.start return startScript.includes('cory') }
Call to parent does not need to use classname
<?php namespace UCD\Infrastructure\Repository\CharacterRepository\FileRepository\RangeFile; use IntervalTree\IntervalTree as BaseIntervalTree; use UCD\Infrastructure\Repository\CharacterRepository\FileRepository\Range; class IntervalTree extends BaseIntervalTree { /** * @var Range[] */ protected $ranges = []; /** * @param Range[] $ranges * @param callable|null $comparator */ public function __construct(array $ranges, callable $comparator = null) { $this->ranges = $ranges; parent::__construct($ranges, $comparator); } /** * @param Range $range */ public function add(Range $range) { $this->ranges[] = $range; $this->top_node = $this->divide_intervals($this->ranges); } }
<?php namespace UCD\Infrastructure\Repository\CharacterRepository\FileRepository\RangeFile; use IntervalTree\IntervalTree as BaseIntervalTree; use UCD\Infrastructure\Repository\CharacterRepository\FileRepository\Range; class IntervalTree extends BaseIntervalTree { /** * @var Range[] */ protected $ranges = []; /** * @param Range[] $ranges * @param callable|null $comparator */ public function __construct(array $ranges, callable $comparator = null) { $this->ranges = $ranges; BaseIntervalTree::__construct($ranges, $comparator); } /** * @param Range $range */ public function add(Range $range) { $this->ranges[] = $range; $this->top_node = $this->divide_intervals($this->ranges); } }
Add update to usermodel upon signup with register controller
(function(){ 'use strict'; angular .module('secondLead') .controller('RegisterCtrl', [ 'Restangular', '$state', 'store', 'UserModel', function (Restangular, $state, store, UserModel) { var register = this; register.newUser = {}; register.onSubmit = function () { UserModel.register(register.newUser) .then(function(response){ if (response.errors){ register.error = response.errors[0]; } else { UserModel.setLoggedIn(true); store.set('jwt',response.token); store.set('user',response.user); $state.go('user.lists', {userID: response.user.id}); register.reset(); } }); }; register.reset = function () { register.newUser = {}; }; }]) })();
(function(){ 'use strict'; angular .module('secondLead') .controller('RegisterCtrl', [ 'Restangular', '$state', 'store', 'UserModel', function (Restangular, $state, store, UserModel) { var register = this; register.newUser = {}; register.onSubmit = function () { UserModel.register(register.newUser) .then(function(response){ if (response.errors){ register.error = response.errors[0]; } else { store.set('jwt',response.token); store.set('user',response.user); $state.go('user.lists', {userID: response.user.id}); register.reset(); } }); }; register.reset = function () { register.newUser = {}; }; }]) })();
Handle more signals to make ParseSignal containerd compatible We'd like to use moby/sys/signal in containerd, but containerd currently supports more signals. Adding them here closes the gap. Signed-off-by: Kazuyoshi Kato <732288c132d39c7d9231a005036e5ecd0fff1d64@amazon.com>
package signal import ( "syscall" "golang.org/x/sys/windows" ) // Signals used in cli/command (no windows equivalent, use // invalid signals so they don't get handled) const ( SIGCHLD = syscall.Signal(0xff) SIGWINCH = syscall.Signal(0xff) SIGPIPE = syscall.Signal(0xff) // DefaultStopSignal is the syscall signal used to stop a container in windows systems. DefaultStopSignal = "15" ) // SignalMap is a map of "supported" signals. As per the comment in GOLang's // ztypes_windows.go: "More invented values for signals". Windows doesn't // really support signals in any way, shape or form that Unix does. var SignalMap = map[string]syscall.Signal{ "HUP": syscall.Signal(windows.SIGHUP), "INT": syscall.Signal(windows.SIGINT), "QUIT": syscall.Signal(windows.SIGQUIT), "ILL": syscall.Signal(windows.SIGILL), "TRAP": syscall.Signal(windows.SIGTRAP), "ABRT": syscall.Signal(windows.SIGABRT), "BUS": syscall.Signal(windows.SIGBUS), "FPE": syscall.Signal(windows.SIGFPE), "KILL": syscall.Signal(windows.SIGKILL), "SEGV": syscall.Signal(windows.SIGSEGV), "PIPE": syscall.Signal(windows.SIGPIPE), "ALRM": syscall.Signal(windows.SIGALRM), "TERM": syscall.Signal(windows.SIGTERM), }
package signal import ( "syscall" ) // Signals used in cli/command (no windows equivalent, use // invalid signals so they don't get handled) const ( SIGCHLD = syscall.Signal(0xff) SIGWINCH = syscall.Signal(0xff) SIGPIPE = syscall.Signal(0xff) // DefaultStopSignal is the syscall signal used to stop a container in windows systems. DefaultStopSignal = "15" ) // SignalMap is a map of "supported" signals. As per the comment in GOLang's // ztypes_windows.go: "More invented values for signals". Windows doesn't // really support signals in any way, shape or form that Unix does. // // We have these so that docker kill can be used to gracefully (TERM) and // forcibly (KILL) terminate a container on Windows. var SignalMap = map[string]syscall.Signal{ "KILL": syscall.SIGKILL, "TERM": syscall.SIGTERM, }
Add better fix for handling invalid markdown inputs
import { node, object, oneOfType, string } from 'prop-types' import Bit from './Bit' import Code from './Code' import HTML from 'html-parse-stringify' import React from 'react' import reactify from '../util/reactify' import Image from './Image' import Rule from './Rule' import Paragraph from './Paragraph' const DEFAULT_MAPPINGS = { // TODO: Add stemcell components and add API endpoint for end-user mappings code: Code, hr: Rule, img: Image, p: Paragraph } // TODO: Move this to optional package? const ComponentizeContent = ({ children, ...props }) => { if (!children) { return null } if (typeof children !== 'string') { return children } const ast = HTML.parse(`<div>${children}</div>`) const reparsedAst = reactify(ast, { mappings: DEFAULT_MAPPINGS }) return ( <Bit {...props}> {reparsedAst} </Bit> ) } ComponentizeContent.propTypes = { children: node, className: oneOfType([object, string]) } export default ComponentizeContent
import { node, object, oneOfType, string } from 'prop-types' import Bit from './Bit' import Code from './Code' import HTML from 'html-parse-stringify' import React from 'react' import reactify from '../util/reactify' import Image from './Image' import Rule from './Rule' import Paragraph from './Paragraph' const DEFAULT_MAPPINGS = { // TODO: Add stemcell components and add API endpoint for end-user mappings code: Code, hr: Rule, img: Image, p: Paragraph } // TODO: Move this to optional package? const ComponentizeContent = ({ children, ...props }) => { if (!children || typeof children !== 'string') { return children } const ast = HTML.parse(`<div>${children}</div>`) const reparsedAst = reactify(ast, { mappings: DEFAULT_MAPPINGS }) return ( <Bit {...props}> {reparsedAst} </Bit> ) } ComponentizeContent.propTypes = { children: node, className: oneOfType([object, string]) } export default ComponentizeContent
Fix NR deploy notification bug
""" Management command to enable New Relic notification of deployments .. moduleauthor:: Infoxchange Development Team <development@infoxchange.net.au> """ import os from subprocess import call, Popen, PIPE from django.conf import settings from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): """ Notify New Relic of the new version """ def handle_noargs(self, **options): # get the current git version git = Popen(('git', 'describe'), stdout=PIPE) ver, _ = git.communicate() ver = ver.strip() # The the tagger name and email git = Popen(('git', 'log', ver, '--format=%ae', '-1'), stdout=PIPE) username, _ = git.communicate() username = username.strip() try: ini_file = os.environ['NEW_RELIC_CONFIG_FILE'] except KeyError: ini_file = settings.NEW_RELIC_CONFIG print "Informing New Relic...", call(['newrelic-admin', 'record-deploy', ini_file, ver, # description ver, # revision '', # changelog username])
""" Management command to enable New Relic notification of deployments .. moduleauthor:: Infoxchange Development Team <development@infoxchange.net.au> """ import os from subprocess import call, Popen, PIPE from django.conf import settings from django.core.management.base import NoArgsCommand class Command(NoArgsCommand): """ Notify New Relic of the new version """ def handle_noargs(self, **options): # get the current git version git = Popen(('git', 'describe'), stdout=PIPE) ver, _ = git.communicate() ver = ver.strip() # The the tagger name and email git = Popen(('git', 'log', ver, '--format=%ae', '-1'), stdout=PIPE) username, _ = git.communicate() username = username.strip() ini_file = os.environ.get('NEW_RELIC_CONFIG_FILE', settings.NEW_RELIC_CONFIG) print "Informing New Relic...", call(['newrelic-admin', 'record-deploy', ini_file, ver, # description ver, # revision '', # changelog username])
Change init() to initNote() to handle each note
$(document).foundation() context = new AudioContext() // declare globals var note, volume = context.createGain() // initialize volume volume.gain.value = 0.1 function initNote(freq) { note = context.createOscillator() note.type = 'sawtooth' note.frequency.value = freq note.connect(volume) volume.connect(context.destination) } function startSaw() { initNote(440) note.start(0) } function stopSaw() { note.stop() } // Gain input event changes level from 0 to 1 $('#gain').on('input',function(e){ gain = $("#gain").val() volume.gain.value = gain }); // test keypress 'a' $(document).keydown(function(e) { if (e.which == 65) { startSaw() } });
$(document).foundation() context = new AudioContext() // declare globals var saw, volume = context.createGain() // initialize volume volume.gain.value = 0.1 function init() { saw = context.createOscillator() saw.type = 'sawtooth' saw.frequency.value = 440 // set the frequency to 440 HZ saw.connect(volume) volume.connect(context.destination) } function startSaw() { saw.start(0) } function stopSaw() { saw.stop() } // Gain input event changes level from 0 to 1 $('#gain').on('input',function(e){ gain = $("#gain").val() volume.gain.value = gain }); // test keypress 'a' $(document).keydown(function(e) { if (e.which == 65) { startSaw() } }); init()
Use sprintf for string construction
<?php namespace Dock\System\Environ; use Dock\IO\ProcessRunner; use Symfony\Component\Process\Process; class BashEnvironManipulator implements EnvironManipulator { /** * @var string */ private $file; /** * @var ProcessRunner */ private $processRunner; /** * @param string $file */ public function __construct(ProcessRunner $processRunner, $file) { $this->file = $file; $this->processRunner = $processRunner; } /** * {@inheritdoc} */ public function save(EnvironmentVariable $environmentVariable) { $command = 'echo "' . $environmentVariable->getName() . '=' . $environmentVariable->getValue( ) . '" >> ' . $this->file; $process = new Process($command); $this->processRunner->run($process); } /** * {@inheritdoc} */ public function has(EnvironmentVariable $environmentVariable) { $process = $this->processRunner->run( new Process(sprintf('grep %s %s', $environmentVariable->getName(), $this->file)), false ); $result = $process->getOutput(); return !empty($result); } }
<?php namespace Dock\System\Environ; use Dock\IO\ProcessRunner; use Symfony\Component\Process\Process; class BashEnvironManipulator implements EnvironManipulator { /** * @var string */ private $file; /** * @var ProcessRunner */ private $processRunner; /** * @param string $file */ public function __construct(ProcessRunner $processRunner, $file) { $this->file = $file; $this->processRunner = $processRunner; } /** * {@inheritdoc} */ public function save(EnvironmentVariable $environmentVariable) { $command = 'echo "'.$environmentVariable->getName().'='.$environmentVariable->getValue().'" >> '.$this->file; $process = new Process($command); $this->processRunner->run($process); } /** * {@inheritdoc} */ public function has(EnvironmentVariable $environmentVariable) { $process = $this->processRunner->run( new Process("grep {$environmentVariable->getName()} $this->file"), false ); $result = $process->getOutput(); return !empty($result); } }
Update webpack to 3rd version
const webpack = require('webpack') const plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), __DEV__: process.env.NODE_ENV === 'development', __TEST__: process.env.NODE_ENV === 'test' }) ] if (process.env.NODE_ENV === 'production') { plugins.push(new webpack.optimize.UglifyJsPlugin()) } module.exports = { entry: './src/index.js', output: { filename: 'dist/bundle.js', library: 'cssVendor', libraryTarget: 'umd' }, plugins, module: { loaders: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/ }, { loader: 'json-loader', test: /\.json$/ } ] }, node: { fs: 'empty', } }
const webpack = require('webpack') const plugins = [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV), __DEV__: process.env.NODE_ENV === 'development', __TEST__: process.env.NODE_ENV === 'test' }) ] if (process.env.NODE_ENV === 'production') { plugins.push(new webpack.optimize.UglifyJsPlugin()) } module.exports = { output: { library: 'cssVendor', libraryTarget: 'umd' }, plugins: plugins, module: { loaders: [ { loader: 'babel-loader', test: /\.js$/, exclude: /node_modules/ }, { loader: 'json-loader', test: /\.json$/ } ] }, node: { fs: "empty", } }
Add key to homepage tile items to satisfy react
import React from 'react'; import { Link } from 'react-router'; import HomepageTile from './homepage-tile.js'; import chaptersData from './chapter-data.js'; // Clone the chapters since sort mutates the array const chapters = [...chaptersData] .filter(chapter => !chapter.hidden) .sort((chapterA, chapterB) => chapterA.number - chapterB.number); const HomePage = React.createClass({ render: function() { return ( <div className="container homepage"> <div className="pure-g row-gap-small"> <div className="pure-u-1"> <h2>Grade 6 Science</h2> </div> </div> <div className="pure-g"> {chapters.map((chapter, index) => ( <HomepageTile key={index} imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} /> ))} </div> {this.props.children} </div> ); } }); export default HomePage;
import React from 'react'; import { Link } from 'react-router'; import HomepageTile from './homepage-tile.js'; import chaptersData from './chapter-data.js'; // Clone the chapters since sort mutates the array const chapters = [...chaptersData] .filter(chapter => !chapter.hidden) .sort((chapterA, chapterB) => chapterA.number - chapterB.number); const HomePage = React.createClass({ render: function() { return ( <div className="container homepage"> <div className="pure-g row-gap-small"> <div className="pure-u-1"> <h2>Grade 6 Science</h2> </div> </div> <div className="pure-g"> {chapters.map(chapter => ( <HomepageTile imagePath={chapter.thumbnailImagePath} chapterNumber={chapter.number} title={chapter.title} /> ))} </div> {this.props.children} </div> ); } }); export default HomePage;
Make sure env.Path === env.PATH on Windows.
var path = require("path"); var devBundleDir = path.resolve(__dirname, "..", "..", "dev_bundle"); var binDir = path.join(devBundleDir, "bin"); exports.getCommandPath = function (command) { return path.join(binDir, command); }; exports.getEnv = function () { var env = Object.create(process.env); var paths = [ // When npm looks for node, it must find dev_bundle/bin/node. binDir, // Also make available any scripts installed by packages in // dev_bundle/lib/node_modules, such as node-gyp. path.join(devBundleDir, "lib", "node_modules", ".bin"), ]; var PATH = env.PATH || env.Path; if (PATH) { paths.push(PATH); } env.PATH = paths.join(path.delimiter); if (process.platform === "win32") { // On Windows we provide a reliable version of python.exe for use by // node-gyp (the tool that rebuilds binary node modules). #WinPy env.PYTHON = env.PYTHON || path.join( devBundleDir, "python", "python.exe"); // We don't try to install a compiler toolchain on the developer's // behalf, but setting GYP_MSVS_VERSION helps select the right one. env.GYP_MSVS_VERSION = env.GYP_MSVS_VERSION || "2015"; // While the original process.env object allows for case insensitive // access on Windows, Object.create interferes with that behavior, so // here we ensure env.PATH === env.Path on Windows. env.Path = env.PATH; } return env; };
var path = require("path"); var devBundleDir = path.resolve(__dirname, "..", "..", "dev_bundle"); var binDir = path.join(devBundleDir, "bin"); exports.getCommandPath = function (command) { return path.join(binDir, command); }; exports.getEnv = function () { var env = Object.create(process.env); env.PATH = [ // When npm looks for node, it must find dev_bundle/bin/node. binDir, // Also make available any scripts installed by packages in // dev_bundle/lib/node_modules, such as node-gyp. path.join(devBundleDir, "lib", "node_modules", ".bin"), env.PATH ].join(path.delimiter); if (process.platform === "win32") { // On Windows we provide a reliable version of python.exe for use by // node-gyp (the tool that rebuilds binary node modules). #WinPy env.PYTHON = env.PYTHON || path.join( devBundleDir, "python", "python.exe"); // We don't try to install a compiler toolchain on the developer's // behalf, but setting GYP_MSVS_VERSION helps select the right one. env.GYP_MSVS_VERSION = env.GYP_MSVS_VERSION || "2015"; } return env; };
Add reverse migration for new groups
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') def remove_groups(*args): Group.objects.filter(name='nodes_and_users').delete() group = Group.objects.get(name='prereg') group.name = 'prereg_group' group.save() class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups, remove_groups), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: logger.info('nodes_and_users group created') try: group = Group.objects.get(name='prereg_group') group.name = 'prereg' group.save() logger.info('prereg_group renamed to prereg') except Group.DoesNotExist: group, created = Group.objects.get_or_create(name='prereg') if created: logger.info('prereg group created') class Migration(migrations.Migration): dependencies = [ ('base', '0001_groups'), ] operations = [ migrations.RunPython(add_groups), ]
structures: Raise more appropriate UnknownStructure exception rather than StructureError if a structure is not found.
#!/usr/bin/python # -*- coding: utf-8 -*- from .base import DBStructure, _Generated from .files.main import * from .files.custom import * from ..locales import L class UnknownStructure(Exception): pass class StructureLoader(): wowfiles = None @classmethod def setup(cls): if cls.wowfiles is None: cls.wowfiles = {} for name in globals(): try: if not issubclass(globals()[name], DBStructure): continue except TypeError: continue cls.wowfiles[name.lower()] = globals()[name] @classmethod def getstructure(cls, name, build=0, parent=None): if name in cls.wowfiles: return cls.wowfiles[name](build, parent) raise UnknownStructure(L["STRUCTURE_NOT_FOUND"] % name) StructureLoader.setup() getstructure = StructureLoader.getstructure
#!/usr/bin/python # -*- coding: utf-8 -*- from .base import DBStructure, _Generated from .files.main import * from .files.custom import * from ..locales import L class StructureError(Exception): pass class StructureLoader(): wowfiles = None @classmethod def setup(cls): if cls.wowfiles is None: cls.wowfiles = {} for name in globals(): try: if not issubclass(globals()[name], DBStructure): continue except TypeError: continue cls.wowfiles[name.lower()] = globals()[name] @classmethod def getstructure(cls, name, build=0, parent=None): if name in cls.wowfiles: return cls.wowfiles[name](build, parent) raise StructureError(L["STRUCTURE_NOT_FOUND"] % name) StructureLoader.setup() getstructure = StructureLoader.getstructure
Fix spelling error on core published PublishableMnager to PublishableManager
#!/usr/bin/env python from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from opps.core.models.date import Date from datetime import datetime class PublishableManager(models.Manager): def all_published(self): return super(PublishableManager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Publishable(Date): user = models.ForeignKey(settings.AUTH_USER_MODEL) site = models.ForeignKey(Site, default=0) date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublishableManager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
#!/usr/bin/env python from django.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.sites.models import Site from opps.core.models.date import Date from datetime import datetime class PublishableMnager(models.Manager): def all_published(self): return super(PublishableMnager, self).get_query_set().filter( date_available__lte=datetime.now(), published=True) class Publishable(Date): user = models.ForeignKey(settings.AUTH_USER_MODEL) site = models.ForeignKey(Site, default=0) date_available = models.DateTimeField(_(u"Date available"), default=datetime.now, null=True) published = models.BooleanField(_(u"Published"), default=False) objects = PublishableMnager() class Meta: abstract = True def is_published(self): return self.published and \ self.date_available.replace(tzinfo=None) <= datetime.now()
Add a link to home in the menu
import React from 'react' import { Link } from 'react-router' //TODO config routes for GSIM and GSBPM explorers in the dedictated file export default function App({ children }) { return ( <div className="container-fluid"> <header> <div> <Link to="/">Home</Link> </div> <div> Explore with: <ul> <li> <Link to="/gsbpm">GSBPM</Link> </li> <li> <Link to="/gsim">GSIM</Link> </li> </ul> </div> </header> <h1>Model Explorer</h1> {/* Children is a special prop name with react. Here, it allows `react-router` to populate our main component with the components that match the route */} { children } </div> ) }
import React from 'react' import { Link } from 'react-router' //TODO config routes for GSIM and GSBPM explorers in the dedictated file export default function App({ children }) { return ( <div className="container-fluid"> <header> Explore with: <ul> <li> <Link to="/gsbpm">GSBPM</Link> </li> <li> <Link to="/gsim">GSIM</Link> </li> </ul> </header> <h1>Model Explorer</h1> {/* Children is a special prop name with react. Here, it allows `react-router` to populate our main component with the components that match the route */} { children } </div> ) }
Fix temperature using salinity config
package mariculture.fishery.fish.dna; import mariculture.api.fishery.fish.FishDNA; import mariculture.api.fishery.fish.FishSpecies; import mariculture.core.config.FishMechanics.FussyFish; import net.minecraft.item.ItemStack; public class FishDNATemperatureTolerance extends FishDNA { @Override public Integer getDNAFromSpecies(FishSpecies species) { return Math.max(0, species.getTemperatureTolerance()); } @Override public int getCopyChance() { return 35; } public Integer sanitize(Integer i) { return Math.min(100, Math.max(0, i)); } @Override public Integer getDNA(ItemStack stack) { return sanitize(super.getDNA(stack) + FussyFish.TEMP_TOLERANCE_BOOSTER); } @Override public Integer getLowerDNA(ItemStack stack) { return sanitize(super.getLowerDNA(stack) + FussyFish.TEMP_TOLERANCE_BOOSTER); } }
package mariculture.fishery.fish.dna; import mariculture.api.fishery.fish.FishDNA; import mariculture.api.fishery.fish.FishSpecies; import mariculture.core.config.FishMechanics.FussyFish; import net.minecraft.item.ItemStack; public class FishDNATemperatureTolerance extends FishDNA { @Override public Integer getDNAFromSpecies(FishSpecies species) { return Math.max(0, species.getTemperatureTolerance()); } @Override public int getCopyChance() { return 35; } public Integer sanitize(Integer i) { return Math.min(100, Math.max(0, i)); } @Override public Integer getDNA(ItemStack stack) { return sanitize(super.getDNA(stack) + FussyFish.SALINITY_TOLERANCE_BOOSTER); } @Override public Integer getLowerDNA(ItemStack stack) { return sanitize(super.getLowerDNA(stack) + FussyFish.SALINITY_TOLERANCE_BOOSTER); } }
Fix relative import (compatible with p3
import os from binstar_client import errors from .uploader import * def parse(handle): """ Handle can take the form of: notebook path/to/notebook[.ipynb] project:notebook[.ipynb] :param handle: String :return: (project, notebook) :raises: NotebookNotFound """ if ':' in handle: project, filepath = handle.split(':', 1) else: project = None filepath = handle if not filepath.endswith('.ipynb'): filepath += '.ipynb' if not os.path.isfile(filepath): raise errors.NotebookNotExist(filepath) notebook = os.path.splitext(os.path.basename(filepath))[0] if project is None: project = notebook return project, notebook
import os from binstar_client import errors from uploader import * def parse(handle): """ Handle can take the form of: notebook path/to/notebook[.ipynb] project:notebook[.ipynb] :param handle: String :return: (project, notebook) :raises: NotebookNotFound """ if ':' in handle: project, filepath = handle.split(':', 1) else: project = None filepath = handle if not filepath.endswith('.ipynb'): filepath += '.ipynb' if not os.path.isfile(filepath): raise errors.NotebookNotExist(filepath) notebook = os.path.splitext(os.path.basename(filepath))[0] if project is None: project = notebook return project, notebook
Set default HAproxy to 1.7.2-k8s
package options import ( "github.com/spf13/pflag" ) type Config struct { Master string KubeConfig string ProviderName string ClusterName string LoadbalancerImageName string } func NewConfig() *Config { return &Config{ Master: "", KubeConfig: "", ProviderName: "", ClusterName: "", LoadbalancerImageName: "appscode/haproxy:1.7.2-k8s", } } func (s *Config) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)") fs.StringVar(&s.KubeConfig, "kubeconfig", s.KubeConfig, "Path to kubeconfig file with authorization information (the master location is set by the master flag).") fs.StringVarP(&s.ProviderName, "cloud-provider", "c", s.ProviderName, "Name of cloud provider") fs.StringVarP(&s.ClusterName, "cluster-name", "k", s.ClusterName, "Name of Kubernetes cluster") fs.StringVarP(&s.LoadbalancerImageName, "haproxy-image", "h", s.LoadbalancerImageName, "haproxy image name to be run") }
package options import ( "github.com/spf13/pflag" ) type Config struct { Master string KubeConfig string ProviderName string ClusterName string LoadbalancerImageName string } func NewConfig() *Config { return &Config{ Master: "", KubeConfig: "", ProviderName: "", ClusterName: "", LoadbalancerImageName: "appscode/haproxy:1.7.0-k8s", } } func (s *Config) AddFlags(fs *pflag.FlagSet) { fs.StringVar(&s.Master, "master", s.Master, "The address of the Kubernetes API server (overrides any value in kubeconfig)") fs.StringVar(&s.KubeConfig, "kubeconfig", s.KubeConfig, "Path to kubeconfig file with authorization information (the master location is set by the master flag).") fs.StringVarP(&s.ProviderName, "cloud-provider", "c", s.ProviderName, "Name of cloud provider") fs.StringVarP(&s.ClusterName, "cluster-name", "k", s.ClusterName, "Name of Kubernetes cluster") fs.StringVarP(&s.LoadbalancerImageName, "haproxy-image", "h", s.LoadbalancerImageName, "haproxy image name to be run") }
Use new multiple cmd contexts
require("./stylesheets/main.less"); var marked = require("marked"); var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "markdown.preview", title: "Markdown: Preview", context: ["editor"], run: function(args, ctx) { return codebox.tabs.add(codebox.tabs.HtmlPanel, { className: "component-markdown-preview", content: marked(ctx.editor.getContent()) }, { type: "markdown", title: "Markdown: " + ctx.editor.model.get("name"), section: "markdown" }); } });
require("./stylesheets/main.less"); var marked = require("marked"); var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "markdown.preview", title: "Markdown: Preview", context: ["editor"], run: function(args, context) { return codebox.tabs.add(codebox.tabs.HtmlPanel, { className: "component-markdown-preview", content: marked(context.getContent()) }, { type: "markdown", title: "Markdown: " + context.model.get("name"), section: "markdown" }); } });
Fix typo from bad conflict resolution during merge
import core from girder_worker.utils import JobStatus from .app import app def _cleanup(*args, **kwargs): core.events.trigger('cleanup') @app.task(name='girder_worker.run', bind=True, after_return=_cleanup) def run(task, *pargs, **kwargs): kwargs['_job_manager'] = task.job_manager \ if hasattr(task, 'job_manager') else None kwargs['status'] = JobStatus.RUNNING return core.run(*pargs, **kwargs) @app.task(name='girder_worker.convert') def convert(*pargs, **kwargs): return core.convert(*pargs, **kwargs) @app.task(name='girder_worker.validators') def validators(*pargs, **kwargs): _type, _format = pargs nodes = [] for (node, data) in core.format.conv_graph.nodes(data=True): if ((_type is None) or (_type == node.type)) and \ ((_format is None) or (_format == node.format)): nodes.append({'type': node.type, 'format': node.format, 'validator': data}) return nodes
import core from girder_worker.utils import JobStatus from .app import app def _cleanup(*args, **kwargs): core.events.trigger('cleanup') @app.task(name='girder_worker.run', bind=True, after_return=_cleanup) def run(tasks, *pargs, **kwargs): jobInfo = kwargs.pop('jobInfo', {}) retval = 0 kwargs['_job_manager'] = task.job_manager \ if hasattr(task, 'job_manager') else None kwargs['status'] = JobStatus.RUNNING return core.run(*pargs, **kwargs) @app.task(name='girder_worker.convert') def convert(*pargs, **kwargs): return core.convert(*pargs, **kwargs) @app.task(name='girder_worker.validators') def validators(*pargs, **kwargs): _type, _format = pargs nodes = [] for (node, data) in core.format.conv_graph.nodes(data=True): if ((_type is None) or (_type == node.type)) and \ ((_format is None) or (_format == node.format)): nodes.append({'type': node.type, 'format': node.format, 'validator': data}) return nodes
Make sure celery_teardown_request gets called in DraftReg auto-approve script [skip ci]
""" A script for testing DraftRegistrationApprovals. Automatically approves all pending DraftRegistrationApprovals. """ import sys import logging from framework.tasks.handlers import celery_teardown_request from website.app import init_app from website.project.model import DraftRegistration, Sanction logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) logging.disable(level=logging.INFO) def main(dry_run=True): if dry_run: logger.warn('DRY RUN mode') pending_approval_drafts = DraftRegistration.find() need_approval_drafts = [draft for draft in pending_approval_drafts if draft.approval and draft.requires_approval and draft.approval.state == Sanction.UNAPPROVED] for draft in need_approval_drafts: sanction = draft.approval try: if not dry_run: sanction.state = Sanction.APPROVED sanction._on_complete(None) sanction.save() logger.warn('Approved {0}'.format(draft._id)) except Exception as e: logger.error(e) if __name__ == '__main__': dry_run = 'dry' in sys.argv app = init_app(routes=False) main(dry_run=dry_run) celery_teardown_request()
""" A script for testing DraftRegistrationApprovals. Automatically approves all pending DraftRegistrationApprovals. """ import sys import logging from website.app import init_app from website.models import DraftRegistration, Sanction, User logger = logging.getLogger(__name__) logging.basicConfig(level=logging.WARN) logging.disable(level=logging.INFO) def main(dry_run=True): if dry_run: logger.warn('DRY RUN mode') pending_approval_drafts = DraftRegistration.find() need_approval_drafts = [draft for draft in pending_approval_drafts if draft.requires_approval and draft.approval and draft.approval.state == Sanction.UNAPPROVED] for draft in need_approval_drafts: sanction = draft.approval try: if not dry_run: sanction.state = Sanction.APPROVED sanction._on_complete(None) sanction.save() logger.warn('Approved {0}'.format(draft._id)) except Exception as e: logger.error(e) if __name__ == '__main__': dry_run = 'dry' in sys.argv init_app(routes=False) main(dry_run=dry_run)
Rename field from eventDescription to displayName
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.tooling.events.internal; import org.gradle.tooling.events.OperationDescriptor; import org.gradle.tooling.events.ProgressEvent; /** * Base class for {@code ProgressEvent} implementations. */ abstract class BaseProgressEvent implements ProgressEvent { private final long eventTime; private final String displayName; private final OperationDescriptor descriptor; BaseProgressEvent(long eventTime, String displayName, OperationDescriptor descriptor) { this.eventTime = eventTime; this.displayName = displayName; this.descriptor = descriptor; } @Override public long getEventTime() { return eventTime; } @Override public String getDisplayName() { return displayName; } @Override public OperationDescriptor getDescriptor() { return descriptor; } @Override public String toString() { return getDisplayName(); } }
/* * Copyright 2015 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.tooling.events.internal; import org.gradle.tooling.events.OperationDescriptor; import org.gradle.tooling.events.ProgressEvent; /** * Base class for {@code ProgressEvent} implementations. */ abstract class BaseProgressEvent implements ProgressEvent { private final long eventTime; private final String eventDescription; private final OperationDescriptor descriptor; BaseProgressEvent(long eventTime, String eventDescription, OperationDescriptor descriptor) { this.eventTime = eventTime; this.eventDescription = eventDescription; this.descriptor = descriptor; } @Override public long getEventTime() { return eventTime; } @Override public String getDisplayName() { return eventDescription; } @Override public String toString() { return getDisplayName(); } @Override public OperationDescriptor getDescriptor() { return descriptor; } }
Use status model in Jenkins service
const logger = require('winston'); const request = require('request-promise'); const Status = require('../../models/status'); class JenkinsStatusesService { constructor (options) { this.options = options || {}; } setup(app) { this.app = app; } get(issueKey) { return this.request(issueKey); } /** * Perform the request to the Jenkins instance based on the configuration in order to retreive the status of an issue. * @param issueKey The key of the issue to get the status for * @returns {Promise} A promise which resolves with the current status for the issue. */ request(issueKey) { let requestOptions = { uri: `${this.options.baseUrl}/job/${this.options.jobNameTemplate.replace('{key}', issueKey)}/api/json?tree=builds[number,url,timestamp,id,building,result]`, json: true, transform: this.transform }; if (this.options.auth && this.options.auth.type !== 'none') { requestOptions.auth = this.options.auth; } logger.info('Requesting status from', requestOptions.uri); return request(requestOptions); } /** * Transforms the response body to a normalized status * @param body The body of the response from Jenkins. * @returns {Array} An array containing the normalized status. */ transform(body) { // TODO transform status return new Status(body); } } module.exports = function (options) { return new JenkinsStatusesService(options); }; module.exports.Service = JenkinsStatusesService;
const logger = require('winston'); const request = require('request-promise'); class Service { constructor (options) { this.options = options || {}; } setup(app) { this.app = app; } get(issueKey) { return this.request(issueKey); } /** * Perform the request to the Jenkins instance based on the configuration in order to retreive the status of an issue. * @param issueKey The key of the issue to get the status for * @returns {Promise} A promise which resolves with the current status for the issue. */ request(issueKey) { let requestOptions = { uri: `${this.options.baseUrl}/job/${this.options.jobNameTemplate.replace('{key}', issueKey)}/api/json?tree=builds[number,url,timestamp,id,building,result]`, json: true, transform: this.transform }; if (this.options.auth && this.options.auth.type !== 'none') { requestOptions.auth = this.options.auth; } logger.info('Requesting status from', requestOptions.uri); return request(requestOptions); } /** * Transforms the response body to a normalized status * @param body The body of the response from Jenkins. * @returns {Array} An array containing the normalized status. */ transform(body) { // TODO transform status return body; } } module.exports = function (options) { return new Service(options); }; module.exports.Service = Service;
Fix prop cache reset triggering in the wrong case (affected performance)
import { ATTR_KEY } from '../constants'; import { toLowerCase } from '../util'; import { ensureNodeData, getRawNodeAttributes, removeNode } from './index'; /** DOM node pool, keyed on nodeName. */ const nodes = {}; export function collectNode(node) { removeNode(node); if (node instanceof Element) { if (!(ATTR_KEY in node)) { ensureNodeData(node, getRawNodeAttributes(node)); } node._component = node._componentConstructor = null; let name = node.normalizedNodeName || toLowerCase(node.nodeName); (nodes[name] || (nodes[name] = [])).push(node); } } export function createNode(nodeName, isSvg) { let name = toLowerCase(nodeName), node = nodes[name] && nodes[name].pop() || (isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName)); ensureNodeData(node); node.normalizedNodeName = name; return node; }
import { ATTR_KEY } from '../constants'; import { toLowerCase } from '../util'; import { ensureNodeData, getRawNodeAttributes, removeNode } from './index'; /** DOM node pool, keyed on nodeName. */ const nodes = {}; export function collectNode(node) { removeNode(node); if (node instanceof Element) { if (node[ATTR_KEY]) { ensureNodeData(node, getRawNodeAttributes(node)); } node._component = node._componentConstructor = null; let name = node.normalizedNodeName || toLowerCase(node.nodeName); (nodes[name] || (nodes[name] = [])).push(node); } } export function createNode(nodeName, isSvg) { let name = toLowerCase(nodeName), node = nodes[name] && nodes[name].pop() || (isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName)); ensureNodeData(node); node.normalizedNodeName = name; return node; }
Add column support for sql server --HG-- extra : convert_revision : svn%3A69d324d9-c39d-4fdc-8679-7745eae9e2c8/trunk%40111
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ add_column_string = 'ALTER TABLE %s ADD %s;' def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
from django.db import connection from django.db.models.fields import * from south.db import generic class DatabaseOperations(generic.DatabaseOperations): """ django-pyodbc (sql_server.pyodbc) implementation of database operations. """ def create_table(self, table_name, fields): # Tweak stuff as needed for name,f in fields: if isinstance(f, BooleanField): if f.default == True: f.default = 1 if f.default == False: f.default = 0 # Run generic.DatabaseOperations.create_table(self, table_name, fields)
Fix for / by 0 in /tps Signed-off-by: Ross Allan <ca2c77e14df1e7ee673215c1ef658354e220f471@gmail.com>
package me.nallar.tickthreading.minecraft.commands; import java.util.List; import me.nallar.tickthreading.minecraft.TickManager; import me.nallar.tickthreading.minecraft.TickThreading; import net.minecraft.command.ICommandSender; public class TPSCommand extends Command { public static String name = "tps"; @Override public String getCommandName() { return name; } @Override public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { return true; } @Override public void processCommand(ICommandSender commandSender, List<String> arguments) { StringBuilder tpsReport = new StringBuilder(); tpsReport.append("---- TPS Report ----\n"); long usedTime = 0; for (TickManager tickManager : TickThreading.instance().getManagers()) { tpsReport.append(tickManager.getBasicStats()); usedTime += tickManager.lastTickLength; } tpsReport.append("\nOverall TPS: ").append(Math.min(20, 1000 / (usedTime == 0 ? 1 : usedTime))) .append("\nOverall load: ").append(usedTime * 2).append('%'); sendChat(commandSender, tpsReport.toString()); } }
package me.nallar.tickthreading.minecraft.commands; import java.util.List; import me.nallar.tickthreading.minecraft.TickManager; import me.nallar.tickthreading.minecraft.TickThreading; import net.minecraft.command.ICommandSender; public class TPSCommand extends Command { public static String name = "tps"; @Override public String getCommandName() { return name; } @Override public boolean canCommandSenderUseCommand(ICommandSender par1ICommandSender) { return true; } @Override public void processCommand(ICommandSender commandSender, List<String> arguments) { StringBuilder tpsReport = new StringBuilder(); tpsReport.append("---- TPS Report ----\n"); long usedTime = 0; for (TickManager tickManager : TickThreading.instance().getManagers()) { tpsReport.append(tickManager.getBasicStats()); usedTime += tickManager.lastTickLength; } tpsReport.append("\nOverall TPS: ").append(Math.min(20, 1000 / usedTime)) .append("\nOverall load: ").append(usedTime / 0.5).append('%'); sendChat(commandSender, tpsReport.toString()); } }