text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update JS to prepend html from CPT to body.
( function( $ ) { 'use strict'; $( function() { var body = $( 'body' ), writeReview = $( '.write-a-review' ), singleReview = $( '.single-re-google-reviews' ); // If review link exists. if ( writeReview.length ) { // On click trigger review window. writeReview.on( 'click', function( e ) { // Prevent default browser action. e.preventDefault(); // Get URL for Reivew. var urlReview = $(this).prop( 'href' ); // Add layout styles. body.prepend( '<div class="open-review" />' ); $( '.open-review' ).prepend( '<h2>Use <span>Google</span><br>to leave your review?</h2>' ); $( '.open-review' ).append( '<a href="' + urlReview + '" class="button">Yes</a>' ); $( '.open-review' ).append( '<a href="#" class="close">Close</a>' ); // Close review. $( '.close' ).on( 'click', function( e ) { // Prevent default browser action. e.preventDefault(); // Review review overlay. $( '.open-review' ).remove(); } ); } ); } // If single custom post type. if ( singleReview.length ) { $( '.open-review' ).prependTo( body ); } } ); }( jQuery ) );
( function( $ ) { 'use strict'; $( function() { var body = $( 'body' ), writeReview = $( '.write-a-review' ); // If review link exists. if ( writeReview.length ) { // On click trigger review window. writeReview.on( 'click', function( e ) { // Prevent default browser action. e.preventDefault(); // Get URL for Reivew. var urlReview = $(this).prop( 'href' ); // Add layout styles. body.prepend( '<div class="open-review" />' ); $( '.open-review' ).prepend( '<h2>Use <span>Google</span><br>to leave your review?</h2>' ); $( '.open-review' ).append( '<a href="' + urlReview + '" class="button">Yes</a>' ); $( '.open-review' ).append( '<a href="#" class="close">Close</a>' ); // Close review. $( '.close' ).on( 'click', function( e ) { // Prevent default browser action. e.preventDefault(); // Review review overlay. $( '.open-review' ).remove(); } ); } ); } } ); }( jQuery ) );
Reconnect channel on window focus.
$(function() { var connected = false; var client = $("head").data("client"); var setup = function() { $.getJSON("/getToken/", {client: client}, function(token) { console.log("connecting"); var chan = new goog.appengine.Channel(token); var sock = chan.open(); sock.onopen = function() { connected = true; }; sock.onmessage = function(m) { var res = $.parseJSON(m.data); var button = $("button[data-index="+res.Ind+"]"); var mark; if (res.Read) { mark = "unread"; } else { mark = "read"; } button.text("mark " + mark); button.data("mark", mark); }; sock.onclose = function() { connected = false; }; }); }; setup(); window.onfocus = function() { if (!connected) { setup(); } }; $(".ajax_link").click(function() { var button = $(this); var url; var mark = button.data("mark") if (mark === "read") { url = "/markRead/"; } else { url = "/markUnread/"; } $.get(url, button.data()); }); });
$(function() { var client = $("head").data("client"); var setup = function() { $.getJSON("/getToken/", {client: client}, function(token) { var chan = new goog.appengine.Channel(token); var sock = chan.open(); sock.onmessage = function(m) { var res = $.parseJSON(m.data); var button = $("button[data-index="+res.Ind+"]"); var mark; if (res.Read) { mark = "unread"; } else { mark = "read"; } button.text("mark " + mark); button.data("mark", mark); }; //sock.onclose = setup; }); }; setup(); $(".ajax_link").click(function() { var button = $(this); var url; var mark = button.data("mark") if (mark === "read") { url = "/markRead/"; } else { url = "/markUnread/"; } $.get(url, button.data()); }); });
Edit test task for gulp
import gulp from 'gulp'; import babel from 'babel-core/register'; import nodemon from 'gulp-nodemon'; import mocha from 'gulp-mocha'; import istanbul from 'gulp-babel-istanbul'; import injectModules from 'gulp-inject-modules'; import dotenv from 'dotenv'; dotenv.config(); process.env.NODE_ENV = 'test'; gulp.task('coverage', (cb) => { gulp.src('src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src('test/**/*.js') .pipe(babel()) .pipe(injectModules()) .pipe(mocha()) .pipe(istanbul.writeReports()) .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) .on('end', cb); }); }); gulp.task('test', () => { return gulp.src(['test/postIttest.js']) .pipe(mocha({ compilers: [ 'js:babel-core/register', ] })); });
import gulp from 'gulp'; import babel from 'gulp-babel'; import nodemon from 'gulp-nodemon'; import mocha from 'gulp-mocha'; import istanbul from 'gulp-babel-istanbul'; import injectModules from 'gulp-inject-modules'; import dotenv from 'dotenv'; dotenv.config(); process.env.NODE_ENV = 'test'; gulp.task('coverage', (cb) => { gulp.src('src/**/*.js') .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', () => { gulp.src('test/**/*.js') .pipe(babel()) .pipe(injectModules()) .pipe(mocha()) .pipe(istanbul.writeReports()) .pipe(istanbul.enforceThresholds({ thresholds: { global: 90 } })) .on('end', cb); }); });
:sparkles: Add in a debug option that defaults to false
'use strict'; const path = require('path'); const pkg = require(path.resolve('./package.json')); const semver = require('semver'); const versions = require('./versions.json'); const presetEnv = require.resolve('babel-preset-env'); const presetStage3 = require.resolve('babel-preset-stage-3'); module.exports = function(context, options) { options = options || {}; const debug = options.debug || false; const modules = options.modules || false; const targets = {}; if (pkg.browserslist) { targets.browsers = pkg.browserslist; } if (pkg.engines && pkg.engines.node) { const version = pkg.engines.node; if (semver.valid(version)) { targets.node = version; } else if (semver.validRange(version)) { targets.node = semver.minSatisfying(versions.node, version); } } return { presets: [ [presetEnv, {debug, modules, targets}], presetStage3, ], }; };
'use strict'; const path = require('path'); const pkg = require(path.resolve('./package.json')); const semver = require('semver'); const versions = require('./versions.json'); const presetEnv = require.resolve('babel-preset-env'); const presetStage3 = require.resolve('babel-preset-stage-3'); module.exports = function(context, options) { options = options || {}; const modules = options.modules || false; const targets = {}; if (pkg.browserslist) { targets.browsers = pkg.browserslist; } if (pkg.engines && pkg.engines.node) { const version = pkg.engines.node; if (semver.valid(version)) { targets.node = version; } else if (semver.validRange(version)) { targets.node = semver.minSatisfying(versions.node, version); } } return { presets: [ [presetEnv, {modules, targets}], presetStage3, ], }; };
Remove the app variable for styling
(function(){ angular.module('color', []) .config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }]) .controller('ColorController', [ '$http', function($http) { var color = this; color.start = "000000"; color.middle = "808080"; color.end = "FFFFFF"; this.inputChanged = function() { if (!properInputSizes()) return; var call = "http://color-divider.herokuapp.com/middle_color?start_color=%23" + color.start + "&end_color=%23" + color.end; $http.get(call).success(function(data){ color.middle = data.substr(1); }); } function properInputSizes() { return (color.start.length == 3 || color.start.length == 6) && /^([0-9a-fA-F]+)$/.test(color.start) && (color.end.length == 3 || color.end.length == 6) && /^([0-9a-fA-F]+)$/.test(color.end); } }]); })();
(function(){ var app = angular.module('color', []); app.config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.useXDomain = true; delete $httpProvider.defaults.headers.common['X-Requested-With']; }]); app.controller('ColorController', [ '$http', function($http) { var color = this; color.start = "000000"; color.middle = "808080"; color.end = "FFFFFF"; this.inputChanged = function() { if (!properInputSizes()) return; var call = "http://color-divider.herokuapp.com/middle_color?start_color=%23" + color.start + "&end_color=%23" + color.end; $http.get(call).success(function(data){ color.middle = data.substr(1); }); } function properInputSizes() { return (color.start.length == 3 || color.start.length == 6) && /^([0-9a-fA-F]+)$/.test(color.start) && (color.end.length == 3 || color.end.length == 6) && /^([0-9a-fA-F]+)$/.test(color.end); } }]); })();
Add missing dependency provider for KwfDynamicAssetsVersion
<?php class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract { public function __construct() { $providers = array(); $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_JsClassKwf(); $providers[] = new Kwf_Assets_Provider_IniNoFiles(); $providers[] = new Kwf_Assets_Provider_Dynamic(); $providers[] = new Kwf_Assets_Provider_ExtTrl(); $providers[] = new Kwf_Assets_Provider_DefaultAssets(); $providers[] = new Kwf_Assets_Provider_ErrorHandler(); $providers[] = new Kwf_Assets_TinyMce_Provider(); $providers[] = new Kwf_Assets_Provider_BowerBuiltFile(VENDOR_PATH.'/bower_components/jquery'); parent::__construct($providers); } }
<?php class Kwf_Assets_ProviderList_Maintenance extends Kwf_Assets_ProviderList_Abstract { public function __construct() { $providers = array(); $providers[] = new Kwf_Assets_Provider_Ini(VENDOR_PATH.'/koala-framework/extjs2/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_Ini(KWF_PATH.'/Kwf/Controller/Action/Maintenance/dependencies.ini'); $providers[] = new Kwf_Assets_Provider_JsClassKwf(); $providers[] = new Kwf_Assets_Provider_IniNoFiles(); $providers[] = new Kwf_Assets_Provider_ExtTrl(); $providers[] = new Kwf_Assets_Provider_DefaultAssets(); $providers[] = new Kwf_Assets_Provider_ErrorHandler(); $providers[] = new Kwf_Assets_TinyMce_Provider(); $providers[] = new Kwf_Assets_Provider_BowerBuiltFile(VENDOR_PATH.'/bower_components/jquery'); parent::__construct($providers); } }
Fix wrong validation (values are wrongly validated as the column name)
var resolver = require('../resolver'); function Translator(domain) { this.domain = domain; this.initialize(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, initialize: function() { this.tableName = resolver.getTableNameFromDomain(this.domain); }, translate: function(batches) { var commands = batches.map(function(batch) { return this.translateOne(batch); }, this); return commands.join('\n'); }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[resolver.getColumnNameFromField(field)] = batch.fields[field]; } var command = 'load --table ' + this.tableName + ' ' + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
var resolver = require('../resolver'); function Translator(domain) { this.domain = domain; this.initialize(); } Translator.prototype = { TYPE_ADD: 'add', MAPPED_FIELDS: { 'id': '_key' }, initialize: function() { this.tableName = resolver.getTableNameFromDomain(this.domain); }, translate: function(batches) { var commands = batches.map(function(batch) { return this.translateOne(batch); }, this); return commands.join('\n'); }, translateOne: function(batch) { switch (batch.type) { case this.TYPE_ADD: return this.addToLoad(batch); default: throw new Error('batch type "' + batch.type + '" is not acceptable'); } }, addToLoad: function(batch) { var line = { _key: batch.id }; for (var field in batch.fields) { if (!batch.fields.hasOwnProperty(field)) continue; line[field] = resolver.getColumnNameFromField(batch.fields[field]); } var command = 'load --table ' + this.tableName + ' ' + JSON.stringify([line]); return command; } }; exports.Translator = Translator;
Move object creation outside of get method
import requests from importlib import import_module class ApiBase(object): def __init__(self, api_key, product, version='v1', entity=None): self.product = product self.version = version self.entity = entity self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % { 'product': self.product, 'version': self.version} self.headers = {'X-Okapi-Key': api_key} def get(self, resource, params={}): response = self._get(resource, params) if self.entity is None: return response return self.create_object(response, self.entity) def _get(self, resource, params={}): r = requests.get(self.api_url + resource, params=params, headers=self.headers) return r.json() def create_object(self, response, entity): module = import_module('lapostesdk.entities') obj = getattr(module, self.entity) instance = obj() instance.hydrate(response) return instance
import requests from importlib import import_module class ApiBase(object): def __init__(self, api_key, product, version='v1', entity=None): self.product = product self.version = version self.entity = entity self.api_url = 'https://api.laposte.fr/%(product)s/%(version)s/' % { 'product': self.product, 'version': self.version} self.headers = {'X-Okapi-Key': api_key} def get(self, resource, params={}): response = self._get(resource, params) if self.entity is None: return response module = import_module('lapostesdk.entities') obj = getattr(module, self.entity) instance = obj() instance.hydrate(response) return instance def _get(self, resource, params={}): r = requests.get(self.api_url + resource, params=params, headers=self.headers) return r.json()
Add comments for probable refactor
function matchMaker(userList) { var likeUsers = []; userList.unshift(userList.pop()); for (var i = 1; i < userList.length; i++) { var likenessCounter = 0; var j = 1; while (j <= 4) { if (userList[0][j] == userList[i][j]) { likenessCounter++; } j++; } if (likenessCounter === 4) { likeUsers.push(userList[i]); } } return likeUsers; }; var jose = {0: 'Jose', 1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'}; var brady = {0: 'Brady',1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'}; var chonson = {0: 'Chonson', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'}; var jabroni = {0: 'Jabroni', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'}; var users = [jose, brady, chonson, jabroni]; // Remove user from [users] // Put into its own array // Compare that with every entry in [users] // Put user back into [users] after search
function matchMaker(userList) { var likeUsers = []; userList.unshift(userList.pop()); for (var i = 1; i < userList.length; i++) { var likenessCounter = 0; var j = 1; while (j <= 4) { if (userList[0][j] == userList[i][j]) { likenessCounter++; } j++; } if (likenessCounter === 4) { likeUsers.push(userList[i]); } } return likeUsers; }; var jose = {0: 'Jose', 1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'}; var brady = {0: 'Brady',1: 'tuesday', 2: '3 AM', 3: 'anytime fitness', 4: 'legs'}; var chonson = {0: 'Chonson', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'}; var jabroni = {0: 'Jabroni', 1: 'tuesday', 2: '5 AM', 3: 'anytime fitness', 4: 'legs'}; var users = [jose, brady, chonson, jabroni];
Set anti-aliasing ON for rounded corner boxes.
package org.openlca.app.editors.graphical.model; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.geometry.Insets; import org.eclipse.swt.SWT; public class RoundBorder extends LineBorder { public RoundBorder(int value) { super(value); } @Override public void paint(IFigure figure, Graphics graphics, Insets insets) { graphics.setAntialias(SWT.ON); tempRect.setBounds(getPaintRectangle(figure, insets)); if (getWidth() % 2 == 1) { tempRect.width--; tempRect.height--; } tempRect.shrink(getWidth() / 2, getWidth() / 2); graphics.setLineWidth(getWidth()); graphics.setLineStyle(getStyle()); if (getColor() != null) graphics.setForegroundColor(getColor()); graphics.drawRoundRectangle(tempRect, 15, 15); } }
package org.openlca.app.editors.graphical.model; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.LineBorder; import org.eclipse.draw2d.geometry.Insets; public class RoundBorder extends LineBorder { public RoundBorder(int value) { super(value); } @Override public void paint(IFigure figure, Graphics graphics, Insets insets) { tempRect.setBounds(getPaintRectangle(figure, insets)); if (getWidth() % 2 == 1) { tempRect.width--; tempRect.height--; } tempRect.shrink(getWidth() / 2, getWidth() / 2); graphics.setLineWidth(getWidth()); graphics.setLineStyle(getStyle()); if (getColor() != null) graphics.setForegroundColor(getColor()); graphics.drawRoundRectangle(tempRect, 15, 15); } }
Fix bug with seeding roles for controllers
<?php namespace DamianTW\LaravelRoles\Services; /** * Class RoleControllerService * @package DamianTW\LaravelRoles */ class RoleControllerService { public function buildAuthorityStringForControllerMethod($controllerClass, $controllerMethodName) { $authorityBaseName = $this->getAuthorityBaseName($controllerClass); return strtoupper(snake_case($authorityBaseName) . '_' . snake_case($controllerMethodName)); } public function getAuthorityFromActionName($actionName) { $parsed = explode('@', $actionName); return $this->buildAuthorityStringForControllerMethod($parsed[0], $parsed[1]); } private function getAuthorityBaseName($controllerClass) { return str_replace('Controller' , '' , class_basename($controllerClass)); } }
<?php namespace DamianTW\LaravelRoles\Services; /** * Class RoleControllerService * @package DamianTW\LaravelRoles */ class RoleControllerService { public function buildAuthorityStringForControllerMethod($controllerClass, $controllerMethodName) { $authorityBaseName = $this->getAuthorityBaseName($controllerClass); return strtoupper(snake_case($authorityBaseName) . '_' . snake_case($controllerMethodName)); } public function getAuthorityFromActionName($actionName) { $parsed = explode('@', $actionName); return $this->buildAuthorityStringForControllerMethod($parsed[0], $parsed[1]); } private function getAuthorityBaseName($controllerClass) { return str_replace('Controller' , '' , class_basename(get_class(new $controllerClass))); } }
Add newline to all sent messages
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value + '\n'; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { const response = xhr.response; console.log(response); } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementsByTagName('form')[0]; form.addEventListener('submit', sendMessage); } initializeForm();
'use strict'; /* This declares the function that will send a message */ function sendMessage(e) { e.preventDefault(); const inputNode = e.target.message; const message = inputNode.value; console.log("Sending message:", message); // Clear node inputNode.value = ''; // Send the message const xhr = new XMLHttpRequest(); xhr.onload = (e) => { const response = xhr.response; console.log(response); } xhr.addEventListener("error", (e) => { console.log(e); }); xhr.open("POST", config.hostUrl); xhr.setRequestHeader("Content-type", "text/plain"); xhr.send(message); } function initializeForm() { const form = document.getElementsByTagName('form')[0]; form.addEventListener('submit', sendMessage); } initializeForm();
Add beta path in dev server
import express from 'express'; import http from 'http'; import {renderFile} from 'ejs'; import request from 'superagent'; var app = express(); var FRIGG_API = process.env.FRIGG_API || 'https://ci.frigg.io'; app.engine('html', renderFile); app.set('view engine', 'html'); app.set('views', '' + __dirname); app.use('/static', express.static(__dirname + '/public')); var responses = {}; app.get('/api/*', (req, res, next) => { var url = req.originalUrl; if (responses.hasOwnProperty(url)) { return res.json(responses[url]); } request(FRIGG_API + url) .end((err, apiRes) => { if (err) return next(err); responses[url] = apiRes.body; res.json(apiRes.body); }); }); app.get('/beta/*', (req, res) => { res.render('index', {}); }); app.get('/', (req, res) => { res.redirect('/beta/'); }); var server = http.Server(app); var port = process.env.PORT || 3000; server.listen(port, () => { console.log('listening on *:' + port); });
import express from 'express'; import http from 'http'; import {renderFile} from 'ejs'; import request from 'superagent'; var app = express(); var FRIGG_API = process.env.FRIGG_API || 'https://ci.frigg.io'; app.engine('html', renderFile); app.set('view engine', 'html'); app.set('views', '' + __dirname); app.use('/static', express.static(__dirname + '/public')); var responses = {}; app.get('/api/*', (req, res, next) => { var url = req.originalUrl; if (responses.hasOwnProperty(url)) { return res.json(responses[url]); } request(FRIGG_API + url) .end((err, apiRes) => { if (err) return next(err); responses[url] = apiRes.body; res.json(apiRes.body); }); }); app.get('*', (req, res) => { res.render('index', {}); }); var server = http.Server(app); var port = process.env.PORT || 3000; server.listen(port, () => { console.log('listening on *:' + port); });
Introduce focusing on specific test file
package main import ( "fmt" "io/ioutil" "os" "testing" . "github.com/VonC/godbg" . "github.com/smartystreets/goconvey/convey" ) func TestGoPanic(t *testing.T) { Convey("Test main", t, func() { fmt.Println("test main") files, err := ioutil.ReadDir("./tests") if err != nil { Pdbgf("Unable to access tests folder\n'%v'\n", err) t.Fail() } for _, file := range files { if file.Name() != "exceptionstack2" { continue } Pdbgf(file.Name()) if in, err = os.Open("tests/" + file.Name()); err == nil { Pdbgf("ok open") main() } else { Pdbgf("Unable to access open file '%v'\n'%v'\n", file.Name(), err) t.Fail() } } }) }
package main import ( "fmt" "io/ioutil" "os" "testing" . "github.com/VonC/godbg" . "github.com/smartystreets/goconvey/convey" ) func TestGoPanic(t *testing.T) { Convey("Test main", t, func() { fmt.Println("test main") files, err := ioutil.ReadDir("./tests") if err != nil { Pdbgf("Unable to access tests folder\n'%v'\n", err) t.Fail() } for _, file := range files { Pdbgf(file.Name()) if in, err = os.Open("tests/" + file.Name()); err == nil { Pdbgf("ok open") main() } else { Pdbgf("Unable to access open file '%v'\n'%v'\n", file.Name(), err) t.Fail() } } }) }
Fix progress bar: length must be "outdated files", not "total files"
var path = require('path'); var childProcess = require('child_process'); var ProgressBar = require('progress'); exports.dest = function(pattern) { var absolutePrefix = (pattern[0] === '/') ? '/' : ''; var parts = pattern.split('/'); var full = path.join.apply(this, parts); return function(file) { return absolutePrefix + full.replace('$path', path.dirname(file)) .replace('$name', path.basename(file, path.extname(file))) .replace('$ext', path.extname(file).substr(1)); }; }; exports.process = function(pattern) { return function(src, dest, callback) { var command = pattern.replace('$src', '"' + src + '"') .replace('$dest', '"' + dest + '"'); childProcess.exec(command, callback); }; }; exports.report = function(pattern) { var bar = null; var format = pattern.replace('$progress', '[:bar] :current/:total files'); return function(stats) { if (stats.processed === 0) { bar = new ProgressBar(format, { total: stats.outdated, width: 20 }); } else { bar.tick(); } }; };
var path = require('path'); var childProcess = require('child_process'); var ProgressBar = require('progress'); exports.dest = function(pattern) { var absolutePrefix = (pattern[0] === '/') ? '/' : ''; var parts = pattern.split('/'); var full = path.join.apply(this, parts); return function(file) { return absolutePrefix + full.replace('$path', path.dirname(file)) .replace('$name', path.basename(file, path.extname(file))) .replace('$ext', path.extname(file).substr(1)); }; }; exports.process = function(pattern) { return function(src, dest, callback) { var command = pattern.replace('$src', '"' + src + '"') .replace('$dest', '"' + dest + '"'); childProcess.exec(command, callback); }; }; exports.report = function(pattern) { var bar = null; var format = pattern.replace('$progress', '[:bar] :current/:total files'); return function(stats) { if (stats.processed === 0) { bar = new ProgressBar(format, { total: stats.totalFiles, width: 20 }); } else { bar.tick(); } }; };
Add no results found message for application search
define(['react', 'components/applications/search', 'components/page_header', 'components/mixins/loading', 'rsvp', 'controllers/applications', 'components/applications/cards'], function(React, SearchBox, PageHeader, LoadingMixin, RSVP, Applications, Cards) { var Results = React.createClass({ mixins: [LoadingMixin], model: function() { return Applications.searchApplications(this.props.query); }, renderContent: function() { if (this.state.model.isEmpty()) return React.DOM.div({}, React.DOM.em({}, "No results found.")); else return Cards.ApplicationCardList({applications: this.state.model}); } }); var SearchResults = React.createClass({ render: function() { return React.DOM.div({}, PageHeader({title: "Image Search"}), SearchBox({query: this.props.query}), Results({query: this.props.query})) } }); return SearchResults; });
define(['react', 'components/applications/search', 'components/page_header', 'components/mixins/loading', 'rsvp', 'controllers/applications', 'components/applications/cards'], function(React, SearchBox, PageHeader, LoadingMixin, RSVP, Applications, Cards) { var Results = React.createClass({ mixins: [LoadingMixin], model: function() { return Applications.searchApplications(this.props.query); }, renderContent: function() { return Cards.ApplicationCardList({applications: this.state.model}); } }); var SearchResults = React.createClass({ render: function() { return React.DOM.div({}, PageHeader({title: "Image Search"}), SearchBox({query: this.props.query}), Results({query: this.props.query})) } }); return SearchResults; });
Store json file as .json
import os import sys import json import utils from datetime import datetime from experiments import * RESULTS_DIR = "results" DATA_DIR = "data" EXPERIMENTS = { "http_request" : http_request.HTTPRequestExperiment, "tcp_connect" : tcp_connect.TCPConnectExperiment, "turkey" : turkey.TurkeyExperiment } def get_result_file(): result_file = "result-%s.json" % (datetime.now().isoformat()) return os.path.join(RESULTS_DIR, result_file) def get_input_file(experiment_name): input_file = "%s.txt" % (experiment_name) return os.path.join(DATA_DIR, input_file) def run(): result_file = get_result_file() result_file = open(result_file, "w") results = {} for name, exp in EXPERIMENTS.items(): input_file = get_input_file(name) if not os.path.isfile(input_file): print "Input file for %s does not exist!" % name return input_file = open(input_file) exp = exp(input_file) exp.run() input_file.close() results[name] = exp.results json.dump(results, result_file) result_file.close() if __name__ == "__main__": run()
import os import sys import json import utils from datetime import datetime from experiments import * RESULTS_DIR = "results" DATA_DIR = "data" EXPERIMENTS = { "http_request" : http_request.HTTPRequestExperiment, "tcp_connect" : tcp_connect.TCPConnectExperiment, "turkey" : turkey.TurkeyExperiment } def get_result_file(): result_file = "result-%s.txt" % (datetime.now().isoformat()) return os.path.join(RESULTS_DIR, result_file) def get_input_file(experiment_name): input_file = "%s.txt" % (experiment_name) return os.path.join(DATA_DIR, input_file) def run(): result_file = get_result_file() result_file = open(result_file, "w") results = {} for name, exp in EXPERIMENTS.items(): input_file = get_input_file(name) if not os.path.isfile(input_file): print "Input file for %s does not exist!" % name return input_file = open(input_file) exp = exp(input_file) exp.run() input_file.close() results[name] = exp.results json.dump(results, result_file) result_file.close() if __name__ == "__main__": run()
Fix problem launching app with webpack
/** * Base webpack config used across other specific configs */ const path = require('path'); const validate = require('webpack-validator'); const config = validate({ entry: [ 'babel-polyfill', './views/App.jsx' ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, // https://webpack.github.io/docs/configuration.html#resolve resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] }); module.exports = config;
/** * Base webpack config used across other specific configs */ const path = require('path'); const validate = require('webpack-validator'); const config = validate({ entry: [ 'babel-polyfill', './views/components/App.jsx' ], module: { loaders: [{ test: /\.jsx?$/, loaders: ['babel-loader'], exclude: /node_modules/ }, { test: /\.json$/, loader: 'json-loader' }] }, output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js', // https://github.com/webpack/webpack/issues/1114 libraryTarget: 'commonjs2' }, // https://webpack.github.io/docs/configuration.html#resolve resolve: { extensions: ['', '.js', '.jsx', '.json'], packageMains: ['webpack', 'browser', 'web', 'browserify', ['jam', 'main'], 'main'] }, plugins: [], externals: [ // put your node 3rd party libraries which can't be built with webpack here // (mysql, mongodb, and so on..) ] }); module.exports = config;
Order facets and add sub facet feature
""" Project: META-SHARE prototype implementation Author: Christian Spurk <cspurk@dfki.de> """ from haystack.exceptions import SearchFieldError from haystack.indexes import SearchField, CharField, MultiValueField class LabeledField(SearchField): """ A kind of mixin class for creating `SearchField`s with a label. """ def __init__(self, label, facet_id, parent_id, **kwargs): if label is None: raise SearchFieldError("'{0}' fields must have a label." \ .format(self.__class__.__name__)) self.label = label self.facet_id = facet_id self.parent_id = parent_id super(LabeledField, self).__init__(**kwargs) class LabeledCharField(LabeledField, CharField): """ A `CharField` with a label. """ pass class LabeledMultiValueField(LabeledField, MultiValueField): """ A `MultiValueField` with a label. """ pass
""" Project: META-SHARE prototype implementation Author: Christian Spurk <cspurk@dfki.de> """ from haystack.exceptions import SearchFieldError from haystack.indexes import SearchField, CharField, MultiValueField class LabeledField(SearchField): """ A kind of mixin class for creating `SearchField`s with a label. """ def __init__(self, label, **kwargs): if label is None: raise SearchFieldError("'{0}' fields must have a label." \ .format(self.__class__.__name__)) self.label = label super(LabeledField, self).__init__(**kwargs) class LabeledCharField(LabeledField, CharField): """ A `CharField` with a label. """ pass class LabeledMultiValueField(LabeledField, MultiValueField): """ A `MultiValueField` with a label. """ pass
Enable ES7 object ...rest and ...spread.
exports.getDefaults = function getDefaults() { return { sourceMap: "inline", externalHelpers: true, ast: false, // "Loose" mode gets us faster and more IE-compatible transpilations of: // classes, computed properties, modules, for-of, and template literals. // Basically all the transformers that support "loose". // http://babeljs.io/docs/usage/loose/ loose: ["all", "es6.modules"], whitelist: [ "es6.arrowFunctions", "es6.templateLiterals", "es6.classes", "es6.blockScoping", "es6.properties.shorthand", "es6.properties.computed", "es6.parameters.rest", "es6.parameters.default", "es6.spread", "es7.objectRestSpread", "es6.destructuring", "es6.modules", "flow" ] }; };
exports.getDefaults = function getDefaults() { return { sourceMap: "inline", externalHelpers: true, ast: false, // "Loose" mode gets us faster and more IE-compatible transpilations of: // classes, computed properties, modules, for-of, and template literals. // Basically all the transformers that support "loose". // http://babeljs.io/docs/usage/loose/ loose: ["all", "es6.modules"], whitelist: [ "es6.arrowFunctions", "es6.templateLiterals", "es6.classes", "es6.blockScoping", "es6.properties.shorthand", "es6.properties.computed", "es6.parameters.rest", "es6.parameters.default", "es6.spread", "es6.destructuring", "es6.modules", "flow" ] }; };
Make addData dynamically recognize how data is being added
/*! * node-gcm * Copyright(c) 2013 Marcus Farkas <toothlessgear@finitebox.com> * MIT Licensed */ function Message(obj) { if (!(this instanceof Message)) { return new Message(obj); } if (!obj) { obj = {}; } this.collapseKey = obj.collapseKey || undefined; this.delayWhileIdle = obj.delayWhileIdle || undefined; this.timeToLive = obj.timeToLive || undefined; this.dryRun = obj.dryRun || undefined; this.data = obj.data || {}; } Message.prototype.addData = function() { if(arguments.length == 1) { return this.addDataWithObject(arguments[0]); } if(arguments.length == 2) { return this.addDataWithKeyValue(arguments[0], arguments[1]); } throw new Error("Invalid number of arguments given to addData ("+arguments.length+")"); }; Message.prototype.addDataWithKeyValue = function (key, value) { this.data[key] = value; }; Message.prototype.addDataWithObject = function (obj) { if (typeof obj === 'object' && Object.keys(obj).length > 0) { this.data = obj; } }; module.exports = Message;
/*! * node-gcm * Copyright(c) 2013 Marcus Farkas <toothlessgear@finitebox.com> * MIT Licensed */ function Message(obj) { if (!(this instanceof Message)) { return new Message(obj); } if (!obj) { obj = {}; } this.collapseKey = obj.collapseKey || undefined; this.delayWhileIdle = obj.delayWhileIdle || undefined; this.timeToLive = obj.timeToLive || undefined; this.dryRun = obj.dryRun || undefined; this.data = obj.data || {}; } Message.prototype.addData = Message.prototype.addDataWithKeyValue = function (key, value) { this.data[key] = value; }; Message.prototype.addDataWithObject = function (obj) { if (typeof obj === 'object' && Object.keys(obj).length > 0) { this.data = obj; } }; module.exports = Message;
Make the window full screen.
var app = require('app'); var BrowserWindow = require('browser-window'); var menu = require('./menu'); process.env.PATH += ':/usr/local/bin'; var mainWindow; app.on('ready', function () { mainWindow = createWindow(); }); app.on('window-all-closed', function () { if (process.platform !== 'darwin') { app.quit(); } }); app.on('activate-with-no-open-windows', function () { mainWindow = createWindow(); }); function createWindow() { var workAreaSize = require('screen').getPrimaryDisplay().workAreaSize; var window = new BrowserWindow({ 'web-preferences': { 'overlay-scrollbars': true }, resizable: true, width: workAreaSize.width, height: workAreaSize.height, show: false }); window.loadUrl('file://' + __dirname + '/../../index.html'); menu.setMenu(app, window); window.on('closed', function () { window = null; }); window.webContents.on('did-finish-load', function () { mainWindow.show(); mainWindow.focus(); }); return window; }
var app = require('app'); var BrowserWindow = require('browser-window'); var menu = require('./menu'); process.env.PATH += ':/usr/local/bin'; var mainWindow; app.on('ready', function () { mainWindow = createWindow(); }); app.on('window-all-closed', function() { if(process.platform !== 'darwin') { app.quit(); } }); app.on('activate-with-no-open-windows', function () { mainWindow = createWindow(); }); function createWindow() { var window = new BrowserWindow({ 'web-preferences': { 'overlay-scrollbars': true }, resizable: true, show: false }); window.loadUrl('file://' + __dirname + '/../../index.html'); menu.setMenu(app, window); window.on('closed', function() { window = null; }); window.webContents.on('did-finish-load', function () { mainWindow.show(); mainWindow.focus(); }); return window; }
Add css class for banner background
<?php /* Template Name: Home Page - Banner */ ?> <?php get_header(); ?> </div> <div class="parallax-background"> <div class="container"> <div class="parallax-content"> <h1 class="parallax-h1">< S T A G E ></h1> <h3 class="parallax-h3">“Stage makes front-end development on WordPress faster and easier. It's made for devices of all shapes and projects of all sizes”</h3> <a class="btn btn-success btn-lg" href="https://github.com/chiraggude/wordpress-bootstrap" role="button"><i class="fa fa-github fa-lg"></i> Download from GitHub</a> </div> </div> </div> <div class="container"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> </div> <div><!-- for <div> at start of footer.php --> <?php get_footer(); ?>
<?php /* Template Name: Home Page - Banner */ ?> <?php get_header(); ?> </div> <div id="parallax1"> <div class="container"> <div class="parallax-content"> <h1 class="parallax-h1">< S T A G E ></h1> <h3 class="parallax-h3">“Stage makes front-end development on WordPress faster and easier. It's made for devices of all shapes and projects of all sizes”</h3> <a class="btn btn-success btn-lg" href="https://github.com/chiraggude/wordpress-bootstrap" role="button"><i class="fa fa-github fa-lg"></i> Download from GitHub</a> </div> </div> </div> <!-- Parallax End --> <div class="container"> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <?php the_content(); ?> <?php endwhile; else: ?> <p><?php _e('Sorry, no posts matched your criteria.'); ?></p> <?php endif; ?> </div> <div><!-- for <div> at start of footer.php --> <?php get_footer(); ?>
[refactor] Move move methods into EX class.
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Dexie from "dexie"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static get DText() { return DText; } static get Tag() { return Tag; } static get UI() { return UI; } static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } } static initialize() { EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.ModeMenu.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } } window.EX = EX; jQuery(function () { "use strict"; EX.initialize(); });
import _ from "lodash"; import jQuery from "jquery"; import moment from "moment"; import Dexie from "dexie"; import DText from "./dtext.js"; import Tag from "./tag.js"; import UI from "./ui.js"; import "./danbooru-ex.css"; export default class EX { static search(url, search, { limit, page } = {}) { return $.getJSON(url, { search, limit: limit || 1000, page: page || 1 }); } } EX.DText = DText; EX.Tag = Tag; EX.UI = UI; EX.initialize = function () { EX.UI.initialize(); EX.UI.Artists.initialize(); EX.UI.Comments.initialize(); EX.UI.ForumPosts.initialize(); EX.UI.ModeMenu.initialize(); EX.UI.Pools.initialize(); EX.UI.Posts.initialize(); EX.UI.PostVersions.initialize(); EX.UI.WikiPages.initialize(); } window.EX = EX; jQuery(function () { "use strict"; EX.initialize(); });
Fix typo in docstring spotted by @armadev
from twisted.trial import unittest import ooni.errors class TestErrors(unittest.TestCase): def test_catch_child_failures_before_parent_failures(self): """ Verify that more specific Failures are caught first by handleAllFailures() and failureToString(). Fails if a subclass is listed after its parent Failure. """ # Check each Failure against all subsequent failures for index, (failure, _) in enumerate(ooni.errors.known_failures): for sub_failure, _ in ooni.errors.known_failures[index+1:]: # Fail if subsequent Failure inherits from the current Failure self.assertNotIsInstance(sub_failure(None), failure)
from twisted.trial import unittest import ooni.errors class TestErrors(unittest.TestCase): def test_catch_child_failures_before_parent_failures(self): """ Verify that more specific Failures are caught first by handleAllFailures() and failureToString(). Fails if a subclass is listed after it's parent Failure. """ # Check each Failure against all subsequent failures for index, (failure, _) in enumerate(ooni.errors.known_failures): for sub_failure, _ in ooni.errors.known_failures[index+1:]: # Fail if subsequent Failure inherits from the current Failure self.assertNotIsInstance(sub_failure(None), failure)
[v0.1.2] Fix for error when no X window detected.
#!/usr/bin/env python3 from setuptools import find_packages, setup dependency_links = [ 'https://github.com/m157q/robobrowser/tarball/babf6dd#egg=robobrowser-0.5.3' ] install_requires = [ 'beautifulsoup4==4.4.1', 'dryscrape==1.0', 'requests==2.10.0', 'robobrowser==0.5.3', ] setup( packages=find_packages(exclude=['gettitle.bin']), scripts=['gettitle/bin/gettitle'], dependency_links=dependency_links, install_requires=install_requires, name='gettitle', version='0.1.2', author='Shun-Yi Jheng', author_email='M157q.tw@gmail.com', url="https://github.com/M157q/gettitle", keywords="cli, webpage, title", description="Get webpage title by url from terminal.", platforms=['Linux'], license='MIT', classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Topic :: Utilities", ], )
#!/usr/bin/env python3 from setuptools import find_packages, setup dependency_links = [ 'https://github.com/m157q/robobrowser/tarball/babf6dd#egg=robobrowser-0.5.3' ] install_requires = [ 'beautifulsoup4==4.4.1', 'dryscrape==1.0', 'requests==2.10.0', 'robobrowser==0.5.3', ] setup( packages=find_packages(exclude=['gettitle.bin']), scripts=['gettitle/bin/gettitle'], dependency_links=dependency_links, install_requires=install_requires, name='gettitle', version='0.1.1', author='Shun-Yi Jheng', author_email='M157q.tw@gmail.com', url="https://github.com/M157q/gettitle", keywords="cli, webpage, title", description="Get webpage title by url from terminal.", platforms=['Linux'], license='MIT', classifiers=[ "Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: End Users/Desktop", "License :: OSI Approved :: MIT License", "Operating System :: POSIX :: Linux", "Programming Language :: Python :: 3 :: Only", "Topic :: Utilities", ], )
Use default parser for Reify Module.prototype._compile hook. This saves us from having to install @babel/parser in the server bundle. There is currently a bug in Reify that prevents it from loading this parser by default, but we can work around that on the Meteor side for now.
const Module = module.constructor; const Mp = Module.prototype; Mp.resolve = function (id) { return Module._resolveFilename(id, this); }; // Enable the module.{watch,export,...} runtime API needed by Reify. require("reify/lib/runtime").enable(Mp); const moduleLoad = Mp.load; Mp.load = function (filename) { const result = moduleLoad.apply(this, arguments); if (typeof this.runSetters === "function") { // Make sure we call module.runSetters (or module.runModuleSetters, a // legacy synonym) whenever a module finishes loading. this.runSetters(); } return result; }; const resolved = Promise.resolve(); Mp.dynamicImport = function (id) { return resolved.then(() => require(id)); }; const parse = require("reify/lib/parsers/default").parse; const reifyCompile = require("reify/lib/compiler").compile; const _compile = Mp._compile; Mp._compile = function (content, filename) { const result = reifyCompile(content, { parse: parse, generateLetDeclarations: false, ast: false, }); if (!result.identical) { content = result.code; } return _compile.call(this, content, filename); };
const Module = module.constructor; const Mp = Module.prototype; Mp.resolve = function (id) { return Module._resolveFilename(id, this); }; // Enable the module.{watch,export,...} runtime API needed by Reify. require("reify/lib/runtime").enable(Mp); const moduleLoad = Mp.load; Mp.load = function (filename) { const result = moduleLoad.apply(this, arguments); if (typeof this.runSetters === "function") { // Make sure we call module.runSetters (or module.runModuleSetters, a // legacy synonym) whenever a module finishes loading. this.runSetters(); } return result; }; const resolved = Promise.resolve(); Mp.dynamicImport = function (id) { return resolved.then(() => require(id)); }; const babelParse = require("reify/lib/parsers/babel").parse; const reifyCompile = require("reify/lib/compiler").compile; const _compile = Mp._compile; Mp._compile = function (content, filename) { const result = reifyCompile(content, { parse: babelParse, generateLetDeclarations: false, ast: false, }); if (!result.identical) { content = result.code; } return _compile.call(this, content, filename); };
Revert "Remove some trailing whitespace" This reverts commit bb4dc625bb0e2317ca15528f517a2d56a91ab32d.
from django.db.models import TextField, ForeignKey, FloatField, DateTimeField, ManyToManyField from yunity.models.utils import BaseModel, MaxLengthCharField class Versionable(BaseModel): pass class Metadata(BaseModel): key = MaxLengthCharField() value = TextField() class Category(BaseModel): name = MaxLengthCharField() parent = ForeignKey('yunity.Category', null=True, related_name='children') class Contact(BaseModel): value = MaxLengthCharField() type = MaxLengthCharField() class Location(BaseModel): latitude = FloatField() longitude = FloatField() class User(BaseModel): name = TextField() contact = ManyToManyField(Contact, through='yunity.UserContact') location = ManyToManyField(Location, null=True, through='yunity.UserLocation') class Message(BaseModel): content = TextField() type = MaxLengthCharField() createdAt = DateTimeField(auto_now=True) class Mappable(Versionable): provenance = MaxLengthCharField() name = TextField() metadata = ForeignKey(Metadata, null=True) category = ForeignKey(Category) location = ManyToManyField(Location, through='yunity.MappableLocation') contact = ManyToManyField(Contact) wall = ManyToManyField(Message, null=True) responsible = ManyToManyField(User, through='yunity.MappableResponsibility') class Event(BaseModel): type = MaxLengthCharField() time = DateTimeField(auto_now=True) initiator = ForeignKey(User) target = ForeignKey(Versionable)
from django.db.models import TextField, ForeignKey, FloatField, DateTimeField, ManyToManyField from yunity.models.utils import BaseModel, MaxLengthCharField class Versionable(BaseModel): pass class Metadata(BaseModel): key = MaxLengthCharField() value = TextField() class Category(BaseModel): name = MaxLengthCharField() parent = ForeignKey('yunity.Category', null=True, related_name='children') class Contact(BaseModel): value = MaxLengthCharField() type = MaxLengthCharField() class Location(BaseModel): latitude = FloatField() longitude = FloatField() class User(BaseModel): name = TextField() contact = ManyToManyField(Contact, through='yunity.UserContact') location = ManyToManyField(Location, null=True, through='yunity.UserLocation') class Message(BaseModel): content = TextField() type = MaxLengthCharField() createdAt = DateTimeField(auto_now=True) class Mappable(Versionable): provenance = MaxLengthCharField() name = TextField() metadata = ForeignKey(Metadata, null=True) category = ForeignKey(Category) location = ManyToManyField(Location, through='yunity.MappableLocation') contact = ManyToManyField(Contact) wall = ManyToManyField(Message, null=True) responsible = ManyToManyField(User, through='yunity.MappableResponsibility') class Event(BaseModel): type = MaxLengthCharField() time = DateTimeField(auto_now=True) initiator = ForeignKey(User) target = ForeignKey(Versionable)
Fix remaining tests (less and stylus)
Tinytest.add("stylus - presence", function(test) { var div = document.createElement('div'); Blaze.render(Template.stylus_test_presence).attach(div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); var leftBorder = getStyleProperty(p, 'border-left-style'); test.equal(leftBorder, "dashed"); document.body.removeChild(div); }); Tinytest.add("stylus - @import", function(test) { var div = document.createElement('div'); Blaze.render(Template.stylus_test_import).attach(div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); test.equal(getStyleProperty(p, 'font-size'), "20px"); test.equal(getStyleProperty(p, 'border-left-style'), "dashed"); document.body.removeChild(div); });
Tinytest.add("stylus - presence", function(test) { var div = document.createElement('div'); Blaze.renderComponent(Template.stylus_test_presence, div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); var leftBorder = getStyleProperty(p, 'border-left-style'); test.equal(leftBorder, "dashed"); document.body.removeChild(div); }); Tinytest.add("stylus - @import", function(test) { var div = document.createElement('div'); Blaze.renderComponent(Template.stylus_test_import, div); div.style.display = 'block'; document.body.appendChild(div); var p = div.querySelector('p'); test.equal(getStyleProperty(p, 'font-size'), "20px"); test.equal(getStyleProperty(p, 'border-left-style'), "dashed"); document.body.removeChild(div); });
Expand CORS filter to allow all the things
package io.github.vyo.hellojersey.filter; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import java.io.IOException; /** * Simple filter to apply some headers to HTML incoming requests. * <p/> * Created by manuel.weidmann on 03.03.2015 */ @Provider public class CORSResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "*"); headers.add("Access-Control-Allow-Methods", "OPTIONS, GET, POST, PUT, DELETE, QUERY, UPDATE"); headers.add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); } }
package io.github.vyo.hellojersey.filter; import javax.ws.rs.container.ContainerRequestContext; import javax.ws.rs.container.ContainerResponseContext; import javax.ws.rs.container.ContainerResponseFilter; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.ext.Provider; import java.io.IOException; /** * Simple filter to apply some headers to HTML incoming requests. * <p/> * Created by manuel.weidmann on 03.03.2015 */ @Provider public class CORSResponseFilter implements ContainerResponseFilter { @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { MultivaluedMap<String, Object> headers = responseContext.getHeaders(); headers.add("Access-Control-Allow-Origin", "localhost"); headers.add("Access-Control-Allow-Methods", "GET, POST, DELETE, QUERY, UPDATE"); headers.add("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With"); } }
Fix date issue (I think)
# Get Contribution Count import urllib import datetime import HTMLParser class ContribParser(HTMLParser.HTMLParser): def __init__(self): self.today = datetime.date.today().isoformat() HTMLParser.HTMLParser.__init__(self) def handle_starttag(self, tag, attrs): if tag == 'rect' and self.is_today(attrs): self.count = self.get_count(attrs) def is_today(self, attrs): for name, value in attrs: if name == 'data-date' and value == self.today: return True return False def get_count(self, attrs): for name, value in attrs: if name == 'data-count': return value return None def getContribs(username): url = 'https://github.com/users/:user/contributions' req = urllib.urlopen(url.replace(':user', username)) parser = ContribParser() parser.feed(req.read()) return parser.count
# Get Contribution Count import urllib import datetime import HTMLParser class ContribParser(HTMLParser.HTMLParser): today = datetime.date.today().isoformat() def handle_starttag(self, tag, attrs): if tag == 'rect' and self.is_today(attrs): self.count = self.get_count(attrs) def is_today(self, attrs): for name, value in attrs: if name == 'data-date' and value == self.today: return True return False def get_count(self, attrs): for name, value in attrs: if name == 'data-count': return value return None def getContribs(username): url = 'https://github.com/users/:user/contributions' req = urllib.urlopen(url.replace(':user', username)) parser = ContribParser() parser.feed(req.read()) return parser.count
Remove link wrapper around drag source - Fixes drag-drop bug in FF https://github.com/gaearon/react-dnd/issues/120#issuecomment-81602875
import './index.css'; import React, { PropTypes } from 'react'; import HashLink from './../HashLink'; import ConceptTile from './../ConceptTile'; import ConceptDragSource from '../ConceptDragSource'; import Padding from '../Padding'; const ConceptList = ({ concepts, concept, dispatch }) => <ul className="List"> {concepts.map((item) => <li className={['List-item', item.id === (concept && concept.id) ? 'List-item--active' : ''].join(' ')} key={item.id} > <ConceptDragSource concept={item} dispatch={dispatch}> <HashLink hash={item.id}> <Padding> <ConceptTile concept={item} /> </Padding> </HashLink> </ConceptDragSource> </li> )} </ul>; ConceptList.propTypes = { concepts: PropTypes.array.isRequired, concept: PropTypes.object, dispatch: PropTypes.func.isRequired, }; export default ConceptList;
import './index.css'; import React, { PropTypes } from 'react'; import HashLink from './../HashLink'; import ConceptTile from './../ConceptTile'; import ConceptDragSource from '../ConceptDragSource'; import Padding from '../Padding'; const ConceptList = ({ concepts, concept, dispatch }) => <ul className="List"> {concepts.map((item) => <li className={['List-item', item.id === (concept && concept.id) ? 'List-item--active' : ''].join(' ')} key={item.id} > <HashLink hash={item.id}> <ConceptDragSource concept={item} dispatch={dispatch}> <Padding> <ConceptTile concept={item} /> </Padding> </ConceptDragSource> </HashLink> </li> )} </ul>; ConceptList.propTypes = { concepts: PropTypes.array.isRequired, concept: PropTypes.object, dispatch: PropTypes.func.isRequired, }; export default ConceptList;
Use comma in CSV POST.
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst. from __future__ import unicode_literals from rest_framework.parsers import BaseParser, DataAndFiles class SimpleFileUploadParser(BaseParser): """ A naive raw file upload parser. """ media_type = '*/*' # Accept anything def parse(self, stream, media_type=None, parser_context=None): content = stream.read() return DataAndFiles({}, content) class CSVParser(BaseParser): media_type = 'text/csv' def parse(self, stream, media_type=None, parser_context=None): content = [line.strip().split(',') \ for line in stream.read().split('\n') if line.strip()] data = [{'uuid':row[1].strip('"'), 'events':[{'datetime':row[0].strip('"'), 'value':row[2].strip('"')}]} for row in content] return DataAndFiles(data, None)
# (c) Nelen & Schuurmans. MIT licensed, see LICENSE.rst. from __future__ import unicode_literals from rest_framework.parsers import BaseParser, DataAndFiles class SimpleFileUploadParser(BaseParser): """ A naive raw file upload parser. """ media_type = '*/*' # Accept anything def parse(self, stream, media_type=None, parser_context=None): content = stream.read() return DataAndFiles({}, content) class CSVParser(BaseParser): media_type = 'text/csv' def parse(self, stream, media_type=None, parser_context=None): content = [line.strip().split(';') \ for line in stream.read().split('\n') if line.strip()] data = [{'uuid':row[1].strip('"'), 'events':[{'datetime':row[0].strip('"'), 'value':row[2].strip('"')}]} for row in content] return DataAndFiles(data, None)
Enable specify command line processor.
import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script self.django_manage_script = os.environ.get("MANAGE_PY", self.django_manage_script) def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
import os class DjangoServer(object): default_django_manage_script = "manage.py" def __init__(self, django_manage_script=None): super(DjangoServer, self).__init__() if django_manage_script is None: self.django_manage_script = self.default_django_manage_script else: self.django_manage_script = django_manage_script def get_task_descriptor(self, task_name, param_list=[]): task_name_and_param = [self.django_manage_script, task_name] task_name_and_param.extend(param_list) return {task_name: task_name_and_param} # noinspection PyMethodMayBeStatic def get_cmd_str(self, cmd_name, param_list=[]): return "python %s %s" % (self.django_manage_script, cmd_name) def execute_cmd(self, django_cmd): os.system(self.get_cmd_str(django_cmd))
Break celeryd restart into distict 'stop' and 'start' commands on deploy
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git fetch") run("git reset --hard origin/master") sudo("pip3 install -r requirements.txt") sudo("python3 manage.py collectstatic --noinput") sudo("python3 manage.py migrate --noinput", user='django') run("rm -f {deploy_path}".format(deploy_path=env.deploy_path)) run("ln -s {project_path} {deploy_path}".format( project_path=env.directory, deploy_path=env.deploy_path)) run("service gunicorn restart") run("service celeryd stop") run("service celeryd start") def dbshell(): with cd(env.directory): sudo("python3 manage.py dbshell", user='django') def shell(): with cd(env.directory): sudo("python3 manage.py shell", user='django') def migrate(): with cd(env.directory): sudo("python3 manage.py migrate", user='django') def gunicorn_restart(): run("service gunicorn restart")
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/api.freemusic.ninja" env.deploy_path = "/home/django/django_project" def deploy(): with cd(env.directory): run("git fetch") run("git reset --hard origin/master") sudo("pip3 install -r requirements.txt") sudo("python3 manage.py collectstatic --noinput") sudo("python3 manage.py migrate --noinput", user='django') run("rm -f {deploy_path}".format(deploy_path=env.deploy_path)) run("ln -s {project_path} {deploy_path}".format( project_path=env.directory, deploy_path=env.deploy_path)) run("service gunicorn restart") run("service celeryd restart") def dbshell(): with cd(env.directory): sudo("python3 manage.py dbshell", user='django') def shell(): with cd(env.directory): sudo("python3 manage.py shell", user='django') def migrate(): with cd(env.directory): sudo("python3 manage.py migrate", user='django') def gunicorn_restart(): run("service gunicorn restart")
Update example to show HTML class
# -*- coding: utf-8 -*- from __future__ import print_function from operator import itemgetter import monoidal_tables as mt from monoidal_tables import renderers if __name__ == '__main__': table = (mt.integer('X', itemgetter('x')) + mt.set_class(mt.integer('Y', itemgetter('y')), 'col-y') + mt.align_center(mt.column('Name', itemgetter('name')))) data = [ {'x': 0, 'y': 0, 'name': 'Origin'}, {'x': 5, 'y': 5, 'name': 'Diagonal'}, {'x': 12, 'y': 8, 'name': 'Up'}, ] table.render(data, renderer=renderers.FancyRenderer)
# -*- coding: utf-8 -*- from __future__ import print_function from operator import itemgetter import monoidal_tables as mt from monoidal_tables import renderers if __name__ == '__main__': table = (mt.integer('X', itemgetter('x')) + mt.integer('Y', itemgetter('y')) + mt.align_center(mt.column('Name', itemgetter('name')))) data = [ {'x': 0, 'y': 0, 'name': 'Origin'}, {'x': 5, 'y': 5, 'name': 'Diagonal'}, {'x': 12, 'y': 8, 'name': 'Up'}, ] table.render(data, renderer=renderers.FancyRenderer)
Read from the same object
const generators = require('yeoman-generator') const fs = require('fs') module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments) this.sourceRoot(__dirname + '/../kit') }, prompting: function () { var done = this.async(); const prompts = [ { type: 'input', name: 'name', message: 'Project name', default: this.appname }, { type: 'input', name: 'author', message: 'Author' } ] this.prompt(prompts, function (answers) { this.fields = { year: new Date().getFullYear() } Object.assign(this.fields, answers); done(); }.bind(this)); }, writing: function () { const details = this.fields fs.readdir(this.templatePath(), function (err, files) { if (err) { throw err } for (file of files) { var source = this.templatePath(file) this.fs.copyTpl(source, this.destinationPath(file), details) } }.bind(this)) } })
const generators = require('yeoman-generator') const fs = require('fs') module.exports = generators.Base.extend({ constructor: function () { generators.Base.apply(this, arguments) this.sourceRoot(__dirname + '/../kit') }, prompting: function () { var done = this.async(); const prompts = [ { type: 'input', name: 'name', message: 'Project name', default: this.appname }, { type: 'input', name: 'author', message: 'Author' } ] this.prompt(prompts, function (answers) { Object.assign(this, answers); done(); }.bind(this)); }, writing: function () { const details = { name: this.name.toLowerCase(), author: this.author, year: new Date().getFullYear() } fs.readdir(this.templatePath(), function (err, files) { if (err) { throw err } for (file of files) { var source = this.templatePath(file) this.fs.copyTpl(source, this.destinationPath(file), details) } }.bind(this)) } })
Change the flag name for the host option in the REPL
#!/usr/bin/env node var repl = require('repl'); var util = require('util'); var program = require('commander'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); program .option('-t, --host <host>', 'Remote Debugging Protocol host') .option('-p, --port <port>', 'Remote Debugging Protocol port') .parse(process.argv); var options = { 'host': program.host, 'port': program.port }; Chrome(options, function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ', 'ignoreUndefined': true, 'writer': function (object) { return util.inspect(object, { 'colors': true, 'depth': null }); } }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } }).on('error', function () { console.error('Cannot connect to Chrome'); });
#!/usr/bin/env node var repl = require('repl'); var util = require('util'); var program = require('commander'); var protocol = require('../lib/protocol.json'); var Chrome = require('../'); program .option('-h, --host <host>', 'Remote Debugging Protocol host') .option('-p, --port <port>', 'Remote Debugging Protocol port') .parse(process.argv); var options = { 'host': program.host, 'port': program.port }; Chrome(options, function (chrome) { var chromeRepl = repl.start({ 'prompt': 'chrome> ', 'ignoreUndefined': true, 'writer': function (object) { return util.inspect(object, { 'colors': true, 'depth': null }); } }); // disconnect on exit chromeRepl.on('exit', function () { chrome.close(); }); // add protocol API for (var domainIdx in protocol.domains) { var domainName = protocol.domains[domainIdx].domain; chromeRepl.context[domainName] = chrome[domainName]; } }).on('error', function () { console.error('Cannot connect to Chrome'); });
Change admin index title: 'Dashboard'
from django.conf.urls import patterns, include, url from django.contrib.auth import views as auth_views from django.contrib import admin admin.site.index_title = 'Dashboard' urlpatterns = patterns('', url(r'^$', 'herana.views.home', name='home'), url(r'^grappelli/', include('grappelli.urls')), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'), url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), )
from django.conf.urls import patterns, include, url from django.contrib.auth import views as auth_views from django.contrib import admin from django.views.generic.base import RedirectView urlpatterns = patterns('', url(r'^$', 'herana.views.home', name='home'), url(r'^grappelli/', include('grappelli.urls')), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^admin/password_reset/$', auth_views.password_reset, name='admin_password_reset'), url(r'^admin/password_reset/done/$', auth_views.password_reset_done, name='password_reset_done'), url(r'^reset/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$', auth_views.password_reset_confirm, name='password_reset_confirm'), url(r'^reset/done/$', auth_views.password_reset_complete, name='password_reset_complete'), )
Add in a missing change from r67143 for print preview options. BUG=none TEST=none Review URL: http://codereview.chromium.org/5334002 git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@67155 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { $('cancel-button').addEventListener('click', function(e) { window.close(); }); chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('noPrinter'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. var localStrings = new LocalStrings(); /** * Window onload handler, sets up the page. */ function load() { $('cancel-button').addEventListener('click', function(e) { window.close(); }); chrome.send('getPrinters'); }; /** * Fill the printer list drop down. */ function setPrinters(printers) { if (printers.length > 0) { for (var i = 0; i < printers.length; ++i) { var option = document.createElement('option'); option.textContent = printers[i]; $('printer-list').add(option); } } else { var option = document.createElement('option'); option.textContent = localStrings.getString('no-printer'); $('printer-list').add(option); $('printer-list').disabled = true; $('print-button').disabled = true; } } window.addEventListener('DOMContentLoaded', load);
Change room to room_id in sensor model
module.exports = SensorModel = Backbone.Model.extend({ urlRoot: 'http://localhost:4000/sensor/', idAttribute: 'sensor_id', defaults : { name: 'MySensor', sensor_id: "", room_id: "", }, schema: { name: 'Text', sensor_id: { editorAttrs: { disabled: true } }, model: { type: 'Select', options: ['temperature', 'door'], editorAttrs: { disabled: true }}, room_id: {type: 'Select', options: function(){ var options = [{val: 0, label:"Unassigned"}]; $.getJSON( 'http://localhost:4000/room/', function(rooms){ rooms.forEach(function(room){ options.push({ val: room['_id'], label: room['name'] }); }); } ); return options; }()}, } });
module.exports = SensorModel = Backbone.Model.extend({ urlRoot: 'http://localhost:4000/sensor/', idAttribute: 'sensor_id', defaults : { name: 'MySensor', sensor_id: "", room: "", }, schema: { name: 'Text', sensor_id: { editorAttrs: { disabled: true } }, model: { type: 'Select', options: ['temperature', 'door'], editorAttrs: { disabled: true }}, room: {type: 'Select', options: function(){ var options = [{val: 0, label:"Unassigned"}]; $.getJSON( 'http://localhost:4000/room/', function(rooms){ rooms.forEach(function(room){ options.push({ val: room['_id'], label: room['name'] }); }); } ); return options; }()}, } });
Increment version with update to snap dependency to v0.11.0-beta
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 main import ( "os" // Import the snap plugin library "github.com/intelsdi-x/snap/control/plugin" // Import our collector plugin implementation "github.com/intelsdi-x/snap-plugin-collector-ceph/ceph" ) // meta data about plugin const ( name = "ceph" version = 3 pluginType = plugin.CollectorPluginType ) // plugin bootstrap func main() { plugin.Start( plugin.NewPluginMeta(name, version, pluginType, []string{}, []string{plugin.SnapGOBContentType}, plugin.ConcurrencyCount(1)), ceph.New(), os.Args[1], ) }
/* http://www.apache.org/licenses/LICENSE-2.0.txt Copyright 2015 Intel Corporation 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 main import ( "os" // Import the snap plugin library "github.com/intelsdi-x/snap/control/plugin" // Import our collector plugin implementation "github.com/intelsdi-x/snap-plugin-collector-ceph/ceph" ) // meta data about plugin const ( name = "ceph" version = 2 pluginType = plugin.CollectorPluginType ) // plugin bootstrap func main() { plugin.Start( plugin.NewPluginMeta(name, version, pluginType, []string{}, []string{plugin.SnapGOBContentType}, plugin.ConcurrencyCount(1)), ceph.New(), os.Args[1], ) }
Make sure URL helped doesn't break if a url is undefined
var moment = require('moment'); exports.dateFormat = function(datestamp) { var date = moment(datestamp); if (date.isBefore(moment(), 'week')) { return date.format('MMM D, YYYY'); } else { return date.fromNow(); } }; exports.section = function(name, options) { if(!this._sections) { this._sections = {}; } this._sections[name] = options.fn(this); return null; } exports.urlFormat = function(url) { if(typeof url !== "undefined" && url != null) { if (url.lastIndexOf('http://', 0) === 0) { url = url.substring(7); if (url.lastIndexOf('www.', 0) === 0) { url = url.substring(4); } } return url; } }
var moment = require('moment'); exports.dateFormat = function(datestamp) { var date = moment(datestamp); if (date.isBefore(moment(), 'week')) { return date.format('MMM D, YYYY'); } else { return date.fromNow(); } }; exports.section = function(name, options) { if(!this._sections) { this._sections = {}; } this._sections[name] = options.fn(this); return null; } exports.urlFormat = function(url) { if (url.lastIndexOf('http://', 0) === 0) { url = url.substring(7); if (url.lastIndexOf('www.', 0) === 0) { url = url.substring(4); } } return url; }
Disable test until filesystem-graph issue works - seems that this error comes in test environment, have to figure out is this something phantomjs specific...
var env = require('../env'); var fs = require('fs'); env.init(); var name = "navigate-to-radiator"; var waitTimeout = 2000; casper.test.begin('navigate to host page', 1, function(test) { casper.start(env.root + "/#metric=cpu&timescale=10800", function() { test.assertExists(env.cpuLink, "common navigation is initialized"); }); //FIXME resolve issue with filesystem-graph.js // TypeError: 'undefined' is not a function (evaluating 'nv.utils.optionsFunc.bind(chart)') //http://localhost:5120/scripts/lib/nv.d3.js:11422 //http://localhost:5120/scripts/lib/nv.d3.js:5128 //http://localhost:5120/scripts/lib/nv.d3.js:5402 //http://localhost:5120/scripts/modules/graphs/heap-graph.js:28 //http://localhost:5120/scripts/lib/nv.d3.js:65 //casper.waitUntilVisible(env.hostLink, function() { // this.click(env.hostLink); //}, env.screencapFailure, waitTimeout); // //casper.waitForPopup(/radiator\.html/, function() { // //FIXME should assert something actual popup count..? //}, env.screencapFailure, waitTimeout); // //casper.withPopup(/radiator\.html/, function() { // this.capture('debugging-in-popup.png'); // //FIXME should assert something actual element presence here //}); // //casper.waitUntilVisible(env.heapDiv, function() { // env.writeCoverage(this, name); //}, env.screencapFailure, waitTimeout); casper.run(function() { test.done(); }); });
var env = require('../env'); var fs = require('fs'); env.init(); var name = "navigate-to-radiator"; var waitTimeout = 2000; casper.test.begin('navigate to host page', 2, function(test) { casper.start(env.root + "/#metric=cpu&timescale=10800", function() { test.assertExists(env.cpuLink); }); casper.waitUntilVisible(env.hostLink, function() { this.click(env.hostLink); }, env.screencapFailure, waitTimeout); casper.waitForPopup(/radiator\.html/, function() { //FIXME should assert something actual popup count..? }, env.screencapFailure, waitTimeout); casper.withPopup(/radiator\.html/, function() { //FIXME should assert something actual element presence here }); casper.waitUntilVisible(env.heapDiv, function() { env.writeCoverage(this, name); }, env.screencapFailure, waitTimeout); casper.run(function() { test.done(); }); });
Clean up bad logic to make it slightly less bad
import logging from django.conf import settings log = logging.getLogger(__name__) CDN_SERVICE = getattr(settings, 'CDN_SERVICE') CDN_USERNAME = getattr(settings, 'CDN_USERNAME') CDN_KEY = getattr(settings, 'CDN_KEY') CDN_SECET = getattr(settings, 'CDN_SECET') CDN_ID = getattr(settings, 'CDN_ID') def purge(files): log.error("CDN not configured, can't purge files") if CDN_USERNAME and CDN_KEY and CDN_SECET and CDN_ID: if CDN_SERVICE == 'maxcdn': from maxcdn import MaxCDN api = MaxCDN(CDN_USERNAME, CDN_KEY, CDN_SECET) def purge(files): return api.purge(CDN_ID, files)
import logging from django.conf import settings log = logging.getLogger(__name__) CDN_SERVICE = getattr(settings, 'CDN_SERVICE') CDN_USERNAME = getattr(settings, 'CDN_USERNAME') CDN_KEY = getattr(settings, 'CDN_KEY') CDN_SECET = getattr(settings, 'CDN_SECET') CDN_ID = getattr(settings, 'CDN_ID') def purge(files): log.error("CDN not configured, can't purge files") if CDN_USERNAME and CDN_KEY and CDN_SECET and CDN_ID: if CDN_SERVICE == 'maxcdn': from maxcdn import MaxCDN as cdn_service api = cdn_service(CDN_USERNAME, CDN_KEY, CDN_SECET) def purge(files): return api.purge(CDN_ID, files)
Use low quality audio (sounds good enough)
import sha import os def sha_hash(content): return sha.new(content).hexdigest() def download_audio(url): from subprocess import call retcode = call(["youtube-dl", "-x", "--id", "--audio-quality", "9", "--audio-format", "mp3", "--exec", "mv {} " + os.path.join('/app/mp3cache/', sha_hash(url)), url]) if retcode == 0: return sha_hash(url) else: raise Exception def download_video(url): from subprocess import call retcode = call(["youtube-dl", "--format", "mp4", "--exec", "mv {} " + os.path.join('/app/mp4cache/', sha_hash(url)), url]) if retcode == 0: return sha_hash(url) else: raise Exception
import sha import os def sha_hash(content): return sha.new(content).hexdigest() def download_audio(url): from subprocess import call retcode = call(["youtube-dl", "-x", "--id", "--audio-quality", "0", "--audio-format", "mp3", "--exec", "mv {} " + os.path.join('/app/mp3cache/', sha_hash(url)), url]) if retcode == 0: return sha_hash(url) else: raise Exception def download_video(url): from subprocess import call retcode = call(["youtube-dl", "--format", "mp4", "--exec", "mv {} " + os.path.join('/app/mp4cache/', sha_hash(url)), url]) if retcode == 0: return sha_hash(url) else: raise Exception
Revert "Fix the location path of OpenIPSL" This reverts commit 5b3af4a6c1c77c651867ee2b5f5cef5100944ba6.
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
import sys from CITests import CITests # Libs in Application Examples appExamples = { #"KundurSMIB":"/ApplicationExamples/KundurSMIB/package.mo", #"TwoAreas":"/ApplicationExamples/TwoAreas/package.mo", #"SevenBus":"/ApplicationExamples/SevenBus/package.mo", #"IEEE9":"/ApplicationExamples/IEEE9/package.mo", #"IEEE14":"/ApplicationExamples/IEEE14/package.mo", #"AKD":"/ApplicationExamples/AKD/package.mo", #"N44":"/ApplicationExamples/N44/package.mo", #"OpenCPSD5d3B":"/ApplicationExamples/OpenCPSD5d3B/package.mo", #"RaPIdExperiments":"/ApplicationExamples/RaPIdExperiments/package.mo" } # Instance of CITests ci = CITests("/OpenIPSL") # Run Check on OpenIPSL passLib = ci.runSyntaxCheck("OpenIPSL","/OpenIPSL/OpenIPSL/package.mo") if not passLib: # Error in OpenIPSL sys.exit(1) else: # Run Check on App Examples passAppEx = 1 for package in appExamples.keys(): passAppEx = passAppEx * ci.runSyntaxCheck(package,appExamples[package]) # The tests are failing if the number of failed check > 0 if passAppEx: # Everything is fine sys.exit(0) else: # Exit with error sys.exit(1)
Remove clone, _ check is not needed
var map = require('map-stream') , clone = require('clone') , sass = require('node-sass') , path = require('path') , gutil = require('gulp-util') , ext = gutil.replaceExtension ; module.exports = function (options) { var opts = options ? options : {}; function nodeSass (file, cb) { if (file.isNull()) { return cb(null, file); } opts.data = file.contents.toString(); opts.success = function (css) { file.path = ext(file.path, '.css'); file.contents = new Buffer(css); cb(null, file); }; opts.error = function (err) { if (opts.errLogToConsole) { gutil.log('[gulp-sass] ' + err); return cb(); } return cb(new gutil.PluginError('gulp-sass', err)); }; sass.render(opts); } return map(nodeSass); };
var es = require('event-stream') , clone = require('clone') , sass = require('node-sass') , path = require('path') , gutil = require('gulp-util') , ext = gutil.replaceExtension ; module.exports = function (options) { var opts = options ? clone(options) : {}; function nodeSass (file, cb) { if (path.basename(file.path).indexOf('_') === 0) { return cb(); } if (file.isNull()) { return cb(null, file); } opts.data = file.contents.toString(); opts.success = function (css) { file.path = ext(file.path, '.css'); file.shortened = file.shortened && ext(file.shortened, '.css'); file.contents = new Buffer(css); cb(null, file); }; opts.error = function (err) { if (opts.errLogToConsole) { gutil.log('[gulp-sass] ' + err); return cb(); } return cb(new gutil.PluginError('gulp-sass', err)); }; sass.render(opts); } return es.map(nodeSass); };
Remove unused code that breaks the file cannot use `storage` without adding it as a dependency
'use strict'; angular.module('emission.main.cci-about', ['emission.plugin.logger']) .controller('CCIAboutCtrl', function($scope, $state, $cordovaEmailComposer, $ionicPopup, SurveyLaunch) { $scope.startSurvey = function () { SurveyLaunch.startSurvey('https://berkeley.qualtrics.com/jfe/form/SV_eQBjPXx10yaAScl', 'QR~QID3'); startSurvey(); }; $scope.emailCCI = function() { var email = { to: ['cci@berkeley.edu'], subject: 'Question from Emission User', body: '' } $cordovaEmailComposer.open(email).then(function() { window.Logger.log(window.Logger.LEVEL_DEBUG, "CCI email queued successfully"); }, function () { window.Logger.log(window.Logger.LEVEL_INFO, "CCI email cancel reported, seems to be an error on android"); }); }; })
'use strict'; angular.module('emission.main.cci-about', ['emission.plugin.logger']) .controller('CCIAboutCtrl', function($scope, $state, $cordovaEmailComposer, $ionicPopup, SurveyLaunch) { $scope.startSurvey = function () { SurveyLaunch.startSurvey('https://berkeley.qualtrics.com/jfe/form/SV_eQBjPXx10yaAScl', 'QR~QID3'); startSurvey(); }; $scope.emailCCI = function() { var email = { to: ['cci@berkeley.edu'], subject: 'Question from Emission User', body: '' } $cordovaEmailComposer.open(email).then(function() { window.Logger.log(window.Logger.LEVEL_DEBUG, "CCI email queued successfully"); }, function () { window.Logger.log(window.Logger.LEVEL_INFO, "CCI email cancel reported, seems to be an error on android"); }); }; var SURVEY_DONE_KEY = 'survey_done'; storage.remove(SURVEY_DONE_KEY); })
Use PDO in the local cellid script With 13ae949 the `mysql` calls have been changed to calls using the `PDO` classes. This updates `cellid_local.php` to use `PDO` as well. It also uses the proper capitalisation of the columns because at least the SQLite driver is case sensitive.
<?php require_once("database.php"); $db = connect_save(); if ($db === null) { echo "Result:4"; die(); } if ($_REQUEST["myl"] != "") { $temp = split(":", $_REQUEST["myl"]); $mcc = $temp[0]; $mnc = $temp[1]; $lac = $temp[2]; $cid = $temp[3]; } else { $mcc = $_REQUEST["mcc"]; $mnc = $_REQUEST["mnc"]; $lac = $_REQUEST["lac"]; $cid = $_REQUEST["cid"]; } if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" ) { echo "Result:7"; // CellID not specified die(); } $result = $db->exec_sql("SELECT Latitude, Longitude FROM cellids WHERE CellID=? ORDER BY DateAdded DESC LIMIT 0,1", "$mcc-$mnc-$lac-$cid"); if ( $row=$result->fetch() ) echo "Result:0|$row[Latitude]|$row[Longitude]"; else echo "Result:6"; // No lat/long for specified CellID die(); ?>
<?php require_once("config.php"); if(!@mysql_connect("$DBIP","$DBUSER","$DBPASS")) { echo "Result:4"; die(); } mysql_select_db("$DBNAME"); if ($_REQUEST["myl"] != "") { $temp = split(":", $_REQUEST["myl"]); $mcc = $temp[0]; $mnc = $temp[1]; $lac = $temp[2]; $cid = $temp[3]; } else { $mcc = $_REQUEST["mcc"]; $mnc = $_REQUEST["mnc"]; $lac = $_REQUEST["lac"]; $cid = $_REQUEST["cid"]; } if ( $mcc == "" || $mnc == "" || $lac == "" || $cid == "" ) { echo "Result:7"; // CellID not specified die(); } $result=mysql_query("Select latitude,longitude FROM cellids WHERE cellid='$mcc-$mnc-$lac-$cid' order by dateadded desc limit 0,1"); if ( $row=mysql_fetch_array($result) ) echo "Result:0|".$row['latitude']."|".$row['longitude']; else echo "Result:6"; // No lat/long for specified CellID die(); ?>
Support configuring the host and port of devserver The HOST and PORT env variables may now be used to explicitly set the host and port. Signed-off-by: Byron Ruth <e9d71f5ee7c92d6dc9e92ffdad17b8bd49418f98@devel.io>
// Host and port const HOST = process.env.HOST || '127.0.0.1' const PORT = process.env.PORT || 3000 export default { // Entrypoint of the application. It is named main since that // is most common in other programming environments. entry: [ // Entry point files. "./src/main.js", "./src/index.html" ], // Output of the built files to the specified path and filename. output: { path: __dirname + "/dist", filename: "bundle.js" }, devServer: { host: HOST, port: PORT }, // Each file that is processed can be optionally handled by a 'loader' // which acts as a preprocessor. module: { loaders: [ // The babel-loader handles all the transpilation work with // ES 2015 and JSX. See .babelrc for specifics about the configuration. { text: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }, // The file loader allows for webpack to copy other static assets. { test: /\.html$/, loader: "file?name=[name].[ext]" } ] } }
export default { // Entrypoint of the application. It is named main since that // is most common in other programming environments. entry: [ // Entry point files. "./src/main.js", "./src/index.html" ], // Output of the built files to the specified path and filename. output: { path: __dirname + "/dist", filename: "bundle.js" }, // Each file that is processed can be optionally handled by a 'loader' // which acts as a preprocessor. module: { loaders: [ // The babel-loader handles all the transpilation work with // ES 2015 and JSX. See .babelrc for specifics about the configuration. { text: /\.js$/, exclude: /node_modules/, loader: "babel-loader" }, // The file loader allows for webpack to copy other static assets. { test: /\.html$/, loader: "file?name=[name].[ext]" } ] } }
provider/aws: Change the resource name expected as part of sqs queue import test
package aws import ( "testing" "fmt" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSSQSQueue_importBasic(t *testing.T) { resourceName := "aws_sqs_queue.queue" queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSSQSQueueDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSSQSConfigWithDefaults(queueName), }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) }
package aws import ( "testing" "fmt" "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" ) func TestAccAWSSQSQueue_importBasic(t *testing.T) { resourceName := "aws_sqs_queue.queue-with-defaults" queueName := fmt.Sprintf("sqs-queue-%s", acctest.RandString(5)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSSQSQueueDestroy, Steps: []resource.TestStep{ resource.TestStep{ Config: testAccAWSSQSConfigWithDefaults(queueName), }, resource.TestStep{ ResourceName: resourceName, ImportState: true, ImportStateVerify: true, //The name is never returned after the initial create of the queue. //It is part of the URL and can be split down if needed //ImportStateVerifyIgnore: []string{"name"}, }, }, }) }
Replace "enter" with "space" for splitting
const Post = function (params) { const defaults = { name: '', // full name username: '', // username profile_display: '', // profile image desc: 'No Description', // description url: '', // post image url like_count: 0, // total like comment_count: 0, // total comment post_id: null, // link to actual post profile_id: null, // profile id tags: [] } const opts = Object.assign({}, defaults, params) const generateTagsFromHash = () => { const split = opts.desc.replace( /↵/g, " " ).split(' ') const filterdDesc = []; const tags = split.filter((item) => { if (item[0] !== undefined && item[0] === '#') { return true; } else { filterdDesc.push(item); } }).map((item) => { return item.substring(1, item.length) }); opts.tags = opts.tags.concat(tags) opts.desc = filterdDesc.join(' ') } generateTagsFromHash(); return { name: opts.name, username: opts.username, profile_display: opts.profile_display, desc: opts.desc, display: opts.url, like: opts.like_count, comment: opts.comment_count, profile: opts.profile_id, post: opts.post_id, tags: opts.tags } } module.exports = Post
const Post = function (params) { const defaults = { name: '', // full name username: '', // username profile_display: '', // profile image desc: 'No Description', // description url: '', // post image url like_count: 0, // total like comment_count: 0, // total comment post_id: null, // link to actual post profile_id: null, // profile id tags: [] } const opts = Object.assign({}, defaults, params) const generateTagsFromHash = () => { const split = opts.desc.split(' ') const filterdDesc = []; const tags = split.filter((item) => { if (item[0] !== undefined && item[0] === '#') { return true; } else { filterdDesc.push(item); } }).map((item) => { return item.substring(1, item.length) }); opts.tags = opts.tags.concat(tags) opts.desc = filterdDesc.join(' ') } generateTagsFromHash(); return { name: opts.name, username: opts.username, profile_display: opts.profile_display, desc: opts.desc, display: opts.url, like: opts.like_count, comment: opts.comment_count, profile: opts.profile_id, post: opts.post_id, tags: opts.tags } } module.exports = Post
Add `(fork)` to forked repos in CLI output Fixes #4.
#!/usr/bin/env node 'use strict'; var chalk = require('chalk'); var meow = require('meow'); var githubRepos = require('./'); var cli = meow({ help: [ 'Usage', ' $ github-repositories kevva', ' $ github-repositories kevva --token 523ef69119eadg12', '', 'Options', ' -t, --token GitHub authentication token' ].join('\n') }, { string: ['token'], alias: {t: 'token'} }); if (!cli.input[0]) { console.error('User required'); process.exit(1); } githubRepos(cli.input[0], cli.flags, function (err, data) { if (err) { console.error(err.message); process.exit(1); } data.forEach(function (repo) { if (repo.fork) { repo.name = repo.name + chalk.dim(' (fork)'); } console.log(repo.name + ' ' + chalk.dim(repo.html_url)); }); });
#!/usr/bin/env node 'use strict'; var chalk = require('chalk'); var meow = require('meow'); var githubRepos = require('./'); var cli = meow({ help: [ 'Usage', ' $ github-repositories kevva', ' $ github-repositories kevva --token 523ef69119eadg12', '', 'Options', ' -t, --token GitHub authentication token' ].join('\n') }, { string: ['token'], alias: {t: 'token'} }); if (!cli.input[0]) { console.error('User required'); process.exit(1); } githubRepos(cli.input[0], cli.flags, function (err, data) { if (err) { console.error(err.message); process.exit(1); } data.forEach(function (repo) { console.log(repo.name + ' ' + chalk.dim(repo.html_url)); }); });
Update description to imperative mood
'use strict'; /** * Compute the inverse of the lower incomplete gamma function. * * @module @stdlib/math/base/special/gammaincinv * * @example * var gammaincinv = require( '@stdlib/math/base/special/gammaincinv' ); * * var val = gammaincinv( 0.5, 2.0 ); * // returns ~1.678 * * val = gammaincinv( 0.1, 10.0 ); * // returns ~6.221 * * val = gammaincinv( 0.75, 3.0 ); * // returns ~3.92 * * val = gammaincinv( 0.75, 3.0, true ); * // returns ~1.727 * * val = gammaincinv( 0.75, NaN ); * // returns NaN * * val = gammaincinv( NaN, 3.0 ); * // returns NaN */ // MODULES // var gammaincinv = require( './gammaincinv.js' ); // EXPORTS // module.exports = gammaincinv;
'use strict'; /** * Computes the inverse of the lower incomplete gamma function. * * @module @stdlib/math/base/special/gammaincinv * * @example * var gammaincinv = require( '@stdlib/math/base/special/gammaincinv' ); * * var val = gammaincinv( 0.5, 2.0 ); * // returns ~1.678 * * val = gammaincinv( 0.1, 10.0 ); * // returns ~6.221 * * val = gammaincinv( 0.75, 3.0 ); * // returns ~3.92 * * val = gammaincinv( 0.75, 3.0, true ); * // returns ~1.727 * * val = gammaincinv( 0.75, NaN ); * // returns NaN * * val = gammaincinv( NaN, 3.0 ); * // returns NaN */ // MODULES // var gammaincinv = require( './gammaincinv.js' ); // EXPORTS // module.exports = gammaincinv;
Fix load in minimized JS for the clickOut directive
/** * @author Evgeny Shpilevsky <evgeny@shpilevsky.com> * @date 9/27/13 */ angular.module("enlitePack").directive("clickOut", [$document, function ($document) { return { restrict: 'A', scope: { visible: '=clickOut' }, link: function (scope, element, attr) { var elementMatchesAnyInArray = function (element, elementArray) { return [].some.call(elementArray, function (e) { return element === e; }); }; $document.bind("click", function (event) { if (!elementMatchesAnyInArray(event.target, element.find(event.target.tagName))) { scope.visible = false; scope.$apply(); } }); } }; }]);
/** * @author Evgeny Shpilevsky <evgeny@shpilevsky.com> * @date 9/27/13 */ angular.module("enlitePack").directive("clickOut", function ($document) { return { restrict: 'A', scope: { visible: '=clickOut' }, link: function (scope, element, attr) { var elementMatchesAnyInArray = function (element, elementArray) { return [].some.call(elementArray, function (e) { return element === e; }); }; $document.bind("click", function (event) { if (!elementMatchesAnyInArray(event.target, element.find(event.target.tagName))) { scope.visible = false; scope.$apply(); } }); } }; });
Make FORMATS a tuple and add FORMATS_DESC for textual format descriptions.
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( TARBALL, TARBALL_GZ, TARBALL_BZ2, TARBALL_XZ, ZIP, ) FORMATS_DESC = { TARBALL: "Tarball (.tar)", TARBALL_GZ: "gzip-compressed Tarball (.tar.gz)", TARBALL_BZ2: "bzip2-compressed Tarball (.tar.bz2)", TARBALL_XZ: "xz-compressed Tarball (.tar.xz)", ZIP: "ZIP archive (.zip)", } def get_archiver(fmt): """ Return the class corresponding with the provided archival format """ if fmt in (TARBALL, TARBALL_GZ, TARBALL_BZ2, TARBALL_XZ): return TarballArchiver if fmt == ZIP: return ZipArchiver raise KeyError("Invalid format '{}' specified".format(fmt))
from .tarball import TarballArchiver from .zipfile import ZipArchiver TARBALL = TarballArchiver.UNCOMPRESSED TARBALL_GZ = TarballArchiver.GZ TARBALL_BZ2 = TarballArchiver.BZ2 TARBALL_XZ = TarballArchiver.XZ ZIP = 'zip' FORMATS = ( (TARBALL, "Tarball (.tar)"), (TARBALL_GZ, "gzip-compressed Tarball (.tar.gz)"), (TARBALL_BZ2, "bzip2-compressed Tarball (.tar.bz2)"), (TARBALL_XZ, "xz-compressed Tarball (.tar.xz)"), (ZIP, "ZIP archive (.zip)"), ) def get_archiver(fmt): """ Return the class corresponding with the provided archival format """ if fmt in (TARBALL, TARBALL_GZ, TARBALL_BZ2, TARBALL_XZ): return TarballArchiver if fmt == ZIP: return ZipArchiver raise KeyError("Invalid format '{}' specified".format(fmt))
refactor: Change parameter name for Rate limit
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.repository.ratelimit.api; import io.gravitee.repository.ratelimit.model.RateLimitResult; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * @author David BRASSELY (brasseld at gmail.com) */ public interface RateLimitRepository<T extends Serializable> { RateLimitResult acquire(T key, int weigth, long limit, long periodTime, TimeUnit periodTimeUnit); }
/** * Copyright (C) 2015 The Gravitee team (http://gravitee.io) * * 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 io.gravitee.repository.ratelimit.api; import io.gravitee.repository.ratelimit.model.RateLimitResult; import java.io.Serializable; import java.util.concurrent.TimeUnit; /** * @author David BRASSELY (brasseld at gmail.com) */ public interface RateLimitRepository<T extends Serializable> { RateLimitResult acquire(T key, int pound, long limit, long periodTime, TimeUnit periodTimeUnit); }
Add check for existing /todo folder in path
const chalk = require('chalk'); const fs = require('fs'); const path = require('path'); const tilde = require('tilde-expansion'); const shell = require('shelljs'); const appRootDir = require('app-root-dir').get(); const setConfigProp = require('./setConfigProp'); const newTodoMonth = require('./newTodoMonth'); const init = function({ dir, withGit=false }){ tilde(dir, (expandedDir) => { if (!fs.existsSync(expandedDir)) return console.log(chalk.red('Directory for workbook doesnt exist')); console.log(chalk.green(`Initializing new todo workbook in ${dir}`)); const configPath = path.join(appRootDir, 'config.json'); let todoRoot = expandedDir; if(path.parse(expandedDir).name !== 'todo') todoRoot = path.join(expandedDir, 'todo'); if (!fs.existsSync( todoRoot )) fs.mkdirSync( todoRoot ); writeConfig( configPath, todoRoot ); setConfigProp({ todoRoot, withGit }); newTodoMonth( todoRoot ); if (withGit) { console.log(chalk.blue('Initialising with git')); shell.cd(todoRoot); shell.exec('git init'); shell.exec('git add --all'); shell.exec('git commit -m "Initial Commit"'); } }); }; const writeConfig = function(configPath){ console.log(chalk.green('Writing config')); fs.writeFileSync(configPath, JSON.stringify({})); } module.exports = init;
const chalk = require('chalk'); const fs = require('fs'); const path = require('path'); const tilde = require('tilde-expansion'); const shell = require('shelljs'); const appRootDir = require('app-root-dir').get(); const setConfigProp = require('./setConfigProp'); const newTodoMonth = require('./newTodoMonth'); const init = function({ dir, withGit=false }){ tilde(dir, (expandedDir) => { if (!fs.existsSync(expandedDir)) return console.log(chalk.red('Directory for workbook doesnt exist')); console.log(chalk.green(`Initializing new todo workbook in ${dir}`)); const configPath = path.join(appRootDir, 'config.json'); const todoRoot = path.join(expandedDir, 'todo'); if (!fs.existsSync( todoRoot )) fs.mkdirSync( todoRoot ); writeConfig( configPath, todoRoot ); setConfigProp({ todoRoot, withGit }); newTodoMonth( todoRoot ); if (withGit) { console.log(chalk.blue('Initialising with git')); shell.cd(expandedDir); shell.exec('git init'); shell.exec('git add --all'); shell.exec('git commit -m "Initial Commit"'); } }); }; const writeConfig = function(configPath){ console.log(chalk.green('Writing config')); fs.writeFileSync(configPath, JSON.stringify({})); } module.exports = init;
Load modules from modules dir
/** * _____ __ * / ___// /_ _____ * \__ \/ / / / / _ \ * ___/ / / /_/ / __/ * /____/_/\__, /\___/ * /____/ * Copyright 2017 Slye Development Team. All Rights Reserved. * Licence: MIT License */ const tree = require('./core/tree'); const compile = require('./core/compile'); const modules = require('./core/modules'); const blocks = require('./core/blocks'); const configs = require('./core/config'); const cache = require('./core/cache'); const glob = require('glob'); const path = require('path'); var esy_lang = { tree : tree, compile : compile, cache : cache, configs : configs, block : blocks.add, }; esy_lang['modules'] = modules._esy(esy_lang); // Load modules (function () { var modules = glob.sync('../modules/*/index.js', {cwd: __dirname}), len = modules.length, i = 0; for(;i < len;i++) esy_lang.modules.load(path.join(__dirname, modules[i])) })(); module.exports = esy_lang;
/** * _____ __ * / ___// /_ _____ * \__ \/ / / / / _ \ * ___/ / / /_/ / __/ * /____/_/\__, /\___/ * /____/ * Copyright 2017 Slye Development Team. All Rights Reserved. * Licence: MIT License */ const tree = require('./core/tree'); const compile = require('./core/compile'); const modules = require('./core/modules'); const blocks = require('./core/blocks'); const configs = require('./core/config'); const cache = require('./core/cache'); var esy_lang = { tree : tree, compile : compile, cache : cache, configs : configs, block : blocks.add, modules : modules._esy(esy_lang) }; module.exports = esy_lang;
Add get param as int
__author__ = 'brock' """ Taken from: https://gist.github.com/1094140 """ from functools import wraps from flask import request, current_app def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype) else: return func(*args, **kwargs) return decorated_function def getParamAsInt(request, key, default): """ Safely pulls a key from the request and converts it to an integer @param request: The HttpRequest object @param key: The key from request.args containing the desired value @param default: The value to return if the key does not exist @return: The value matching the key, or if it does not exist, the default value provided. """ return int(request.args.get(key)) if key in request.args and request.args[key].isdigit() else default
__author__ = 'brock' """ Taken from: https://gist.github.com/1094140 """ from functools import wraps from flask import request, current_app def jsonp(func): """Wraps JSONified output for JSONP requests.""" @wraps(func) def decorated_function(*args, **kwargs): callback = request.args.get('callback', False) if callback: data = str(func(*args, **kwargs).data) content = str(callback) + '(' + data + ')' mimetype = 'application/javascript' return current_app.response_class(content, mimetype=mimetype) else: return func(*args, **kwargs) return decorated_function
Fix "bem create" as worcker invocation
'use strict'; var U = require('../../util'); // NOTE: process.once() doesn't guarantee that process // will exit after receiving first message from master // (node bug prior to 0.10) process.once('message', function(m) { require('../../coa').api.create(m.opts, m.args) .then(function() { process.send({ code: 0 }); U.oldNode && process.exit(0); }) .fail(function(err) { process.send({ code: 1, msg: err.stack }); U.oldNode && process.exit(1); }) .done(); });
'use strict'; var U = require('../../util'); // NOTE: process.once() doesn't guarantee that process // will exit after receiving first message from master // (node bug prior to 0.10) process.once('message', function(m) { require('../../coa').api.create[m.cmd](m.opts, m.args) .then(function() { process.send({ code: 0 }); U.oldNode && process.exit(0); }) .fail(function(err) { process.send({ code: 1, msg: err.stack }); U.oldNode && process.exit(1); }) .done(); });
Include icon-blocks.php sidebar snippet and clean code
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="row"> <div class="col-md-8"> <?php get_template_part(SNIPPETS_DIR . '/header/entry-header'); get_template_part(SNIPPETS_DIR . '/entry-content'); comments_template(); ?> </div> <div class="col-md-4"> <?php if ('' !== get_the_post_thumbnail() && !is_single()) : get_template_part(SNIPPETS_DIR . '/post-thumbnail'); endif; keitaro_child_pages_list(get_the_ID()); get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks'); ?> </div> </div> </article>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="row"> <div class="col-md-8"> <?php get_template_part(SNIPPETS_DIR . '/header/entry', 'header'); get_template_part(SNIPPETS_DIR . '/entry', 'content'); comments_template(); ?> </div> <div class="col-md-4"> <?php if ('' !== get_the_post_thumbnail() && !is_single()) : get_template_part(SNIPPETS_DIR . '/post', 'thumbnail'); endif; keitaro_child_pages_list(get_the_ID()); get_template_part(SNIPPETS_DIR . '/sidebars/icon-blocks'); ?> </div> </div> </article>
Fix dashboard to display newest grades
<?php class DashboardController extends \BaseController { /** * Display main page of dashboard * * @return View */ public function getIndex() { $user = User::find(Sentry::getUser()->id); $snapshot = $user->snapshots()->orderBy('created_at', 'DESC')->first(); $grades = $snapshot->grades()->orderBy('date', 'DESC')->take(10)->get(); if ($grades->isEmpty() === true) { Session::flash( 'message', 'Nie posiadasz żadnych ocen! Kliknij '. link_to('jobs/check', 'tutaj'). ', aby uruchomić proces pobierania.' ); } $content = $grades; return View::make('dashboard.index')->withContent($content); } }
<?php class DashboardController extends \BaseController { /** * Display main page of dashboard * * @return View */ public function getIndex() { $grades = Grade::where('user_id', '=', Sentry::getUser()->id)->get(); if($grades->isEmpty() === true){ Session::flash('message', 'Nie posiadasz żadnych ocen! Kliknij '.link_to('jobs/check', 'tutaj').', aby uruchomić proces pobierania.'); } $content = Grade::where('user_id', '=', Sentry::getUser()->id)->orderBy('date', 'DESC')->take(10)->get(); return View::make('dashboard.index')->withContent($content); } }
Add /var/task to $PATH for "aws" command.
// // lambdash - AWS Lambda function to run shell commands // // See also: https://alestic.com/2014/11/aws-lambda-shell/ // process.env['PATH'] = process.env['PATH'] + ':' + process.cwd() var AWS = require('aws-sdk'); var exec = require('child_process').exec; var MAX_OUTPUT = 1024 * 1024 * 1024; // 1 GB exports.handler = function(event, context) { var child = exec(event.command, {encoding: 'binary', maxBuffer: MAX_OUTPUT}, function (error, stdout, stderr) { var result = { "stdout": new Buffer(stdout, 'binary').toString('base64'), "stderr": new Buffer(stderr, 'binary').toString('base64'), "error": error }; context.succeed(result); } ); }
// // lambdash - AWS Lambda function to run shell commands // // See also: https://alestic.com/2014/11/aws-lambda-shell/ // var AWS = require('aws-sdk'); var exec = require('child_process').exec; var MAX_OUTPUT = 1024 * 1024 * 1024; // 1 GB exports.handler = function(event, context) { var child = exec(event.command, {encoding: 'binary', maxBuffer: MAX_OUTPUT}, function (error, stdout, stderr) { var result = { "stdout": new Buffer(stdout, 'binary').toString('base64'), "stderr": new Buffer(stderr, 'binary').toString('base64'), "error": error }; context.succeed(result); } ); }
Use database ID, not filename, to identify documents to remove
module.exports = function(conn) { return { list: function(businessId, callback) { conn.get('/businesses/'+businessId+'/audits', callback); }, create: function(businessId, audit, callback) { conn.post('/businesses/'+businessId+'/audits', audit, callback); }, edit: function(businessId, auditId, audit, callback) { conn.put('/businesses/'+businessId+'/audits/'+auditId, audit, callback); }, find: function(businessId, auditId, callback) { conn.get('/businesses/'+businessId+'/audits/'+auditId, callback); }, delete: function(businessId, auditId, callback){ conn.delete('/businesses/'+businessId+'/audits/'+auditId, callback); }, addFailure: function(businessId, auditId, failure, callback) { conn.post( '/businesses/' + businessId + '/audits/' + auditId + '/failures', failure, callback ); }, deleteDocument: function(businessId, auditId, docId, callback) { conn.delete( '/businesses/' + businessId + '/audits/' + auditId + '/documents/' + docId, callback ); } }; };
module.exports = function(conn) { return { list: function(businessId, callback) { conn.get('/businesses/'+businessId+'/audits', callback); }, create: function(businessId, audit, callback) { conn.post('/businesses/'+businessId+'/audits', audit, callback); }, edit: function(businessId, auditId, audit, callback) { conn.put('/businesses/'+businessId+'/audits/'+auditId, audit, callback); }, find: function(businessId, auditId, callback) { conn.get('/businesses/'+businessId+'/audits/'+auditId, callback); }, delete: function(businessId, auditId, callback){ conn.delete('/businesses/'+businessId+'/audits/'+auditId, callback); }, addFailure: function(businessId, auditId, failure, callback) { conn.post( '/businesses/' + businessId + '/audits/' + auditId + '/failures', failure, callback ); }, deleteDocument: function(businessId, auditId, s3Filename, callback) { conn.delete( '/businesses/' + businessId + '/audits/' + auditId + '/documents/' + s3Filename, callback ); } }; };
Fix case linker exception throwing
<?php namespace NS\ImportBundle\Linker; use NS\ImportBundle\Exceptions\CaseLinkerNotFoundException; class CaseLinkerRegistry { /** * @var array */ private $caseLinkers; /** * CaseLinkerRegistry constructor. * @param $caseLinkers */ public function __construct($caseLinkers = array()) { foreach($caseLinkers as $id => $linker) { $this->addLinker($id,$linker); } } /** * @param $id * @param CaseLinkerInterface $linker */ public function addLinker($id, CaseLinkerInterface $linker) { $this->caseLinkers[$id] = $linker; } /** * @param $linkerName * @return CaseLinkerInterface * @throws CaseLinkerNotFoundException */ public function getLinker($linkerName) { if(isset($this->caseLinkers[$linkerName])) { return $this->caseLinkers[$linkerName]; } throw new CaseLinkerNotFoundException($linkerName); } }
<?php namespace NS\ImportBundle\Linker; class CaseLinkerRegistry { /** * @var array */ private $caseLinkers; /** * CaseLinkerRegistry constructor. * @param $caseLinkers */ public function __construct($caseLinkers = array()) { foreach($caseLinkers as $id => $linker) { $this->addLinker($id,$linker); } } /** * @param $id * @param CaseLinkerInterface $linker */ public function addLinker($id, CaseLinkerInterface $linker) { $this->caseLinkers[$id] = $linker; } /** * @param $linkerName * @return CaseLinkerInterface * @throws CaseLinkerNotFoundException */ public function getLinker($linkerName) { if(isset($this->caseLinkers[$linkerName])) { return $this->caseLinkers[$linkerName]; } throw new CaseLinkerNotFoundException('Unable to locate case linker with id %s'); } }
Make sure library is fetched on first load after auth
import React from 'react'; import { connect } from 'react-redux'; import { doAuth, parseAuthToken } from '../lib/actions/auth'; import { fetchLibrary } from '../lib/actions/library'; import LoggedIn from './logged-in'; import LogInBox from './log-in-box'; const App = React.createClass( { componentWillMount() { if ( this.props.auth.token ) { return this.props.dispatch( fetchLibrary() ); } this.props.dispatch( parseAuthToken() ); }, componentDidUpdate() { return this.props.dispatch( fetchLibrary() ); }, showAuth() { this.props.dispatch( doAuth() ) }, render() { if ( this.props.auth.token ) { return ( <LoggedIn /> ); } return ( <LogInBox showAuth={ this.showAuth } /> ); } } ); function mapStateToProps( state ) { const { auth } = state; return { auth }; } export default connect( mapStateToProps )( App );
import React from 'react'; import { connect } from 'react-redux'; import { doAuth, parseAuthToken } from '../lib/actions/auth'; import { fetchLibrary } from '../lib/actions/library'; import LoggedIn from './logged-in'; import LogInBox from './log-in-box'; const App = React.createClass( { componentWillMount() { if ( this.props.auth.token ) { return this.props.dispatch( fetchLibrary() ); } this.props.dispatch( parseAuthToken() ); }, showAuth() { this.props.dispatch( doAuth() ) }, render() { if ( this.props.auth.token ) { return ( <LoggedIn /> ); } return ( <LogInBox showAuth={ this.showAuth } /> ); } } ); function mapStateToProps( state ) { const { auth } = state; return { auth }; } export default connect( mapStateToProps )( App );
Add Fill data to TestMakeXLSXStyleElements.
package xlsx import ( . "gopkg.in/check.v1" ) type StyleSuite struct{} var _ = Suite(&StyleSuite{}) func (s *StyleSuite) TestNewStyle(c *C) { style := NewStyle() c.Assert(style, NotNil) } func (s *StyleSuite) TestMakeXLSXStyleElements(c *C) { style := NewStyle() font := *NewFont(12, "Verdana") style.Font = font fill := *NewFill("solid", "00FF0000", "FF000000") style.Fill = fill xFont, xFill, _, _, _ := style.makeXLSXStyleElements() // HERE YOU ARE! c.Assert(xFont.Sz.Val, Equals, "12") c.Assert(xFont.Name.Val, Equals, "Verdana") c.Assert(xFill.PatternFill.PatternType, Equals, "solid") c.Assert(xFill.PatternFill.FgColor.RGB, Equals, "00FF0000") c.Assert(xFill.PatternFill.BgColor.RGB, Equals, "FF000000") } type FontSuite struct{} var _ = Suite(&FontSuite{}) func (s *FontSuite) TestNewFont(c *C) { font := NewFont(12, "Verdana") c.Assert(font, NotNil) c.Assert(font.Name, Equals, "Verdana") c.Assert(font.Size, Equals, 12) }
package xlsx import ( . "gopkg.in/check.v1" ) type StyleSuite struct{} var _ = Suite(&StyleSuite{}) func (s *StyleSuite) TestNewStyle(c *C) { style := NewStyle() c.Assert(style, NotNil) } func (s *StyleSuite) TestMakeXLSXStyleElements(c *C) { style := NewStyle() font := *NewFont(12, "Verdana") style.Font = font xFont, _, _, _, _ := style.makeXLSXStyleElements() // HERE YOU ARE! c.Assert(xFont.Sz.Val, Equals, "12") c.Assert(xFont.Name.Val, Equals, "Verdana") } type FontSuite struct{} var _ = Suite(&FontSuite{}) func (s *FontSuite) TestNewFont(c *C) { font := NewFont(12, "Verdana") c.Assert(font, NotNil) c.Assert(font.Name, Equals, "Verdana") c.Assert(font.Size, Equals, 12) }
Test routine for contour plotting
import numpy as np from pyquante2 import basisset,rhf,h2 from pyquante2.graphics.vtk import vtk_orbital from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs from pyquante.graphics.contourplot import test_contour def lineplot_orbs(): return test_plot_orbs() def lineplot_bfs(): return test_plot_bfs() def contour_orb(): return test_contour(True) def plot_h2(): bfs = basisset(h2,'sto3g') solver = rhf(h2,bfs) ens = solver.converge() # Note: these orbitals are not coming out symmetric. Why not?? print solver print solver.orbs vtk_orbital(h2,solver.orbs,bfs) def plot_orbs(): bfs = basisset(h2,'sto3g') orbs = np.array([[1.0,1.0], [1.0,-1.0]],'d') vtk_orbital(h2,orbs,bfs) return if __name__ == '__main__': plot_h2()
import numpy as np from pyquante2 import basisset,rhf,h2 from pyquante2.graphics.vtk import vtk_orbital from pyquante.graphics.lineplot import test_plot_orbs,test_plot_bfs def lineplot_orbs(): return test_plot_orbs() def lineplot_bfs(): return test_plot_bfs() def plot_h2(): bfs = basisset(h2,'sto3g') solver = rhf(h2,bfs) ens = solver.converge() # Note: these orbitals are not coming out symmetric. Why not?? print solver print solver.orbs vtk_orbital(h2,solver.orbs,bfs) def plot_orbs(): bfs = basisset(h2,'sto3g') orbs = np.array([[1.0,1.0], [1.0,-1.0]],'d') vtk_orbital(h2,orbs,bfs) return if __name__ == '__main__': plot_h2()
Update dock block for new location of HeadersInterface
<?php /** * Slim Framework (https://slimframework.com) * * @link https://github.com/slimphp/Slim * @copyright Copyright (c) 2011-2017 Josh Lockhart * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Tests\Mocks; use Slim\Http\Message; /** * Mock object for Slim\Http\MessageTest */ class MessageStub extends Message { /** * Protocol version * * @var string */ public $protocolVersion; /** * Headers * * @var \Slim\Http\HeadersInterface */ public $headers; /** * Body object * * @var \Psr\Http\Message\StreamInterface */ public $body; }
<?php /** * Slim Framework (https://slimframework.com) * * @link https://github.com/slimphp/Slim * @copyright Copyright (c) 2011-2017 Josh Lockhart * @license https://github.com/slimphp/Slim/blob/3.x/LICENSE.md (MIT License) */ namespace Slim\Tests\Mocks; use Slim\Http\Message; /** * Mock object for Slim\Http\MessageTest */ class MessageStub extends Message { /** * Protocol version * * @var string */ public $protocolVersion; /** * Headers * * @var \Slim\Interfaces\Http\HeadersInterface */ public $headers; /** * Body object * * @var \Psr\Http\Message\StreamInterface */ public $body; }
Update up to changes in site-tree
'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , ensureCallable = require('es5-ext/object/valid-callable') , d = require('d') , SiteTree = require('site-tree') , defineProperty = Object.defineProperty, defineProperties = Object.defineProperties; var DomjsSiteTree = module.exports = defineProperties(setPrototypeOf(function (domjs) { if (!(this instanceof DomjsSiteTree)) return new DomjsSiteTree(domjs); SiteTree.call(this, domjs.document); defineProperty(this, 'domjs', d(domjs)); }, SiteTree), { ensureTemplate: d(function (tpl) { if (typeof tpl === 'string') return tpl; return ensureCallable(tpl); }) }); DomjsSiteTree.prototype = Object.create(SiteTree.prototype, { constructor: d(DomjsSiteTree), _resolveTemplate: d(function (tpl, context) { var df; if (typeof tpl === 'string') { df = this.document.createDocumentFragment(); df.appendChild(this.document.createTextNode(tpl)); return df; } return this.domjs.collect(tpl.bind(context)); }) });
'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , ensureCallable = require('es5-ext/object/valid-callable') , d = require('d') , SiteTree = require('site-tree') , defineProperty = Object.defineProperty, defineProperties = Object.defineProperties; var DomjsSiteTree = module.exports = defineProperties(setPrototypeOf(function (domjs) { if (!(this instanceof DomjsSiteTree)) return new DomjsSiteTree(domjs); SiteTree.call(this, domjs.document); defineProperty(this, 'domjs', d(domjs)); }, SiteTree), { ensureTemplate: d(function (tpl) { if (typeof tpl === 'string') return tpl; return ensureCallable(tpl); }) }); DomjsSiteTree.prototype = Object.create(SiteTree.prototype, { constructor: d(DomjsSiteTree), resolveTemplate: d(function (tpl, context) { var df; if (typeof tpl === 'string') { df = this.document.createDocumentFragment(); df.appendChild(this.document.createTextNode(tpl)); return df; } return this.domjs.collect(tpl.bind(context)); }) });
Drop test for importing fakemodule
# encoding: utf-8 def test_import_completer(): from IPython.core import completer def test_import_crashhandler(): from IPython.core import crashhandler def test_import_debugger(): from IPython.core import debugger def test_import_excolors(): from IPython.core import excolors def test_import_history(): from IPython.core import history def test_import_hooks(): from IPython.core import hooks def test_import_getipython(): from IPython.core import getipython def test_import_interactiveshell(): from IPython.core import interactiveshell def test_import_logger(): from IPython.core import logger def test_import_macro(): from IPython.core import macro def test_import_magic(): from IPython.core import magic def test_import_oinspect(): from IPython.core import oinspect def test_import_prefilter(): from IPython.core import prefilter def test_import_prompts(): from IPython.core import prompts def test_import_release(): from IPython.core import release def test_import_shadowns(): from IPython.core import shadowns def test_import_ultratb(): from IPython.core import ultratb def test_import_usage(): from IPython.core import usage
# encoding: utf-8 def test_import_completer(): from IPython.core import completer def test_import_crashhandler(): from IPython.core import crashhandler def test_import_debugger(): from IPython.core import debugger def test_import_fakemodule(): from IPython.core import fakemodule def test_import_excolors(): from IPython.core import excolors def test_import_history(): from IPython.core import history def test_import_hooks(): from IPython.core import hooks def test_import_getipython(): from IPython.core import getipython def test_import_interactiveshell(): from IPython.core import interactiveshell def test_import_logger(): from IPython.core import logger def test_import_macro(): from IPython.core import macro def test_import_magic(): from IPython.core import magic def test_import_oinspect(): from IPython.core import oinspect def test_import_prefilter(): from IPython.core import prefilter def test_import_prompts(): from IPython.core import prompts def test_import_release(): from IPython.core import release def test_import_shadowns(): from IPython.core import shadowns def test_import_ultratb(): from IPython.core import ultratb def test_import_usage(): from IPython.core import usage
Allow as much writing as needed after sync switch.
var Queue = require('prolific.queue') var createUncaughtExceptionHandler = require('./uncaught') var abend = require('abend') function Shuttle (input, output, sync, uncaught, process) { this.input = input this.output = output this.queue = new Queue(output, sync) this.uncaught = createUncaughtExceptionHandler(uncaught) this.process = process } Shuttle.prototype.uncaughtException = function (error) { console.error(error.stack) this.uncaught.call(null, error) this.exit(function () { this.process.exit(1) }.bind(this)) } Shuttle.prototype.stop = function () { this.queue.close() } Shuttle.prototype.exit = function (callback) { this.stop() this.queue.exit(callback) } Shuttle.shuttle = require('./bootstrap').createShuttle(require('net'), Shuttle) Shuttle.filename = module.filename Shuttle.sink = require('prolific.sink') module.exports = Shuttle
var Queue = require('prolific.queue') var createUncaughtExceptionHandler = require('./uncaught') var abend = require('abend') function Shuttle (input, output, sync, uncaught, process) { this.input = input this.output = output this.queue = new Queue(output) this.sync = sync this.uncaught = createUncaughtExceptionHandler(uncaught) this.process = process } Shuttle.prototype.uncaughtException = function (error) { console.error(error.stack) this.uncaught.call(null, error) this.exit(function () { this.process.exit(1) }.bind(this)) } Shuttle.prototype.stop = function () { this.queue.close() } Shuttle.prototype.exit = function (callback) { this.stop() this.queue.exit(this.sync, callback) } Shuttle.shuttle = require('./bootstrap').createShuttle(require('net'), Shuttle) Shuttle.filename = module.filename Shuttle.sink = require('prolific.sink') module.exports = Shuttle
Use *_preview settings for OBI.
# -*- coding: utf-8 -*- # Settings for obi.1flow.net (test) import os from sparks.django.settings import include_snippets include_snippets( os.path.dirname(__file__), ( # no debug on OBI, we need to be in "real-life-mode". # Sentry will help us catch errors, anyway. '00_production', '1flow_io', 'common', 'db_common', 'db_preview', 'cache_common', 'cache_development', 'mail_production', # But it's a preview/test environment, still. 'raven_preview', 'common_preview', # Thus we get rosetta, and the Django Debug toolbar. 'rosetta', 'djdt', ), globals() ) # Override `1flow_io` for preview/test environment. SITE_DOMAIN = 'obi.1flow.io'
# -*- coding: utf-8 -*- # Settings for obi.1flow.net (test) import os from sparks.django.settings import include_snippets include_snippets( os.path.dirname(__file__), ( # no debug on OBI, we need to be in "real-life-mode". # Sentry will help us catch errors, anyway. '00_production', '1flow_io', 'common', 'db_common', 'db_test', 'cache_common', 'cache_development', 'mail_production', # But it's a preview/test environment, still. 'raven_test', 'common_test', # Thus we get rosetta, and the Django Debug toolbar. 'rosetta', 'djdt', ), globals() ) # Override `1flow_io` for preview/test environment. SITE_DOMAIN = 'obi.1flow.io'
Increase threshold and ignore anti-aliasing when comparing images
/* Copyright 2018 Google LLC 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. */ const pixelmatch = require('pixelmatch'); const sharp = require('sharp'); function diff(oldImage, newImage, length, width, callback) { // Number of pixels that have to mismatch to consider the images different const diffPixelThreshold = 100; const diffBuffer = Buffer.alloc(oldImage.length); Promise.all([sharp(oldImage).toBuffer(), sharp(newImage).toBuffer()]).then(images => { const diffPixelCount = pixelmatch(images[0], images[1], diffBuffer, length, width, { includeAA: true, // Ignore Anti-aliasing in diff threshold: 0.3, // be less sensitive than default (0.1) to determine if a pixel has changed. }); if (diffPixelCount === diffPixelThreshold) return callback(null, false); callback(null, diffPixelCount, diffBuffer); }); } module.exports = diff;
/* Copyright 2018 Google LLC 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. */ const pixelmatch = require('pixelmatch'); const sharp = require('sharp'); function diff(oldImage, newImage, length, width, callback) { const diffBuffer = Buffer.alloc(oldImage.length); Promise.all([sharp(oldImage).toBuffer(), sharp(newImage).toBuffer()]).then(images => { const diffPixelCount = pixelmatch(images[0], images[1], diffBuffer, length, width); if (diffPixelCount === 0) return callback(null, false); callback(null, diffPixelCount, diffBuffer); }); } module.exports = diff;
Remove 2FA from login page
@extends('templates.master') @section('content') <form action="/login" method="POST"> <input type="text" name="username" placeholder="Username"><br /> <input type="password" name="password" placeholder="Password"><br /> {{ csrf_field() }} <input type="submit" value="Login"> </form> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @stop
@extends('templates.master') @section('content') <form action="/login" method="POST"> <input type="text" name="username" placeholder="Username"><br /> <input type="password" name="password" placeholder="Password"><br /> <input type="text" name="2fa" placeholder="2 Factor Authen"><br /> {{ csrf_field() }} <input type="submit" value="Login"> </form> @if (count($errors) > 0) <div class="alert alert-danger"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif @stop
Add known offset for known bad calibration. Former-commit-id: afa3d6a66e32bbcc2b20f00f7e63fba5cb45882e [formerly 0470ca22b8a24205d2eb1c66caee912c990da0b3] [formerly c23210f4056c27e61708da2f2440bce3eda151a8 [formerly 5c0a6b9c0fefd2b88b9382d4a6ed98d9eac626df]] Former-commit-id: 8bfdaa1f7940b26aee05f20e801616f4a8d1d55d [formerly 1c85db5b2b87b73dfb28a1db171ff79a69e3a24a] Former-commit-id: d02a26b263c5c59776a35fc130e5c96b7ac30f5d
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) # assert np.round(p1, 1).value == published_results[vsini] assert np.round(100 * p1, 1).value == published_results[vsini] # With incorect normalization
""" To test if the new code produces the same precision values on the published results.""" from __future__ import division, print_function import pytest import numpy as np import eniric.Qcalculator as Q import eniric.IOmodule as IO from bin.prec_1 import calc_prec1 # For python2.X compatibility file_error_to_catch = getattr(__builtins__, 'FileNotFoundError', IOError) path = "data/Published_Results/resampled/" @pytest.mark.xfail(raises=file_error_to_catch) # Data file may not exist def test_presicion_1(): """ New precision 1 test that works.""" published_results = {1: 3.8, 5: 9.1, 10: 20.7} path = "data/resampled/" for vsini in [1, 5, 10]: # name = "Spectrum_M0-PHOENIX-ACES_Yband_vsini{0}.0_R100k_res3.txt".format(vsini) __, p1 = calc_prec1("M0", "Y", vsini, "100k", 3, resampled_dir=path) assert np.round(p1, 1).value == published_results[vsini]
Remove version info from comment. git-svn-id: 6eed74fe9a15c8da84b9a8d7f2960c0406113ece@891684 13f79535-47bb-0310-9956-ffa450edef68
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.event; /** * The eventing thread pool is a special thread pool used for the eventing. * The eventing uses a service registered as this interface. * The default implementation is a configurable pool registered with * commons threads. */ public interface ThreadPool extends org.apache.sling.commons.threads.ThreadPool { // this is just a marker interface }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.event; /** * The eventing thread pool is a special thread pool used for the eventing. * The eventing uses a service registered as this interface. * The default implementation is a configurable pool registered with * commons threads. * * @version $Id$ */ public interface ThreadPool extends org.apache.sling.commons.threads.ThreadPool { // this is just a marker interface }
Make version number match patchboard, bitvault
from setuptools import setup, find_packages setup(name='coinop', version='0.1.0', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
from setuptools import setup, find_packages setup(name='coinop', version='0.0.3', description='Crypto-currency conveniences', url='http://github.com/BitVault/coinop-py', author='Matthew King', author_email='matthew@bitvault.io', license='MIT', packages=find_packages(exclude=[ u'*.tests', u'*.tests.*', u'tests.*', u'tests']), install_requires=[ # Not listed explicitly to ensure you install PyNaCl by hand-- # see README #'PyNaCl', 'cffi', 'pytest', 'pycrypto', 'python-bitcoinlib', 'pycoin', 'PyYAML', 'ecdsa' ], zip_safe=False)
cmd: Remove trailing dots from collected endpoint domain names
package main import ( "context" "errors" "fmt" "strings" "github.com/gentlemanautomaton/serviceresolver" "github.com/scjalliance/resourceful/guardian" ) func collectEndpoints(ctx context.Context) (endpoints []guardian.Endpoint, err error) { services, err := serviceresolver.DefaultResolver.Resolve(ctx, "resourceful") if err != nil { return nil, fmt.Errorf("failed to locate resourceful endpoints: %v", err) } if len(services) == 0 { return nil, errors.New("unable to detect host domain") } for _, service := range services { for _, addr := range service.Addrs { endpoint := guardian.Endpoint(fmt.Sprintf("http://%s:%d", strings.TrimSuffix(addr.Target, "."), addr.Port)) endpoints = append(endpoints, endpoint) } } return endpoints, nil }
package main import ( "context" "errors" "fmt" "github.com/gentlemanautomaton/serviceresolver" "github.com/scjalliance/resourceful/guardian" ) func collectEndpoints(ctx context.Context) (endpoints []guardian.Endpoint, err error) { services, err := serviceresolver.DefaultResolver.Resolve(ctx, "resourceful") if err != nil { return nil, fmt.Errorf("failed to locate resourceful endpoints: %v", err) } if len(services) == 0 { return nil, errors.New("unable to detect host domain") } for _, service := range services { for _, addr := range service.Addrs { endpoint := guardian.Endpoint(fmt.Sprintf("http://%s:%d", addr.Target, addr.Port)) endpoints = append(endpoints, endpoint) } } return endpoints, nil }
Add console statements for initial notification
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn, winner: state.tictactoe.winner }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein console.log('DRAW'); } else if (propObj.winner) { // do very cool modal fadein with computer winning console.log('YOU LOST'); } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <h2 className='text-center'>Open your console to see messages</h2> <h3 className='text-center'>You can't win</h3> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
import React from 'react'; import './TicTacToe.scss'; import { connect } from 'react-redux'; import ticTacToeActions from 'actions/tictactoe'; import GameBoard from './components/GameBoard'; const mapStateToProps = (state) => { return { playerTurn: state.tictactoe.playerTurn }; }; class TicTacToe extends React.Component { static propTypes = { playerTurn: React.PropTypes.bool, computer_move: React.PropTypes.func } componentWillReceiveProps (propObj) { if (!propObj.playerTurn) { this.props.computer_move(); } if (propObj.winner && propObj.winner.result === 'draw') { // do very cool modal fadein } else if (propObj.winner) { // do very cool modal fadein with computer winning } // nothing else, the player can't win } render () { return ( <div> <h1 className='text-center'>Tic-Tac-Toe</h1> <GameBoard /> </div> ); } } export default connect(mapStateToProps, ticTacToeActions)(TicTacToe);
Fix sidebar classname multi-line problem
import React from 'react'; import LazyLoad from 'react-lazyload'; import PropTypes from 'prop-types'; import './index.scss'; const Sidebar = ({ post }) => ( <header className={`intro-header col-lg-2 col-xs-12 order-lg-1 ${post === true ? 'order-md-10 order-10' : 'order-1'}`} > <div className="site-heading text-center"> <div className="about-me"> <LazyLoad height={200}> <img className="avatar" src="https://calpa.me/img/profile.png" alt="Calpa" /> </LazyLoad> <h4>Calpa</h4> <p>夢裡不覺秋已深</p> <p>餘情豈是為他人</p> </div> </div> </header> ); Sidebar.propTypes = { post: PropTypes.bool, }; Sidebar.defaultProps = { post: false, }; export default Sidebar;
import React from 'react'; import LazyLoad from 'react-lazyload'; import './index.scss'; const Sidebar = ({ post = false }) => ( <header className={` intro-header col-lg-2 col-xs-12 order-lg-1 ${post === true ? 'order-md-10 order-10' : 'order-1'} `} > <div className="site-heading text-center"> <div className="about-me"> <LazyLoad height={200}> <img className="avatar" src="https://calpa.me/img/profile.png" alt="Calpa" /> </LazyLoad> <h4>Calpa</h4> <p>夢裡不覺秋已深</p> <p>餘情豈是為他人</p> </div> </div> </header> ); export default Sidebar;
Add hashes for inline styles to CSP (temporary hack)
<?php /* generate a nonce which should be completely unpredictable, for use by inline script tags */ $csp_nonce = substr(base64_encode(hash("sha256", $_SERVER["UNIQUE_ID"] . $_SERVER["REQUEST_TIME_FLOAT"] . openssl_random_pseudo_bytes(6), true)), 0, 20); $csp = "Content-Security-Policy: default-src 'none'; " . "connect-src 'self'; img-src 'self'; " . "font-src https://cdnjs.cloudflare.com https://fonts.gstatic.com; " . "script-src 'self' 'nonce-{$csp_nonce}' https://cdnjs.cloudflare.com https://ajax.googleapis.com; " . "style-src 'self' https://cdnjs.cloudflare.com https://ajax.googleapis.com https://fonts.googleapis.com " . "'sha256-UiXlt9djFx1o7crFtCH7sUqquV6B2BX9ozY9jqs43JE=' 'sha256-UiXlt9djFx1o7crFtCH7sUqquV6B2BX9ozY9jqs43JE=' " . "'sha256-t6oewASd7J1vBg5mQtX4hl8bg8FeegYFM3scKLIhYUc=' 'sha256-47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU='; "; /* the last 2 lines above are a hack to allow inline styles such as "style='width:100%'" but need a better more scalable solution */ header($csp);
<?php /* generate a nonce which should be completely unpredictable, for use by inline script tags */ $csp_nonce = substr(base64_encode(hash("sha256", $_SERVER["UNIQUE_ID"] . $_SERVER["REQUEST_TIME_FLOAT"] . openssl_random_pseudo_bytes(6), true)), 0, 20); $csp = "Content-Security-Policy: default-src 'none'; " . "connect-src 'self'; img-src 'self'; " . "font-src https://cdnjs.cloudflare.com https://fonts.gstatic.com; " . "script-src 'self' 'nonce-{$csp_nonce}' https://cdnjs.cloudflare.com https://ajax.googleapis.com; " . "style-src 'self' https://cdnjs.cloudflare.com https://ajax.googleapis.com https://fonts.googleapis.com;"; header($csp);
Edit comment to describe the difficulty more clearly.
/* * site: codemelon2012 * file: scripts/main.js * author: Marshall Farrier * date: 8/24/2012 * description: * main JavaScript for codemelon2012 * links: * http://code.google.com/p/jquery-rotate/ (if needed) */ function codeMelonMain(activePage) { if (!$.support.boxModel) { window.location.replace("templates/no-boxmodel.html"); } navigationMain(activePage); logoMain(activePage); /* * The top of the gray footer is sometimes about 32px too high up on the page in Chrome. * This is presumably because the function is sometimes called asynchronously before * the rest of the page is set up. The call on resize is working fine. */ backgroundMain(); $(window).resize(backgroundMain); }
/* * site: codemelon2012 * file: scripts/main.js * author: Marshall Farrier * date: 8/24/2012 * description: * main JavaScript for codemelon2012 * links: * http://code.google.com/p/jquery-rotate/ (if needed) */ function codeMelonMain(activePage) { if (!$.support.boxModel) { window.location.replace("templates/no-boxmodel.html"); } navigationMain(activePage); logoMain(activePage); /* * This sometimes doesn't work properly in Chrome (overlap at the bottom is too big). * This is presumably because the function is sometimes called asynchronously before * the rest of the page is set up. The call on resize is working fine. */ backgroundMain(); $(window).resize(backgroundMain); }
Change package owner and homepage
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 KenTyde # All rights reserved. # # This software is licensed as described in the file LICENSE, # which you should have received as part of this distribution. from setuptools import setup import os desc = open(os.path.join(os.path.dirname(__file__), 'README')).read() setup( name='fixlib', version='0.5', description='Pythonic library for dealing with the FIX protocol', long_description=desc, author='Dirkjan Ochtman', author_email='dirkjan@ochtman.nl', license='BSD', url='https://github.com/djc/fixlib', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Financial and Insurance Industry', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['fixlib'], test_suite='fixlib.tests.suite', )
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (C) 2010 KenTyde # All rights reserved. # # This software is licensed as described in the file LICENSE, # which you should have received as part of this distribution. from setuptools import setup import os desc = open(os.path.join(os.path.dirname(__file__), 'README')).read() setup( name='fixlib', version='0.5', description='Pythonic library for dealing with the FIX protocol', long_description=desc, author='Dirkjan Ochtman', author_email='djc.ochtman@kentyde.com', license='BSD', url='http://source.kentyde.com/fixlib', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Financial and Insurance Industry', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], packages=['fixlib'], test_suite='fixlib.tests.suite', )
Change python module author to @tonyseek
#!/usr/bin/env python from setuptools import setup def fread(filepath): with open(filepath, 'r') as f: return f.read() setup( name='GB2260', version='0.1.0', author='TonySeek', author_email='tonyseek@gmail.com', url='https://github.com/cn/GB2260', packages=['gb2260'], description='The Python implementation for looking up the Chinese ' 'administrative divisions.', long_description=fread('README.rst'), license='BSD', include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD License', 'Natural Language :: Chinese (Simplified)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
#!/usr/bin/env python from setuptools import setup def fread(filepath): with open(filepath, 'r') as f: return f.read() setup( name='GB2260', version='0.1.0', author='Hsiaoming Yang', author_email='me@lepture.com', url='https://github.com/cn/GB2260', packages=['gb2260'], description='The Python implementation for looking up the Chinese ' 'administrative divisions.', long_description=fread('README.rst'), license='BSD', include_package_data=True, classifiers=[ 'Development Status :: 3 - Alpha', 'License :: OSI Approved :: BSD License', 'Natural Language :: Chinese (Simplified)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: Implementation :: CPython', 'Programming Language :: Python :: Implementation :: PyPy', ] )
Check for p = 0.00 #149
# -*- coding: utf-8 -*- """Psychological and psychiatric terms to avoid. --- layout: post source: Scott O. Lilienfeld, et al. source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100 title: psychological and psychiatric terms to avoid date: 2014-06-10 12:31:19 categories: writing --- Psychological and psychiatric terms to avoid. """ from tools import preferred_forms_check, existence_check, memoize @memoize def check_lie_detector_test(text): """Suggest the preferred forms.""" err = "lilienfeld.terms_to_avoid.lie_detector" msg = "Polygraph machines measure arousal, not lying per se. Try {}." list = [ ["polygraph test", ["lie detector test"]], ["polygraph machine", ["lie detector machine"]], ] return preferred_forms_check(text, list, err, msg) @memoize def check_p_equals_zero(text): """Check for p = 0.000.""" err = "lilienfeld.terms_to_avoid.p_equals_zero" msg = "Unless p really equals zero, you should use more decimal places." list = [ "p = 0.00", "p = 0.000", "p = 0.0000", ] return existence_check(text, list, err, msg, join=True)
# -*- coding: utf-8 -*- """Psychological and psychiatric terms to avoid. --- layout: post source: Scott O. Lilienfeld, et al. source_url: http://dx.doi.org/10.3389/fpsyg.2015.01100 title: psychological and psychiatric terms to avoid date: 2014-06-10 12:31:19 categories: writing --- Psychological and psychiatric terms to avoid. """ from tools import preferred_forms_check, memoize @memoize def check_lie_detector_test(text): """Suggest the preferred forms.""" err = "lilienfeld.terms_to_avoid.lie_detector" msg = "Polygraph machines measure arousal, not lying per se. Try {}." list = [ ["polygraph test", ["lie detector test"]], ["polygraph machine", ["lie detector machine"]], ] return preferred_forms_check(text, list, err, msg)
Make bot functionality publicly available
<?php namespace eHOSP\Http\Controllers\API\v1; use Illuminate\Http\Request; use Illuminate\Http\Response; use eHOSP\Http\Requests; use eHOSP\Http\Controllers\Controller; class Bot extends Controller { public function __construct() { // $this->middleware('auth:api'); } public function index(Request $request) { // Retrieve text that user typed to bot $request_text = $request->input('text'); // Call Hospbot throught eHOSP webhook $http = new \GuzzleHttp\Client; $post_url = env('HOSPBOT_WEBHOOK_URL'); $response = $http->post($post_url, [ 'form_params' => [ 'message' => $request_text ], ]); return $response->getBody(); } }
<?php namespace eHOSP\Http\Controllers\API\v1; use Illuminate\Http\Request; use Illuminate\Http\Response; use eHOSP\Http\Requests; use eHOSP\Http\Controllers\Controller; class Bot extends Controller { public function __construct() { $this->middleware('auth:api'); } public function index(Request $request) { // Retrieve text that user typed to bot $request_text = $request->input('text'); // Call Hospbot throught eHOSP webhook $http = new \GuzzleHttp\Client; $post_url = env('HOSPBOT_WEBHOOK_URL'); $response = $http->post($post_url, [ 'form_params' => [ 'message' => $request_text ], ]); return $response->getBody(); } }
Fix typo in error message
/* * Copyright 2016 Martijn van der Woud - The Crimson Cricket Internet Services * * 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.crimsoncricket.ddd.domain.model; import javax.persistence.MappedSuperclass; import javax.persistence.Version; @MappedSuperclass public class AggregateRoot<I extends Id> extends Entity<I> { @Version private Integer version; protected AggregateRoot() {} public AggregateRoot(I id) { super(id); } public Integer version() { return version; } protected void ensureVersionIs(int expectedVersion) throws OutdatedEntityVersionException { if (version != expectedVersion) throw new OutdatedEntityVersionException( "Attempted to execute a command on an outdated entity of type " + this.getClass().getSimpleName(), expectedVersion, version); } }
/* * Copyright 2016 Martijn van der Woud - The Crimson Cricket Internet Services * * 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.crimsoncricket.ddd.domain.model; import javax.persistence.MappedSuperclass; import javax.persistence.Version; @MappedSuperclass public class AggregateRoot<I extends Id> extends Entity<I> { @Version private Integer version; protected AggregateRoot() {} public AggregateRoot(I id) { super(id); } public Integer version() { return version; } protected void ensureVersionIs(int expectedVersion) throws OutdatedEntityVersionException { if (version != expectedVersion) throw new OutdatedEntityVersionException( "Attempted to executed a command on an outdated entity of type " + this.getClass().getSimpleName(), expectedVersion, version); } }
Make examples build more verbose
var childProcess = require('child_process'); var fs = require('fs'); process.chdir('examples'); childProcess.execSync('npm install', { stdio: 'inherit' }); childProcess.execSync('npm run update', { stdio: 'inherit' }); process.chdir('..'); // Build all of the example folders. dirs = fs.readdirSync('examples'); var cmd; for (var i = 0; i < dirs.length; i++) { if (dirs[i].indexOf('.') !== -1) { continue; } if (dirs[i].indexOf('node_modules') !== -1) { continue; } console.log('\n***********\nBuilding: ' + dirs[i] + '...'); process.chdir('examples/' + dirs[i]); childProcess.execSync('npm run build', { stdio: 'inherit' }); process.chdir('../..'); } console.log('\n********\nDone!');
var childProcess = require('child_process'); var fs = require('fs'); process.chdir('examples'); childProcess.execSync('npm install', { stdio: 'inherit' }); childProcess.execSync('npm run update', { stdio: 'inherit' }); process.chdir('..'); // Build all of the example folders. dirs = fs.readdirSync('examples'); var cmd; for (var i = 0; i < dirs.length; i++) { if (dirs[i].indexOf('.') !== -1) { continue; } if (dirs[i].indexOf('node_modules') !== -1) { continue; } console.log('Building: ' + dirs[i] + '...'); process.chdir('examples/' + dirs[i]); childProcess.execSync('npm run build', { stdio: 'inherit' }); process.chdir('../..'); }
Reset commandbar input after pressing return
import React from 'react'; import './CommandBar.css'; export default class CommandBar extends React.Component { onTextChange(eventArgs) { const { onCommandChange } = this.props; if (eventArgs.keyCode === 13) { //return onCommandChange(this.refs.commandText.value); this.refs.commandText.value = ''; } } render() { const { commandError, modal } = this.props; const classNames = modal ? "commandbar modal" : "commandbar inline"; return ( <div className={classNames}> <div> <span className="input-prefix">&gt;</span> <span><input ref="commandText" type="text" onKeyDown={this.onTextChange.bind(this)} /></span> </div> <div className="error-message"> {commandError} </div> </div> ); } }
import React from 'react'; import './CommandBar.css'; export default class CommandBar extends React.Component { onTextChange(eventArgs) { const { onCommandChange } = this.props; if (eventArgs.keyCode === 13) { //return onCommandChange(this.refs.commandText.value); } } render() { const { commandError, modal } = this.props; const classNames = modal ? "commandbar modal" : "commandbar inline"; return ( <div className={classNames}> <div> <span className="input-prefix">&gt;</span> <span><input ref="commandText" type="text" onKeyDown={this.onTextChange.bind(this)} /></span> </div> <div className="error-message"> {commandError} </div> </div> ); } }
Add limit of 5 post revisions
<?php /** Include Genesis to use with WordPress */ require_once(dirname(__FILE__) . '/../bower_components/genesis-wordpress/src/Genesis.php'); <%= wpConfigFile // Already started PHP .replace('<?php', '') // Replace DB_* .replace('database_name_here', props.DB_NAME) .replace('username_here', props.DB_USER) .replace('password_here', props.DB_PASSWORD) .replace('localhost', props.DB_HOST) // Replace WP_DEBUG .replace(/define\('WP_DEBUG'.+\);/, "define('WP_DEBUG', Genesis::isDebug());") // Replace salts .replace(/define\('AUTH_KEY'[\s\S]+'put your unique phrase here'\);/, props.salts) // Limit to 5 post revisions .replace("/* That's all,", "define('WP_POST_REVISIONS', 5);\n\n/*That's all,") %> if (Genesis::isDebug()) { Genesis::rewriteUrls(); }
<?php /** Include Genesis to use with WordPress */ require_once(dirname(__FILE__) . '/../bower_components/genesis-wordpress/src/Genesis.php'); <%= wpConfigFile // Already started PHP .replace('<?php', '') // Replace DB_* .replace('database_name_here', props.DB_NAME) .replace('username_here', props.DB_USER) .replace('password_here', props.DB_PASSWORD) .replace('localhost', props.DB_HOST) // Replace WP_DEBUG .replace(/define\('WP_DEBUG'.+\);/, "define('WP_DEBUG', Genesis::isDebug());") // Replace salts .replace(/define\('AUTH_KEY'[\s\S]+'put your unique phrase here'\);/, props.salts) %> if (Genesis::isDebug()) { Genesis::rewriteUrls(); }
Set ImageJ to headless in main method
/* * #%L * ImageJ server for RESTful access to ImageJ. * %% * Copyright (C) 2013 - 2016 Board of Regents of the University of * Wisconsin-Madison. * %% * 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 net.imagej.server; import net.imagej.ImageJ; /** * Main class for imagej-server. * * @author Leon Yang */ public class Main { public static void main(String[] args) throws Exception { final ImageJ ij = new ImageJ(); ij.ui().setHeadless(true); final String[] arguments = args == null || args.length == 0 ? new String[] { "server", "imagej-server.yml" } : args; final ImageJServerApplication app = new ImageJServerApplication(ij .context()); app.run(arguments); app.join(); ij.context().dispose(); } }
/* * #%L * ImageJ server for RESTful access to ImageJ. * %% * Copyright (C) 2013 - 2016 Board of Regents of the University of * Wisconsin-Madison. * %% * 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 net.imagej.server; import net.imagej.ImageJ; /** * Main class for imagej-server. * * @author Leon Yang */ public class Main { public static void main(String[] args) throws Exception { final ImageJ ij = new ImageJ(); final String[] arguments = args == null || args.length == 0 ? new String[] { "server", "imagej-server.yml" } : args; final ImageJServerApplication app = new ImageJServerApplication(ij .context()); app.run(arguments); app.join(); ij.context().dispose(); } }
Use the el reference instead of the vm reference
import { util } from 'vue'; export var directive = { acceptStatement: true, priority: 700, update: function(handler) { if (typeof handler !== 'function') { if (process.env.NODE_ENV !== 'production') { util.warn( this.name + '="' + this.expression + '" expects a function value, ' + 'got ' + handler ); } return; } this.reset(); var el = this.el; var scope = this._scope || this.vm; this.handler = function(ev) { // @NOTE: IE 5.0+ // @REFERENCE: https://developer.mozilla.org/en/docs/Web/API/Node/contains if (!el.contains(ev.target)) { scope.$event = ev; var res = handler(ev); scope.$event = null; return res; } }; util.on(document.documentElement, 'click', this.handler); }, reset: function() { util.off(document.documentElement, 'click', this.handler); }, unbind: function() { this.reset(); }, }; export var mixin = { directives: { onClickaway: directive }, };
import { util } from 'vue'; export var directive = { acceptStatement: true, priority: 700, update: function(handler) { if (typeof handler !== 'function') { if (process.env.NODE_ENV !== 'production') { util.warn( this.name + '="' + this.expression + '" expects a function value, ' + 'got ' + handler ); } return; } this.reset(); var self = this; var scope = this._scope || this.vm; this.handler = function(ev) { // @NOTE: IE 5.0+ // @REFERENCE: https://developer.mozilla.org/en/docs/Web/API/Node/contains if (!self.el.contains(ev.target)) { scope.$event = ev; var res = handler(ev); scope.$event = null; return res; } }; util.on(document.documentElement, 'click', this.handler); }, reset: function() { util.off(document.documentElement, 'click', this.handler); }, unbind: function() { this.reset(); }, }; export var mixin = { directives: { onClickaway: directive }, };
Fix deprecation warning on v0.7.x
/** * package - Easy package.json exports. * * Author: Veselin Todorov <hi@vesln.com> * Licensed under the MIT License. */ /** * Dependencies. */ var fs = require('fs'); var path = require('path'); var exists = fs.existsSync || path.existsSync; /** * Package. * * @param {String|null} location * @returns {Object} package.json data */ var package = function(location) { if (location === Object(location)) { location = package.discover(location); } return package.read(path.normalize(location + '/package.json')); }; /** * Reads and parses a package.json file. * * @param {String} file * @returns {Object} package.json data */ package.read = function(file) { var data = fs.readFileSync(file, 'utf8'); return JSON.parse(data); }; /** * Makes an atempt to find package.json file. * * @returns {Object} package.json data */ package.discover = function(module) { var location = path.dirname(module.filename); var found = null; while (!found) { if (exists(location + '/package.json')) { found = location; } else if (location !== '/') { location = path.dirname(location); } else { throw new Error('package.json can not be located'); } } return found; }; /** * Exporting the lib. */ module.exports = package;
/** * package - Easy package.json exports. * * Author: Veselin Todorov <hi@vesln.com> * Licensed under the MIT License. */ /** * Dependencies. */ var fs = require('fs'); var path = require('path'); /** * Package. * * @param {String|null} location * @returns {Object} package.json data */ var package = function(location) { if (location === Object(location)) { location = package.discover(location); } return package.read(path.normalize(location + '/package.json')); }; /** * Reads and parses a package.json file. * * @param {String} file * @returns {Object} package.json data */ package.read = function(file) { var data = fs.readFileSync(file, 'utf8'); return JSON.parse(data); }; /** * Makes an atempt to find package.json file. * * @returns {Object} package.json data */ package.discover = function(module) { var location = path.dirname(module.filename); var found = null; while (!found) { if (path.existsSync(location + '/package.json')) { found = location; } else if (location !== '/') { location = path.dirname(location); } else { throw new Error('package.json can not be located'); } } return found; }; /** * Exporting the lib. */ module.exports = package;
Fix test so it doesn't have side-effects
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugins = plugin_store['imread'] plugin_store['imread'] = [] try: io.imread(image_path) finally: plugin_store['imread'] = plugins if __name__ == "__main__": run_module_suite()
import os from numpy.testing import assert_array_equal, raises, run_module_suite import numpy as np import skimage.io as io from skimage.io._plugins.plugin import plugin_store from skimage import data_dir def test_stack_basic(): x = np.arange(12).reshape(3, 4) io.push(x) assert_array_equal(io.pop(), x) @raises(ValueError) def test_stack_non_array(): io.push([[1, 2, 3]]) def test_imread_url(): # tweak data path so that file URI works on both unix and windows. data_path = data_dir.lstrip(os.path.sep) data_path = data_path.replace(os.path.sep, '/') image_url = 'file:///{0}/camera.png'.format(data_path) image = io.imread(image_url) assert image.shape == (512, 512) @raises(RuntimeError) def test_imread_no_plugin(): # tweak data path so that file URI works on both unix and windows. image_path = os.path.join(data_dir, 'lena.png') plugin_store['imread'] = [] io.imread(image_path) if __name__ == "__main__": run_module_suite()
Remove unnecessary assertion for `Ember.inspect` The assertion for `Ember.inspect` with error object depends on `Error#toString`. It returns the value that provided by each environments.
module("Ember.inspect"); var inspect = Ember.inspect; test("strings", function() { equal(inspect("foo"), "foo"); }); test("numbers", function() { equal(inspect(2.6), "2.6"); }); test("null", function() { equal(inspect(null), "null"); }); test("undefined", function() { equal(inspect(undefined), "undefined"); }); test("true", function() { equal(inspect(true), "true"); }); test("false", function() { equal(inspect(false), "false"); }); test("object", function() { equal(inspect({}), "{}"); equal(inspect({ foo: 'bar' }), "{foo: bar}"); equal(inspect({ foo: Ember.K }), "{foo: function() { ... }}"); }); test("array", function() { equal(inspect([1,2,3]), "[1,2,3]"); }); test("regexp", function() { equal(inspect(/regexp/), "/regexp/"); }); test("date", function() { var inspected = inspect(new Date("Sat Apr 30 2011 13:24:11")); ok(inspected.match(/Sat Apr 30/), "The inspected date has its date"); ok(inspected.match(/2011/), "The inspected date has its year"); ok(inspected.match(/13:24:11/), "The inspected date has its time"); });
module("Ember.inspect"); var inspect = Ember.inspect; test("strings", function() { equal(inspect("foo"), "foo"); }); test("numbers", function() { equal(inspect(2.6), "2.6"); }); test("null", function() { equal(inspect(null), "null"); }); test("undefined", function() { equal(inspect(undefined), "undefined"); }); test("true", function() { equal(inspect(true), "true"); }); test("false", function() { equal(inspect(false), "false"); }); test("object", function() { equal(inspect({}), "{}"); equal(inspect({ foo: 'bar' }), "{foo: bar}"); equal(inspect({ foo: Ember.K }), "{foo: function() { ... }}"); }); test("array", function() { equal(inspect([1,2,3]), "[1,2,3]"); }); test("regexp", function() { equal(inspect(/regexp/), "/regexp/"); }); test("date", function() { var inspected = inspect(new Date("Sat Apr 30 2011 13:24:11")); ok(inspected.match(/Sat Apr 30/), "The inspected date has its date"); ok(inspected.match(/2011/), "The inspected date has its year"); ok(inspected.match(/13:24:11/), "The inspected date has its time"); }); test("error", function() { equal(inspect(new Error("Oops")), "Error: Oops"); });
Hide loading text after loading is complete
$().ready(() => { loadContentSection().then(() =>{ $("body").children(":not(#real-body)").addClass("hide"); $("#real-body").removeClass("hide").addClass("body"); }); }); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } });
$().ready(() => { loadContentSection().then(() =>{ $("#loader").addClass("hide"); $("#real-body").removeClass("hide"); $("#real-body").addClass("body"); }); }); $("body").on('click', '.keyword', function() { $(this).addClass("active"); $(".base").hide(200); $("#real-body").addClass("focus"); }); $("body").on('click', ".close", function(event) { event.stopPropagation(); $(".extended").removeClass("extended"); $(this).parent().removeClass("active"); $(".base").show(200); $("#real-body").removeClass("focus"); }); $("body").on('click', ".active .item", function() { $(".item").off("click"); const url = $(this).attr("data-url"); window.location.href = url; }); $("body").on('click', '.level-name', function() { const isThisExtended = $(this).parent().hasClass("extended"); $(".extended").removeClass("extended"); if (!isThisExtended) { $(this).parent().addClass("extended"); } });
Add code to exception message since name can be null
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Calculator; use Sylius\Component\Core\Exception\MissingChannelConfigurationException; use Sylius\Component\Core\Model\ProductVariantInterface; use Webmozart\Assert\Assert; final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface { /** * {@inheritdoc} */ public function calculate(ProductVariantInterface $productVariant, array $context): int { Assert::keyExists($context, 'channel'); $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']); if (null === $channelPricing) { throw new MissingChannelConfigurationException(sprintf( 'Channel %s has no price defined for product variant %s (%s)', $context['channel']->getName(), $productVariant->getName(), $productVariant->getCode() )); } return $channelPricing->getPrice(); } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Component\Core\Calculator; use Sylius\Component\Core\Exception\MissingChannelConfigurationException; use Sylius\Component\Core\Model\ProductVariantInterface; use Webmozart\Assert\Assert; final class ProductVariantPriceCalculator implements ProductVariantPriceCalculatorInterface { /** * {@inheritdoc} */ public function calculate(ProductVariantInterface $productVariant, array $context): int { Assert::keyExists($context, 'channel'); $channelPricing = $productVariant->getChannelPricingForChannel($context['channel']); if (null === $channelPricing) { throw new MissingChannelConfigurationException(sprintf( 'Channel %s has no price defined for product variant %s', $context['channel']->getName(), $productVariant->getName() )); } return $channelPricing->getPrice(); } }