text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
map: Add mapping for 'Chrome Mobile' -> 'Android Browser' BrowserStack v4 has back-compat mapping that is actually working against us in this case..
/** * We need to map identifiers between TestSwarm and BrowserStack. * * Sources: * - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php * - ua-parser: https://github.com/ua-parser/uap-core * - BrowserStack: * https://github.com/browserstack/api * http://api.browserstack.com/3/browsers (requires authentication) */ // These are in the direction testswarm (ua-parser) -> browserstack. module.exports = { browserFamily: { 'Yandex Browser': 'yandex', 'Android': 'Android Browser', // Android 4.4 and higher use Chrome Mobile instead of Android Browser. // BrowserStack supports both Chrome and Firefox on Android through // the UI. However, the v4 API only exposes one of them (Chrome) // but labels it "Android Browser" for back-compat. 'Chrome Mobile': 'Android Browser' }, osFamily: { 'Windows': 'Windows', 'Mac OS X': 'OS X', 'Android': 'android', 'iOS': 'ios' }, // BrowserStack puts device version inside device family. // Normalise them here, we use OS version instead. deviceFamily: { // Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc. 'iPad': /^iPad\b/, // Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc. 'iPhone': /^iPhone\b/ } };
/** * We need to map identifiers between TestSwarm and BrowserStack. * * Sources: * - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php * - ua-parser: https://github.com/ua-parser/uap-core * - BrowserStack: * https://github.com/browserstack/api * http://api.browserstack.com/3/browsers (requires authentication) */ // These are in the direction testswarm (ua-parser) -> browserstack. module.exports = { browserFamily: { 'Yandex Browser': 'yandex', 'Android': 'Android Browser' }, osFamily: { 'Windows': 'Windows', 'Mac OS X': 'OS X', 'Android': 'android', 'iOS': 'ios' }, // BrowserStack puts device version inside device family. // Normalise them here, we use OS version instead. deviceFamily: { // Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc. 'iPad': /^iPad\b/, // Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc. 'iPhone': /^iPhone\b/ } };
Update requests requirement to >=2.4.2,<2.20 Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version. - [Release notes](https://github.com/requests/requests/releases) - [Changelog](https://github.com/requests/requests/blob/master/HISTORY.rst) - [Commits](https://github.com/requests/requests/commits/v2.19.1) Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.0.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.20', 'future>=0.16,<0.17', 'python-magic>=0.4,<0.5', ], extras_require={ 'testing': [ 'mock>=2.0,<2.1', ], 'docs': [ 'sphinx', ] } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.0.1', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.19', 'future>=0.16,<0.17', 'python-magic>=0.4,<0.5', ], extras_require={ 'testing': [ 'mock>=2.0,<2.1', ], 'docs': [ 'sphinx', ] } )
Update migration file for namechange
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2017-02-21 02:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seedlibrary', '0002_add_extendedview'), ] operations = [ migrations.RenameField( model_name='extendedview', old_name='external_field', new_name='external_url', ), migrations.AddField( model_name='extendedview', name='grain_subcategory', field=models.CharField(blank=True, max_length=50), ), ]
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2017-02-21 02:55 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('seedlibrary', '0002_auto_20170219_2058'), ] operations = [ migrations.RenameField( model_name='extendedview', old_name='external_field', new_name='external_url', ), migrations.AddField( model_name='extendedview', name='grain_subcategory', field=models.CharField(blank=True, max_length=50), ), ]
Improve the game database update to new version - add old version check for not do incompatible update - converted to utf8 and added indentation
<?php if((empty($int_security)) OR ($int_security!=$game_se_code)){ header("Location: ../../index.php?error=16"); exit(); } $oldversion="0.8.0"; $newversion="0.8.1"; foreach($game_server as $chiave=>$elemento){ $db->Setdb($chiave); $check=$db->QuerySelect("SELECT version FROM config WHERE id=".$chiave); if($check['version']==$oldversion AND $newversion==$game_version){ $db->QueryMod(""); $db->QueryMod("UPDATE `config` SET version='".$newversion."' WHERE id=".$chiave); echo sprintf($lang['aggiornato_db_server'],$chiave,$newversion)."<br />"; }else{ echo sprintf($lang['non_aggiornato_db_server'],$chiave)."<br />"; } }//end for each server ?>
<?php if((empty($int_security)) OR ($int_security!=$game_se_code)){ header("Location: ../../index.php?error=16"); exit(); } $newversion="0.8.1"; foreach($game_server as $chiave=>$elemento){ if($chiave!=999){ $db->Setdb($chiave); $check=$db->QuerySelect("SELECT version FROM config WHERE id=".$chiave); if($check['version']!=$newversion AND $newversion==$game_version){ $db->QueryMod(""); $db->QueryMod("UPDATE `config` SET version='".$newversion."' WHERE id=".$chiave); echo sprintf($lang['aggiornato_db_server'],$chiave,$newversion)."<br />"; }/*se non aggiornato*/else{ echo sprintf($lang['non_aggiornato_db_server'],$chiave)."<br />"; } }//se non quello di sviluppo principale }//fine per ogni server ?>
Update vers to new loader format
define(['mac/roman'], function(macintoshRoman) { 'use strict'; return function(item) { return item.getBytes().then(function(bytes) { var dataObject = { major: bytes[0], minor: bytes[1], developmentStage: (function(v) { switch(v) { case 0x20: return 'development'; case 0x40: return 'alpha'; case 0x60: return 'beta'; case 0x80: return 'release'; default: return v; } })(bytes[2]), prereleaseRevisionLevel: bytes[3], regionCode: (bytes[4] << 8) | bytes[5], }; dataObject.versionNumber = macintoshRoman(bytes, 7, bytes[6]); var pos = 7 + bytes[6]; dataObject.versionMessage = macintoshRoman(bytes, pos + 1, bytes[pos]); item.setDataObject(dataObject); }); }; });
define(['mac/roman'], function(macintoshRoman) { 'use strict'; return function(resource) { resource.dataObject = { major: resource.data[0], minor: resource.data[1], developmentStage: (function(v) { switch(v) { case 0x20: return 'development'; case 0x40: return 'alpha'; case 0x60: return 'beta'; case 0x80: return 'release'; default: return v; } })(resource.data[2]), prereleaseRevisionLevel: resource.data[3], regionCode: (resource.data[4] << 8) | resource.data[5], }; resource.dataObject.versionNumber = macintoshRoman(resource.data, 7, resource.data[6]); var pos = 7 + resource.data[6]; resource.dataObject.versionMessage = macintoshRoman(resource.data, pos + 1, resource.data[pos]); }; });
Remove search from location on cancel
'use strict'; angular.module('Teem') .factory('NewForm', [ '$location', '$window', function($location, $window) { var scope, objectName, scopeFn = { isNew () { return $location.search().form === 'new'; }, cancelNew () { scope[objectName].delete(); $location.search('form', undefined); $window.history.back(); }, confirmNew () { $location.search('form', undefined); } }; function initialize(s, o) { scope = s; objectName = o; Object.assign(scope, scopeFn); } return { initialize }; }]);
'use strict'; angular.module('Teem') .factory('NewForm', [ '$location', '$window', function($location, $window) { var scope, objectName, scopeFn = { isNew () { return $location.search().form === 'new'; }, cancelNew () { scope[objectName].delete(); $window.history.back(); }, confirmNew () { $location.search('form', undefined); } }; function initialize(s, o) { scope = s; objectName = o; Object.assign(scope, scopeFn); } return { initialize }; }]);
Fix seconds part of play time showing incorrectly in range [59.5, 60.0) This effectively rolls back the commit 989d5fb3. Using `round` instead of `floor` for the seconds of the playtime wasn't such a great idea after all, because it made the time stamp to show up like "0:60" for a half a second before it changed to "1:00". It would have been possible to keep the rounding to closest by altering the logic for minutes and seconds parts, but the rounding had also a second minor issue: the play time changed from 0:00 to 0:01 already after playing for half a second which isn't quite how a time display is assumed to work, normally. refs #814
/** * ownCloud - Music app * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Morris Jobke <morris.jobke@gmail.com> * @author Pauli Järvinen <pauli.jarvinen@gmail.com> * @copyright 2013 Morris Jobke * @copyright 2020, 2021 Pauli Järvinen * */ angular.module('Music').filter('playTime', function() { return function(input) { var hours = Math.floor(input / 3600); var minutes = Math.floor((input - hours*3600) / 60); var seconds = Math.floor(input % 60); if (hours > 0) { return hours + ':' + fmtTwoDigits(minutes) + ':' + fmtTwoDigits(seconds); } else { return minutes + ':' + fmtTwoDigits(seconds); } }; // Format the given integer with two digits, prepending with a leading zero if necessary function fmtTwoDigits(integer) { return (integer < 10 ? '0' : '') + integer; } });
/** * ownCloud - Music app * * This file is licensed under the Affero General Public License version 3 or * later. See the COPYING file. * * @author Morris Jobke <morris.jobke@gmail.com> * @author Pauli Järvinen <pauli.jarvinen@gmail.com> * @copyright 2013 Morris Jobke * @copyright 2020 Pauli Järvinen * */ angular.module('Music').filter('playTime', function() { return function(input) { var hours = Math.floor(input / 3600); var minutes = Math.floor((input - hours*3600) / 60); var seconds = Math.round(input % 60); if (hours > 0) { return hours + ':' + fmtTwoDigits(minutes) + ':' + fmtTwoDigits(seconds); } else { return minutes + ':' + fmtTwoDigits(seconds); } }; // Format the given integer with two digits, prepending with a leading zero if necessary function fmtTwoDigits(integer) { return (integer < 10 ? '0' : '') + integer; } });
Add return to ensure prodution settings command to get exit status of command
<?php /* * This file is part of the Doctrine Bundle * * The code was originally distributed inside the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * (c) Doctrine Project, Benjamin Eberlei <kontakt@beberlei.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand; /** * Ensure the Doctrine ORM is configured properly for a production environment. * * @author Fabien Potencier <fabien@symfony.com> * @author Jonathan H. Wage <jonwage@gmail.com> */ class EnsureProductionSettingsDoctrineCommand extends EnsureProductionSettingsCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:ensure-production-settings') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); return parent::execute($input, $output); } }
<?php /* * This file is part of the Doctrine Bundle * * The code was originally distributed inside the Symfony framework. * * (c) Fabien Potencier <fabien@symfony.com> * (c) Doctrine Project, Benjamin Eberlei <kontakt@beberlei.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Doctrine\Bundle\DoctrineBundle\Command\Proxy; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand; /** * Ensure the Doctrine ORM is configured properly for a production environment. * * @author Fabien Potencier <fabien@symfony.com> * @author Jonathan H. Wage <jonwage@gmail.com> */ class EnsureProductionSettingsDoctrineCommand extends EnsureProductionSettingsCommand { /** * {@inheritDoc} */ protected function configure() { parent::configure(); $this ->setName('doctrine:ensure-production-settings') ->addOption('em', null, InputOption::VALUE_OPTIONAL, 'The entity manager to use for this command'); } /** * {@inheritDoc} */ protected function execute(InputInterface $input, OutputInterface $output) { DoctrineCommandHelper::setApplicationEntityManager($this->getApplication(), $input->getOption('em')); parent::execute($input, $output); } }
Revert "Pinning restclients to 1.1." This reverts commit 0d33ddd392d33c7eca57289554feedd25b851ca2.
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot', version='0.1', packages=['mdot'], include_package_data=True, install_requires=[ 'setuptools', 'django<1.9rc1', 'django-compressor', 'django_mobileesp', 'uw-restclients', 'django-htmlmin', ], license='Apache License, Version 2.0', description='A Django app to ...', long_description=README, url='http://www.example.com/', author='Your Name', author_email='yourname@example.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from setuptools import setup README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name='mdot', version='0.1', packages=['mdot'], include_package_data=True, install_requires=[ 'setuptools', 'django<1.9rc1', 'django-compressor', 'django_mobileesp', 'uw-restclients==1.1', 'django-htmlmin', ], license='Apache License, Version 2.0', description='A Django app to ...', long_description=README, url='http://www.example.com/', author='Your Name', author_email='yourname@example.com', classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Fix undefined telescope on createUser
Accounts.onCreateUser(function(options, user){ user = Telescope.callbacks.run("onCreateUser", user, options); // get facebook profile picture if (options.profile) { if(user.services.facebook) { options.profile.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large"; var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + user.services.facebook.id + '?access_token=' + user.services.facebook.accessToken + '&fields=first_name, last_name, birthday, email, gender, location, link, friends'); //console.log(result.data.birthday); if(result.data.birthday) user.telescope.birthday = result.data.birthday; if(user.services.facebook.gender) user.telescope.gender = user.services.facebook.gender; if(user.telescope) user.telescope.email = user.services.facebook.email; } user.profile = options.profile; } return user; });
Accounts.onCreateUser(function(options, user){ user = Telescope.callbacks.run("onCreateUser", user, options); // get facebook profile picture if (options.profile) { if(user.services.facebook) { options.profile.picture = "http://graph.facebook.com/" + user.services.facebook.id + "/picture/?type=large"; var result = Meteor.http.get('https://graph.facebook.com/v2.4/' + user.services.facebook.id + '?access_token=' + user.services.facebook.accessToken + '&fields=first_name, last_name, birthday, email, gender, location, link, friends'); //console.log(result.data.birthday); if(result.data.birthday) user.telescope.birthday = result.data.birthday; if(user.services.facebook.gender) user.telescope.gender = user.services.facebook.gender; } if(user.telescope) user.telescope.email = user.services.facebook.email; user.profile = options.profile; } return user; });
Use promises for flatter code
import mongoose from 'mongoose' import bcrypt from 'bcrypt' const User = new mongoose.Schema({ type: { type: String, default: 'User' }, name: { type: String }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, salt: { type: String } }) User.pre('save', function preSave(next) { const user = this if (!user.isModified('password')) { return next() } new Promise((resolve, reject) => { bcrypt.genSalt(10, (err, salt) => { if (err) { return reject(err) } return salt }) }) .then(salt => { bcrypt.hash(user.password, salt, (err, hash) => { if (err) { throw new Error(err) } user.password = hash user.salt = salt return user }) }) .then(() => { next() }) }) User.methods.validatePassword = function validatePassword(password) { const user = this return new Promise((resolve, reject) => { bcrypt.compare(password, user.password, (err, isMatch) => { if (err) { return reject(err) } resolve(isMatch) }) }) } export default mongoose.model('user', User)
import mongoose from 'mongoose' import bcrypt from 'bcrypt' const User = new mongoose.Schema({ type: { type: String, default: 'User' }, name: { type: String }, username: { type: String, required: true, unique: true }, password: { type: String, required: true }, salt: { type: String } }) User.pre('save', function(next) { const user = this if(!user.isModified('password')) { return next() } bcrypt.genSalt(10, (err, salt) => { if(err) { return next(err) } bcrypt.hash(user.password, salt, (err, hash) => { if(err) { return next(err) } user.password = hash user.salt = salt next() }) }) }) User.methods.validatePassword = function(password) { const user = this return new Promise((resolve, reject) => { bcrypt.compare(password, user.password, (err, isMatch) => { if(err) { return reject(err) } resolve(isMatch) }); }) }; export default mongoose.model('user', User)
Fix test error on node v0.10.x
'use strict' var url = require('url'); function ChinachuClient(options) { var urlObj = url.parse(options.url); urlObj.auth = options.user + ':' + options.password; if (urlObj.path[urlObj.path.length - 1] !== '/') { urlObj.path += '/'; } this.baseUrl = url.resolve(url.format(urlObj), urlObj.path + 'api/'); this.userAgent = options.userAgent; // this.scheduler = require('./scheduler')(this); // this.rules = require('./rules')(this); this.program = require('./program')(this); this.schedule = require('./schedule')(this); this.reserves = require('./reserves')(this); this.recording = require('./recording')(this); // this.recorded = require('./recorded')(this); } function remote(options) { return new ChinachuClient(options); } module.exports = { remote: remote };
'use strict' var url = require('url'); function ChinachuClient(options) { var urlObj = url.parse(options.url); urlObj.auth = options.user + ':' + options.password; if (!urlObj.path.endsWith('/')) { urlObj.path += '/'; } this.baseUrl = url.resolve(url.format(urlObj), urlObj.path + 'api/'); this.userAgent = options.userAgent; // this.scheduler = require('./scheduler')(this); // this.rules = require('./rules')(this); this.program = require('./program')(this); this.schedule = require('./schedule')(this); this.reserves = require('./reserves')(this); this.recording = require('./recording')(this); // this.recorded = require('./recorded')(this); } function remote(options) { return new ChinachuClient(options); } module.exports = { remote: remote };
Make sure the connection exists before setting it
<?php namespace adLDAP\Classes; use adLDAP\adLDAP; /** * The base adLDAP class * * Class adLDAPBase * @package adLDAP\classes */ class adLDAPBase { /** * The current adLDAP connection via dependency injection * * @var adLDAP */ protected $adldap; /** * The current adLDAP connection * * @var \adLDAP\Interfaces\ConnectionInterface */ protected $connection; /** * Constructor. * * @param adLDAP $adldap */ public function __construct(adLDAP $adldap) { $this->adldap = $adldap; $connection = $adldap->getLdapConnection(); if($connection) $this->connection = $connection; } }
<?php namespace adLDAP\Classes; use adLDAP\adLDAP; /** * The base adLDAP class * * Class adLDAPBase * @package adLDAP\classes */ class adLDAPBase { /** * The current adLDAP connection via dependency injection * * @var adLDAP */ protected $adldap; /** * The current adLDAP connection * * @var \adLDAP\Interfaces\ConnectionInterface */ protected $connection; /** * Constructor. * * @param adLDAP $adldap */ public function __construct(adLDAP $adldap) { $this->adldap = $adldap; $this->connection = $adldap->getLdapConnection(); } }
Update our temporary route path
<?php namespace Fyuze\Kernel\Application; use Fyuze\Http\Kernel; use Fyuze\Http\Response; use Fyuze\Kernel\Fyuze; use Fyuze\Http\Request; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; class Web extends Fyuze { /** * @return Response */ public function boot($request = null) { $request = (null === $request) ? Request::createFromGlobals() : $request; $this->getContainer()->instance('request', $request); $routes = include $this->path . '/app/routes.php'; $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); $kernel = new Kernel($matcher, $resolver); $kernel = new HttpCache($kernel, new Store($this->path . '/app/cache')); return $kernel->handle($request); } }
<?php namespace Fyuze\Kernel\Application; use Fyuze\Http\Kernel; use Fyuze\Http\Response; use Fyuze\Kernel\Fyuze; use Fyuze\Http\Request; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; class Web extends Fyuze { /** * @return Response */ public function boot($request = null) { $request = (null === $request) ? Request::createFromGlobals() : $request; $this->getContainer()->instance('request', $request); $routes = include $this->path . '/routes.php'; $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); $kernel = new Kernel($matcher, $resolver); $kernel = new HttpCache($kernel, new Store($this->path . '/app/cache')); return $kernel->handle($request); } }
Change var to const for module require statements
const gulp = require('gulp'); const pump = require('pump'); const rename = require('gulp-rename'); const sass = require('gulp-sass'); const webpack = require('webpack-stream'); const uglify = require('gulp-uglify'); var config = { "pug": { "src": "./app/pug/*.pug", "dest": "./" }, "sass": { "src": "./app/sass/*.scss", "dest": "./css/" }, "js": { "src": "./app/js/*.js", "dest": "./js/" } }; gulp.task('pug', () => { return gulp.src(config.pug.src) .pipe(pug()) .pipe(gulp.dest(config.pug.dest)) }); gulp.task('sass', () => { return gulp.src(config.sass.src) .pipe(sass()) .pipe(gulp.dest(config.sass.dest)) }); gulp.task('js', (cb) => { pump([ gulp.src(config.js.src), uglify(), gulp.dest(config.js.dest) ], cb ); }); gulp.task('watch', () => { gulp.watch(config.sass.src, ['sass']); gulp.watch(config.js.src, ['js']); }); gulp.task('default', ['watch']);
var gulp = require('gulp'); var pump = require('pump'); var sass = require('gulp-sass'); var uglify = require('gulp-uglify'); var config = { "pug": { "src": "./app/pug/*.pug", "dest": "./" }, "sass": { "src": "./app/sass/*.scss", "dest": "./css/" }, "js": { "src": "./app/js/*.js", "dest": "./js/" } }; gulp.task('pug', () => { return gulp.src(config.pug.src) .pipe(pug()) .pipe(gulp.dest(config.pug.dest)) }); gulp.task('sass', () => { return gulp.src(config.sass.src) .pipe(sass()) .pipe(gulp.dest(config.sass.dest)) }); gulp.task('js', (cb) => { pump([ gulp.src(config.js.src), uglify(), gulp.dest(config.js.dest) ], cb ); }); gulp.task('watch', () => { gulp.watch(config.sass.src, ['sass']); gulp.watch(config.js.src, ['js']); }); gulp.task('default', ['watch']);
Use random_int() instead of rand()
<?php declare(strict_types=1); /* * This file is part of PHP Copy/Paste Detector (PHPCPD). * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\PHPCPD\Detector\Strategy\SuffixTree; use function random_int; /** * A sentinel character which can be used to produce explicit leaves for all * suffixes. The sentinel just has to be appended to the list before handing * it to the suffix tree. For the sentinel equality and object identity are * the same! */ class Sentinel extends AbstractToken { /** @var int The hash value used. */ private $hash; public function __construct() { $this->hash = random_int(0, PHP_INT_MAX); $this->tokenCode = -1; $this->line = -1; $this->file = '<no file>'; $this->tokenName = '<no token name>'; $this->content = '<no token content>'; } public function __toString(): string { return '$'; } public function hashCode(): int { return $this->hash; } public function equals(AbstractToken $other): bool { // Original code uses physical object equality, not present in PHP. return $other instanceof self; } }
<?php declare(strict_types=1); /* * This file is part of PHP Copy/Paste Detector (PHPCPD). * * (c) Sebastian Bergmann <sebastian@phpunit.de> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace SebastianBergmann\PHPCPD\Detector\Strategy\SuffixTree; /** * A sentinel character which can be used to produce explicit leaves for all * suffixes. The sentinel just has to be appended to the list before handing * it to the suffix tree. For the sentinel equality and object identity are * the same! */ class Sentinel extends AbstractToken { /** @var int The hash value used. */ private $hash; public function __construct() { $this->hash = rand(0, PHP_INT_MAX); $this->tokenCode = -1; $this->line = -1; $this->file = '<no file>'; $this->tokenName = '<no token name>'; $this->content = '<no token content>'; } public function __toString(): string { return '$'; } public function hashCode(): int { return $this->hash; } public function equals(AbstractToken $other): bool { // Original code uses physical object equality, not present in PHP. return $other instanceof self; } }
Reorganize imports to be later
from __future__ import absolute_import, unicode_literals from .signals import connect __version__ = '0.0.1' default_app_config = 'diffs.apps.DiffLogConfig' klasses_to_connect = [] def register(klass): """ Decorator function that registers a class to record diffs. @register class ExampleModel(models.Model): ... """ from django.apps import apps as django_apps from dirtyfields import DirtyFieldsMixin from .models import DiffLogEntryManager # Hack to add dirtyfieldsmixin automatically if DirtyFieldsMixin not in klass.__bases__: klass.__bases__ = (DirtyFieldsMixin,) + klass.__bases__ klass.add_to_class('diffs', DiffLogEntryManager()) if not django_apps.ready: klasses_to_connect.append(klass) else: connect(klass) return klass
from __future__ import absolute_import, unicode_literals from django.apps import apps as django_apps from .signals import connect __version__ = '0.0.1' default_app_config = 'diffs.apps.DiffLogConfig' klasses_to_connect = [] def register(klass): """ Decorator function that registers a class to record diffs. @register class ExampleModel(models.Model): ... """ from .models import DiffLogEntryManager from dirtyfields import DirtyFieldsMixin # Hack to add dirtyfieldsmixin automatically if DirtyFieldsMixin not in klass.__bases__: klass.__bases__ = (DirtyFieldsMixin,) + klass.__bases__ klass.add_to_class('diffs', DiffLogEntryManager()) if not django_apps.ready: klasses_to_connect.append(klass) else: connect(klass) return klass
Apply possibility to input null value on the users table field
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->enum('genre', ['M', 'F'])->after('password'); $table->unsignedInteger('department_id')->nullable()->after('remember_token'); $table->softDeletes()->after('department_id'); $table->foreign('department_id') ->references('id') ->on('departments') ->onDelete('restrict') ->onUpdate('restrict'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } }
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AlterUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('users', function (Blueprint $table) { $table->enum('genre', ['M', 'F'])->after('password'); $table->unsignedInteger('department_id')->after('remember_token'); $table->softDeletes()->after('department_id'); $table->foreign('department_id') ->references('id') ->on('departments') ->onDelete('restrict') ->onUpdate('restrict'); }); } /** * Reverse the migrations. * * @return void */ public function down() { // } }
Use built-in cobra version parameter
package main import ( "log" "github.com/spf13/cobra" "github.com/hellofresh/kandalf/cmd" ) var ( version string configPath string ) func main() { var RootCmd = &cobra.Command{ Use: "kandalf", Version: version, Short: `RabbitMQ to Kafka bridge.`, Long: `RabbitMQ to Kafka bridge. Complete documentation is available at https://github.com/hellofresh/kandalf`, RunE: func(c *cobra.Command, args []string) error { return cmd.RunApp(version, configPath) }, } RootCmd.Flags().StringVarP(&configPath, "config", "c", "", "Source of a configuration file") err := RootCmd.Execute() if err != nil { log.Fatal(err) } }
package main import ( "fmt" "log" "os" "github.com/spf13/cobra" "github.com/hellofresh/kandalf/cmd" ) var ( version string configPath string versionFlag bool ) func main() { versionString := "Kandalf v" + version cobra.OnInitialize(func() { if versionFlag { fmt.Println(versionString) os.Exit(0) } }) var RootCmd = &cobra.Command{ Use: "kandalf", Short: versionString, Long: versionString + `. RabbitMQ to Kafka bridge. Complete documentation is available at https://github.com/hellofresh/kandalf`, RunE: func(c *cobra.Command, args []string) error { return cmd.RunApp(version, configPath) }, } RootCmd.Flags().StringVarP(&configPath, "config", "c", "", "Source of a configuration file") RootCmd.Flags().BoolVarP(&versionFlag, "version", "v", false, "Print application version") err := RootCmd.Execute() if err != nil { log.Fatal(err) } }
Revert "Fix: Add new measure -> headCircumference" This reverts commit 152b8e73235be97cd989e9b39498fc351a71fc8c.
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; ModelingMeasureRange equivalence = null; }
package sizebay.catalog.client.model; import lombok.*; @Getter @Setter @EqualsAndHashCode @ToString public class ModelingSizeMeasures { String sizeName = null; ModelingMeasureRange chest = null; ModelingMeasureRange hip = null; ModelingMeasureRange waist = null; ModelingMeasureRange sleeve = null; ModelingMeasureRange length = null; ModelingMeasureRange insideLeg = null; ModelingMeasureRange biceps = null; ModelingMeasureRange height = null; ModelingMeasureRange fist = null; ModelingMeasureRange neck = null; ModelingMeasureRange thigh = null; ModelingMeasureRange centralSeam = null; ModelingMeasureRange underBust = null; ModelingMeasureRange shoulderWidth = null; ModelingMeasureRange insoleLength = null; ModelingMeasureRange insoleWidth = null; ModelingMeasureRange waistUpper = null; ModelingMeasureRange waistLower = null; ModelingMeasureRange label1 = null; ModelingMeasureRange label2 = null; ModelingMeasureRange label3 = null; ModelingMeasureRange ageChart = null; ModelingMeasureRange weightChart = null; ModelingMeasureRange equivalence = null; ModelingMeasureRange headCircumference = null; }
Fix TypeError if `LANG` is not set in on osx In macosx.uniqueid, `$LANG` is retrieved with `old_lang = environ.get('LANG')`. This means that if `LANG` is not set, `old_lang` will be none. When plyer later tries to restore the original value of lang, `putenv` will complain that we're not supplying a string. I've corrected this by popping the inserted `LANG` value if `old_lang` is none.
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] if old_lang is None: environ.pop('LANG') else: environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
from subprocess import Popen, PIPE from plyer.facades import UniqueID from plyer.utils import whereis_exe from os import environ class OSXUniqueID(UniqueID): def _get_uid(self): old_lang = environ.get('LANG') environ['LANG'] = 'C' ioreg_process = Popen(["ioreg", "-l"], stdout=PIPE) grep_process = Popen(["grep", "IOPlatformSerialNumber"], stdin=ioreg_process.stdout, stdout=PIPE) ioreg_process.stdout.close() output = grep_process.communicate()[0] environ['LANG'] = old_lang if output: return output.split()[3][1:-1] else: return None def instance(): import sys if whereis_exe('ioreg'): return OSXUniqueID() sys.stderr.write("ioreg not found.") return UniqueID()
Remove trailing php close tag
<?php $fields = get_fields($module->ID); $imageSrc = $fields['mod_image_image']['url']; if ($fields['mod_image_crop'] === true) { $imageSrc = wp_get_attachment_image_src( $fields['mod_image_image']['ID'], apply_filters('Modularity/image/image', array($fields['mod_image_crop_width'], $fields['mod_image_crop_height']) ) ); $imageSrc = $imageSrc[0]; } else { $imageSrc = $fields['mod_image_image']['sizes'][$fields['mod_image_size']]; } $classes = array(); if ($fields['mod_image_responsive'] === true) { $classes[] = 'image-responsive'; } echo '<img src="' . $imageSrc . '" alt="' . $fields['mod_image_image']['alt'] . '" class="' . implode(' ', apply_filters('', $classes)) . '">';
<?php $fields = get_fields($module->ID); $imageSrc = $fields['mod_image_image']['url']; if ($fields['mod_image_crop'] === true) { $imageSrc = wp_get_attachment_image_src( $fields['mod_image_image']['ID'], apply_filters('Modularity/image/image', array($fields['mod_image_crop_width'], $fields['mod_image_crop_height']) ) ); $imageSrc = $imageSrc[0]; } else { $imageSrc = $fields['mod_image_image']['sizes'][$fields['mod_image_size']]; } $classes = array(); if ($fields['mod_image_responsive'] === true) { $classes[] = 'image-responsive'; } echo '<img src="' . $imageSrc . '" alt="' . $fields['mod_image_image']['alt'] . '" class="' . implode(' ', apply_filters('', $classes)) . '">'; ?>
Fix missing requirement (overwrote in last batch of commits, due to conflicts).
<?php /* * Created on Aug 19, 2009 * * SVN INFORMATION::: * ------------------- * Last Author::::::::: $Author$ * Current Revision:::: $Revision$ * Repository Location: $HeadURL$ * Last Updated:::::::: $Date$ */ require_once(dirname(__FILE__) .'/../../cs-content/abstract/cs_version.abstract.class.php'); abstract class cs_webapplibsAbstract extends cs_versionAbstract { protected $gfObj; //------------------------------------------------------------------------- function __construct($makeGfObj=true) { $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); $this->get_version(); $this->get_project(); if($makeGfObj === true) { //make a cs_globalFunctions{} object. //TODO::: find a way to avoid h require_once(dirname(__FILE__) ."/../../cs-content/cs_globalFunctions.class.php"); $this->gfObj = new cs_globalFunctions(); } }//end __construct() //------------------------------------------------------------------------- } ?>
<?php /* * Created on Aug 19, 2009 * * SVN INFORMATION::: * ------------------- * Last Author::::::::: $Author$ * Current Revision:::: $Revision$ * Repository Location: $HeadURL$ * Last Updated:::::::: $Date$ */ abstract class cs_webapplibsAbstract extends cs_versionAbstract { protected $gfObj; //------------------------------------------------------------------------- function __construct($makeGfObj=true) { $this->set_version_file_location(dirname(__FILE__) . '/../VERSION'); $this->get_version(); $this->get_project(); if($makeGfObj === true) { //make a cs_globalFunctions{} object. //TODO::: find a way to avoid h require_once(dirname(__FILE__) ."/../../cs-content/cs_globalFunctions.class.php"); $this->gfObj = new cs_globalFunctions(); } }//end __construct() //------------------------------------------------------------------------- } ?>
Revert "Remove "test" prefix from test methods for consistency" This reverts commit 815ef75aa72e0af0998f27663ddb6c38d6afc5ba.
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package com.example.project; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Nested test classes") public class NestedTest { private Calculator calculator = new Calculator(); @Nested @Tag("negative") class TestAddingNegativeNumber { @BeforeEach void setUp(TestInfo testInfo) { System.out.println("Executing: " + testInfo.getDisplayName()); } @Test @DisplayName("Tests adding zero") void testAddingZero() { assertEquals(-2, calculator.add(-2, 0)); } @Test @DisplayName("Tests adding two negative numbers") void testAddingNegative() { assertEquals(-3, calculator.add(-1, -2)); } } }
/* * Copyright 2015-2017 the original author or authors. * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution and is available at * * http://www.eclipse.org/legal/epl-v10.html */ package com.example.project; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import static org.junit.jupiter.api.Assertions.assertEquals; @DisplayName("Nested test classes") public class NestedTest { private Calculator calculator = new Calculator(); @Nested @Tag("negative") class TestAddingNegativeNumber { @BeforeEach void setUp(TestInfo testInfo) { System.out.println("Executing: " + testInfo.getDisplayName()); } @Test @DisplayName("Tests adding zero") void addZero() { assertEquals(-2, calculator.add(-2, 0)); } @Test @DisplayName("Tests adding two negative numbers") void addNegativeNumber() { assertEquals(-3, calculator.add(-1, -2)); } } }
Allow setting args in nextTile
import { nextCoord } from './utils'; export function tile() { return pixelToTile({ x: this.x, y: this.y, }); } export function nextTile(tile, faceDirection) { tile = tile || this.tile; faceDirection = faceDirection || this.faceDirection; return nextCoord(tile, faceDirection, 1); } export function pixelToTile(pixelCoord) { return { x: Math.floor(pixelCoord.x / 32), y: Math.floor(pixelCoord.y / 32), }; } export function tileToPixel(tileCoord) { return { x: (tileCoord.x * 32) + 16, y: (tileCoord.y * 32) + 16, }; } export function alignToGrid(pixelCoord) { if (pixelCoord.x % 16 === 0 && pixelCoord.y % 16 === 0) return pixelCoord; // perhaps not the most efficient way to do this return tileToPixel(pixelToTile(pixelCoord)); }
import { nextCoord } from './utils'; export function tile() { return pixelToTile({ x: this.x, y: this.y, }); } export function nextTile() { return nextCoord(this.tile, this.faceDirection, 1); } export function pixelToTile(pixelCoord) { return { x: Math.floor(pixelCoord.x / 32), y: Math.floor(pixelCoord.y / 32), }; } export function tileToPixel(tileCoord) { return { x: (tileCoord.x * 32) + 16, y: (tileCoord.y * 32) + 16, }; } export function alignToGrid(pixelCoord) { if (pixelCoord.x % 16 === 0 && pixelCoord.y % 16 === 0) return pixelCoord; // perhaps not the most efficient way to do this return tileToPixel(pixelToTile(pixelCoord)); }
Write getName() manually instead of using lombok to please PMD
package net.liquidpineapple.pang; /** * @author Govert de Gans * @date 2016-10-25 */ public final class SoundEffect { public static final SoundEffect COLLECT_COIN = new SoundEffect("coin"); public static final SoundEffect COLLECT_BOMB = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_FREEZE = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_HEART = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_HOOK = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_SHIELD = new SoundEffect("shield"); public static final SoundEffect COLLECT_STICKY = new SoundEffect("genericPowerup"); public static final SoundEffect FOOTSTEP = new SoundEffect("step"); public static final SoundEffect HOOK_SHOOT = new SoundEffect("lazor"); public static final SoundEffect PLAYER_HIT = new SoundEffect("hit"); public static final SoundEffect BALL_DESTROY = new SoundEffect("pop"); private String name; private SoundEffect(String name) { this.name = name; } public String getName() { return this.name; } }
package net.liquidpineapple.pang; import lombok.Getter; /** * @author Govert de Gans * @date 2016-10-25 */ public final class SoundEffect { public static final SoundEffect COLLECT_COIN = new SoundEffect("coin"); public static final SoundEffect COLLECT_BOMB = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_FREEZE = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_HEART = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_HOOK = new SoundEffect("genericPowerup"); public static final SoundEffect COLLECT_SHIELD = new SoundEffect("shield"); public static final SoundEffect COLLECT_STICKY = new SoundEffect("genericPowerup"); public static final SoundEffect FOOTSTEP = new SoundEffect("step"); public static final SoundEffect HOOK_SHOOT = new SoundEffect("lazor"); public static final SoundEffect PLAYER_HIT = new SoundEffect("hit"); public static final SoundEffect BALL_DESTROY = new SoundEffect("pop"); @Getter private String name; private SoundEffect(String name) { this.name = name; } }
Fix bug helpers css path
<?php /** * Yii2 FancyBox Extension * @author Paul P <bigpaulie25ro@yahoo.com> * @license MIT */ namespace bigpaulie\fancybox; use yii\web\AssetBundle; class FancyBoxAsset extends AssetBundle{ public $sourcePath = '@bower/fancybox'; public $css = [ 'source/jquery.fancybox.css', 'source/helpers/jquery.fancybox-buttons.css', 'source/helpers/jquery.fancybox-thumbs.css', ]; public $js = [ 'source/jquery.fancybox.js', 'lib/jquery.mousewheel-3.0.6.pack.js', 'source/helpers/jquery.fancybox-buttons.js', 'source/helpers/jquery.fancybox-thumbs.js', ]; public $depends = [ 'yii\web\JqueryAsset', ]; }
<?php /** * Yii2 FancyBox Extension * @author Paul P <bigpaulie25ro@yahoo.com> * @license MIT */ namespace bigpaulie\fancybox; use yii\web\AssetBundle; class FancyBoxAsset extends AssetBundle{ public $sourcePath = '@bower/fancybox'; public $css = [ 'source/jquery.fancybox.css', 'source/helpers/fancybox-buttons.css', 'source/helpers/fancybox-thumbs.css', ]; public $js = [ 'source/jquery.fancybox.js', 'lib/jquery.mousewheel-3.0.6.pack.js', 'source/helpers/jquery.fancybox-buttons.js', 'source/helpers/jquery.fancybox-thumbs.js', ]; public $depends = [ 'yii\web\JqueryAsset', ]; }
Refactor url_to_class_builder so that the view is only built once
django = __import__("django.conf.urls.defaults", {}) from zuice import Injector def _view_builder(bindings): def view(request, view_class, **kwargs): view_injector = Injector(bindings) view = view_injector.get_from_type(view_class) bindings_for_response = bindings.copy() bindings_for_response.bind('request').to_instance(request) for item in kwargs.iteritems(): bindings_for_response.bind_name(item[0]).to_instance(item[1]) response_injector = Injector(bindings_for_response) response = response_injector.call(view.respond) return response.render(request) return view def url_to_class_builder(bindings): view = _view_builder(bindings.copy()) def url_to_class(regex, view_class, kwargs=None, name=None): if kwargs is None: kwargs = {} kwargs['view_class'] = view_class return django.conf.urls.defaults.url(regex, view, kwargs, name=name) return url_to_class
django = __import__("django.conf.urls.defaults", {}) from zuice import Injector def _view_builder(bindings): def view(request, view_class, **kwargs): view_injector = Injector(bindings) view = view_injector.get_from_type(view_class) bindings_for_response = bindings.copy() bindings_for_response.bind('request').to_instance(request) for item in kwargs.iteritems(): bindings_for_response.bind_name(item[0]).to_instance(item[1]) response_injector = Injector(bindings_for_response) response = response_injector.call(view.respond) return response.render(request) return view def url_to_class_builder(bindings): def url_to_class(regex, view_class, kwargs=None, name=None): if kwargs is None: kwargs = {} kwargs['view_class'] = view_class return django.conf.urls.defaults.url(regex, _view_builder(bindings), kwargs, name=name) return url_to_class
Fix lint rules for non module files
const OFF = 0; const ERROR = 2; module.exports = { root: true, parser: "babel-eslint", plugins: [ "node", "import", "react", "flowtype", "prettier", ], extends: [ "eslint:recommended", "plugin:import/recommended", "plugin:react/recommended", "prettier", "prettier/flowtype" ], rules: { 'prettier/prettier': ERROR, 'no-console': OFF, 'import/no-commonjs': ERROR }, overrides: [ { files: ["*.js", "server/**/*"], env: { node: true } }, { files: [ "react-client/**/*"], env: { browser: true } }, { files: [ "**/__tests__/**", "**.test.js"], env: { jest: true } }, { files: ["webpack.config.js", "ecosystem.config.js"], rules: { "import/unambiguous": OFF, "import/no-commonjs": OFF } }, ] }
const OFF = 0; const ERROR = 2; module.exports = { root: true, parser: "babel-eslint", plugins: [ "node", "import", "react", "flowtype", "prettier", ], extends: [ "eslint:recommended", "plugin:import/recommended", "plugin:react/recommended", "prettier", "prettier/flowtype" ], rules: { 'prettier/prettier': ERROR, 'no-console': OFF, 'import/no-commonjs': ERROR }, overrides: [ { files: ["*.js", "server/**/*"], env: { node: true } }, { files: [ "react-client/**/*"], env: { browser: true } }, { files: [ "**/__tests__/**", "**.test.js"], env: { jest: true } } ] }
Update clear buffer cache plugin to only flush page cache. More detail: http://linux-mm.org/Drop_Caches Change-Id: I7fa675ccdc81f375d88e9cfab330fca3bc983ec8 Reviewed-on: http://gerrit.ent.cloudera.com:8080/1157 Reviewed-by: Alex Behm <fe1626037acfc2dc542d2aa723a6d14f2464a20c@cloudera.com> Reviewed-by: Lenni Kuff <724b7df200764f5dc1b723c05ee6c6adabd11bb1@cloudera.com> Tested-by: Nong Li <99a5e5f8f5911755b88e0b536d46aafa102bed41@cloudera.com>
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): # Drop the page cache (drop_caches=1). We'll leave the inodes and dentries # since that is not what we are testing and it causes excessive performance # variability. cmd = "sysctl -w vm.drop_caches=1 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
#!/usr/bin/env python # Copyright (c) 2012 Cloudera, Inc. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from tests.util.cluster_controller import ClusterController from tests.benchmark.plugins import Plugin class ClearBufferCache(Plugin): """Plugin that clears the buffer cache before a query is run.""" __name__ = "ClearBufferCache" def __init__(self, *args, **kwargs): self.cluster_controller = ClusterController(*args, **kwargs) Plugin.__init__(self, *args, **kwargs) def run_pre_hook(self, context=None): cmd = "sysctl -w vm.drop_caches=3 vm.drop_caches=0" self.cluster_controller.run_cmd(cmd)
Add model method to store contract
<?php namespace Michaeljennings\Carpenter\Contracts; interface Store { /** * Set the model to be used for the table. * * @param mixed $model * @return $this */ public function model($model); /** * Return all of the results. * * @return array */ public function results(); /** * Return a count of all of the results. * * @return int */ public function count(); /** * Return a paginated list of results. * * @param int|string $amount * @param int|string $page * @param int|string $perPage * @return array */ public function paginate($amount, $page, $perPage); /** * Order the results by the given column in the given direction. * * @param string $key * @param string $direction * @return mixed */ public function orderBy($key, $direction = 'asc'); /** * Unset any set order queries. * * @return mixed */ public function refreshOrderBy(); }
<?php namespace Michaeljennings\Carpenter\Contracts; interface Store { /** * Return all of the results. * * @return array */ public function results(); /** * Return a count of all of the results. * * @return int */ public function count(); /** * Return a paginated list of results. * * @param $amount * @param $page * @param $perPage * @return array */ public function paginate($amount, $page, $perPage); /** * Order the results by the given column in the given direction. * * @param string $key * @param string $direction * @return mixed */ public function orderBy($key, $direction = 'asc'); /** * Unset any set order queries. * * @return mixed */ public function refreshOrderBy(); }
Rename generic arguments to silence sonar Change-Id: Ie578bbfb3a82e7c33cdd4c9abd4d8d43d2e0d35e Signed-off-by: Robert Varga <b8bd3df785fdc0ff42dd1710c5d91998513c57ef@cisco.com>
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.concepts; import javax.annotation.concurrent.ThreadSafe; @ThreadSafe public class HandlerRegistry<C, P, S> { private final MultiRegistry<Class<? extends C>, S> serializers = new MultiRegistry<>(); private final MultiRegistry<Integer, P> parsers = new MultiRegistry<>(); public AbstractRegistration registerParser(final int type, final P parser) { return parsers.register(type, parser); } public P getParser(final int type) { return parsers.get(type); } public AbstractRegistration registerSerializer(final Class<? extends C> clazz, final S serializer) { return serializers.register(clazz, serializer); } public S getSerializer(final Class<? extends C> clazz) { return serializers.get(clazz); } }
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.protocol.concepts; import javax.annotation.concurrent.ThreadSafe; @ThreadSafe public class HandlerRegistry<CLASS, PARSER, SERIALIZER> { private final MultiRegistry<Class<? extends CLASS>, SERIALIZER> serializers = new MultiRegistry<>(); private final MultiRegistry<Integer, PARSER> parsers = new MultiRegistry<>(); public AbstractRegistration registerParser(final int type, final PARSER parser) { return parsers.register(type, parser); } public PARSER getParser(final int type) { return parsers.get(type); } public AbstractRegistration registerSerializer(final Class<? extends CLASS> clazz, final SERIALIZER serializer) { return serializers.register(clazz, serializer); } public SERIALIZER getSerializer(final Class<? extends CLASS> clazz) { return serializers.get(clazz); } }
Include metadata tables in package.
#!/usr/bin/env python # coding=utf-8 import os from setuptools import setup, find_packages from eodatasets import __version__ as version # Append TeamCity build number if it gives us one. if 'BUILD_NUMBER' in os.environ and version.endswith('b'): version += '' + os.environ['BUILD_NUMBER'] setup( name="eodatasets", description="Packaging, metadata and provenance for GA EO datasets", version=version, packages=find_packages(exclude=('tests', 'tests.*')), package_data={ '': ['*.json'], }, install_requires=[ 'click', 'python-dateutil', 'gdal', 'numpy', 'pathlib', 'pyyaml', ], entry_points=''' [console_scripts] eod-package=eodatasets.scripts.genpackage:cli eod-generate-metadata=eodatasets.scripts.genmetadata:cli eod-generate-browse=eodatasets.scripts.genbrowse:cli ''', )
#!/usr/bin/env python # coding=utf-8 import os from setuptools import setup, find_packages from eodatasets import __version__ as version # Append TeamCity build number if it gives us one. if 'BUILD_NUMBER' in os.environ and version.endswith('b'): version += '' + os.environ['BUILD_NUMBER'] setup( name="eodatasets", description="Packaging, metadata and provenance for GA EO datasets", version=version, packages=find_packages(exclude=('tests', 'tests.*')), install_requires=[ 'click', 'python-dateutil', 'gdal', 'numpy', 'pathlib', 'pyyaml', ], entry_points=''' [console_scripts] eod-package=eodatasets.scripts.genpackage:cli eod-generate-metadata=eodatasets.scripts.genmetadata:cli eod-generate-browse=eodatasets.scripts.genbrowse:cli ''', )
Order notes on the server (API) side.
require('dotenv').load(); var express = require('express'); var notelyServerApp = express(); var Note = require('./models/note'); var bodyParser = require('body-parser'); // Allow ourselves to use `req.body` to work with form data notelyServerApp.use(bodyParser.json()); // Cross-Origin Resource Sharing (CORS) middleware notelyServerApp.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); next(); }); notelyServerApp.get('/notes', function(req, res) { Note.find().sort({ updated_at: 'desc' }).then(function(notes) { res.json(notes); }); }); notelyServerApp.post('/notes', function(req, res) { var note = new Note({ title: req.body.note.title, body_html: req.body.note.body_html }); note.save().then(function(noteData) { res.json({ message: 'Saved!', note: noteData }); }); }); notelyServerApp.listen(3030, function() { console.log('Listening on http://localhost:3030'); });
require('dotenv').load(); var express = require('express'); var notelyServerApp = express(); var Note = require('./models/note'); var bodyParser = require('body-parser'); // Allow ourselves to use `req.body` to work with form data notelyServerApp.use(bodyParser.json()); // Cross-Origin Resource Sharing (CORS) middleware notelyServerApp.use(function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); next(); }); notelyServerApp.get('/notes', function(req, res) { Note.find().then(function(notes) { res.json(notes); }); }); notelyServerApp.post('/notes', function(req, res) { var note = new Note({ title: req.body.note.title, body_html: req.body.note.body_html }); note.save().then(function(noteData) { res.json({ message: 'Saved!', note: noteData }); }); }); notelyServerApp.listen(3030, function() { console.log('Listening on http://localhost:3030'); });
Use US Locale for date parser
package com.icosillion.podengine.utils; import com.icosillion.podengine.exceptions.DateFormatException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateUtils { private static SimpleDateFormat[] dateFormats = { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z", Locale.US), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z", Locale.US), new SimpleDateFormat("dd MMM yyyy HH:mm Z", Locale.US) }; public static Date stringToDate(String dt) throws DateFormatException { Date date = null; for (SimpleDateFormat dateFormat : DateUtils.dateFormats) { try { date = dateFormat.parse(dt); break; } catch (ParseException e) { //This format didn't work, keep going } } return date; } }
package com.icosillion.podengine.utils; import com.icosillion.podengine.exceptions.DateFormatException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateUtils { private static SimpleDateFormat[] dateFormats = { new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z"), new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z"), new SimpleDateFormat("EEE, dd MMM yyyy HH:mm Z"), new SimpleDateFormat("dd MMM yyyy HH:mm Z") }; public static Date stringToDate(String dt) throws DateFormatException { Date date = null; for (SimpleDateFormat dateFormat : DateUtils.dateFormats) { try { date = dateFormat.parse(dt); break; } catch (ParseException e) { //This format didn't work, keep going } } return date; } }
Fix build failure due to git-rev.json opening nonexistent directory.
'use strict'; const fs = require('fs'); const gitRev = require('git-rev'); const path = require('path'); module.exports = class WebpackEmitGitrev { apply(compiler) { compiler.plugin('after-emit', (compilation, callback) => { gitRev.long(commitHash => { if (commitHash == '') { return callback(new Error('fail')); } const outPath = path.join(compiler.outputPath, 'git-rev.json'); fs.writeFile(outPath, JSON.stringify(commitHash), (ex) => { callback(ex); }); }); }); } };
'use strict'; const fs = require('fs'); const gitRev = require('git-rev'); const path = require('path'); module.exports = class WebpackEmitGitrev { apply(compiler) { compiler.plugin('emit', (compilation, callback) => { gitRev.long(commitHash => { if (commitHash == '') { return callback(new Error('fail')); } const outPath = path.join(compiler.outputPath, 'git-rev.json'); fs.writeFile(outPath, JSON.stringify(commitHash), (ex) => { callback(ex); }); }); }); } };
Fix IndexError while processing tweets
import datetime import json import requests import telebot LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}" bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo") def get_tweet_rating(tweet): """ Function that count tweet rating based on favourites and retweets """ return (tweet['retweet_count'] * 2) + tweet['favourites_count'] @bot.message_handler() def description(message): pass @bot.message_handler(func=lambda m: True) def search(message): result = requests.get(LOKLAK_API_URL.format(query=message.text)) tweets = json.loads(result.text)['statuses'] if tweets: # Find the best tweet for this search query, # by using sorting tweets.sort(key=get_tweet_rating, reverse=True) tweet = '"{message}" - {author} \n\n{link}'.format( message=tweets[0]['text'], author=tweets[0]['screen_name'], link=tweets[0]['link'] ) bot.reply_to(message, tweet) else: bot.reply_to(message, 'Not found') @bot.message_handler() def description(message): pass') bot.polling() # Do not stop main thread while True: pass
import datetime import json import requests import telebot LOKLAK_API_URL = "http://loklak.org/api/search.json?q={query}" bot = telebot.TeleBot("162563966:AAHRx_KauVWfNrS9ADn099kjxqGNB_jqzgo") def get_tweet_rating(tweet): """ Function that count tweet rating based on favourites and retweets """ return (tweet['retweet_count'] * 2) + tweet['favourites_count'] @bot.message_handler(func=lambda m: True) def search(message): result = requests.get(LOKLAK_API_URL.format(query=message.text)) tweets = json.loads(result.text)['statuses'] # Find the best tweet for this search query, # by using sorting tweets.sort(key=get_tweet_rating, reverse=True) tweet = '"{message}" - {author} \n\n{link}'.format( message=tweets[0]['text'], author=tweets[0]['screen_name'], link=tweets[0]['link'] ) bot.reply_to(message, tweet) bot.polling() # Do not stop main thread while True: pass
Sort the list for consistent output
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not field_info.get('read_only') and isinstance(field, ContentTypeField): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_str(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] field_info['choices'].sort(key=lambda item: item['display_name']) return field_info
from rest_framework.metadata import SimpleMetadata from django.utils.encoding import force_str from utilities.api import ContentTypeField class ContentTypeMetadata(SimpleMetadata): def get_field_info(self, field): field_info = super().get_field_info(field) if hasattr(field, 'queryset') and not field_info.get('read_only') and isinstance(field, ContentTypeField): field_info['choices'] = [ { 'value': choice_value, 'display_name': force_str(choice_name, strings_only=True) } for choice_value, choice_name in field.choices.items() ] return field_info
Disable less tests on php 7.4+
<?php namespace Minify\Test; use Minify_HTML_Helper; /** * @requires php < 7.3 */ class LessSourceTest extends TestCase { public function setUp() { $this->realDocRoot = $_SERVER['DOCUMENT_ROOT']; $_SERVER['DOCUMENT_ROOT'] = self::$document_root; } /** * @link https://github.com/mrclay/minify/issues/500 */ public function testLessTimestamp() { $baseDir = self::$test_files; $mainLess = "$baseDir/main.less"; $includedLess = "$baseDir/included.less"; // touch timestamp with 1s difference touch($mainLess); sleep(1); touch($includedLess); $mtime1 = filemtime($mainLess); $mtime2 = filemtime($includedLess); $max = max($mtime1, $mtime2); $options = array( 'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php", ); $res = Minify_HTML_Helper::getUri('less', $options); $this->assertEquals("/min/g=less&amp;{$max}", $res); } }
<?php namespace Minify\Test; use Minify_HTML_Helper; class LessSourceTest extends TestCase { public function setUp() { $this->realDocRoot = $_SERVER['DOCUMENT_ROOT']; $_SERVER['DOCUMENT_ROOT'] = self::$document_root; } /** * @link https://github.com/mrclay/minify/issues/500 */ public function testLessTimestamp() { $baseDir = self::$test_files; $mainLess = "$baseDir/main.less"; $includedLess = "$baseDir/included.less"; // touch timestamp with 1s difference touch($mainLess); sleep(1); touch($includedLess); $mtime1 = filemtime($mainLess); $mtime2 = filemtime($includedLess); $max = max($mtime1, $mtime2); $options = array( 'groupsConfigFile' => "$baseDir/htmlHelper_groupsConfig.php", ); $res = Minify_HTML_Helper::getUri('less', $options); $this->assertEquals("/min/g=less&amp;{$max}", $res); } }
Fix utf-8 problem with åäö and friends.
import os from flask import Flask, render_template from jinja2 import Template app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..') app.config.from_pyfile('settings.py') BASE = '/%s' % app.config['REPO_NAME'] @app.route('/') def home(): with open('talk.md', 'r') as f: template = Template(f.read().decode('utf-8')) markdown = template.render(base=BASE) js_file = 'talk.js' if os.path.isfile(js_file): with open(js_file, 'r') as f_js: js = f_js.read() else: js = '' return render_template('slides.html', markdown=markdown, js=js) if __name__ == '__main__': BASE = '' port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
import os from flask import Flask, render_template from jinja2 import Template app = Flask(__name__, template_folder='.', static_url_path='', static_folder='..') app.config.from_pyfile('settings.py') BASE = '/%s' % app.config['REPO_NAME'] @app.route('/') def home(): with open('talk.md', 'r') as f: template = Template(f.read()) markdown = template.render(base=BASE) js_file = 'talk.js' if os.path.isfile(js_file): with open(js_file, 'r') as f_js: js = f_js.read() else: js = '' return render_template('slides.html', markdown=markdown, js=js) if __name__ == '__main__': BASE = '' port = int(os.environ.get('PORT', 5000)) app.run(host='0.0.0.0', port=port)
Fix the list of local_date objects in the ModeStatTimeSummary
import logging import emission.core.wrapper.wrapperbase as ecwb import emission.core.wrapper.motionactivity as ecwm # Used for various metrics such as count, distance, mean speed calorie consumption, # median speed calorie consumption # Should come later: carbon footprint # Optimal doesn't look like it fits this, because it is not per mode class ModeStatTimeSummary(ecwb.WrapperBase): # We will end up with props like # { # MotionTypes.IN_VEHICLE: ecwb.WrapperBase.Access.WORM # } # Each distance will have # # props = dict([(t.name, ecwb.WrapperBase.Access.WORM) for t in ecwm.MotionTypes]) props.update( {'ts': ecwb.WrapperBase.Access.WORM, # YYYY-MM-DD 'local_dt': ecwb.WrapperBase.Access.WORM, 'fmt_time': ecwb.WrapperBase.Access.WORM} # YYYY-MM-DD ) enums = {} geojson = [] nullable = [] local_dates = ['local_dt'] def _populateDependencies(self): pass
import logging import emission.core.wrapper.wrapperbase as ecwb import emission.core.wrapper.motionactivity as ecwm # Used for various metrics such as count, distance, mean speed calorie consumption, # median speed calorie consumption # Should come later: carbon footprint # Optimal doesn't look like it fits this, because it is not per mode class ModeStatTimeSummary(ecwb.WrapperBase): # We will end up with props like # { # MotionTypes.IN_VEHICLE: ecwb.WrapperBase.Access.WORM # } # Each distance will have # # props = dict([(t.name, ecwb.WrapperBase.Access.WORM) for t in ecwm.MotionTypes]) props.update( {'ts': ecwb.WrapperBase.Access.WORM, # YYYY-MM-DD 'local_dt': ecwb.WrapperBase.Access.WORM, 'fmt_time': ecwb.WrapperBase.Access.WORM} # YYYY-MM-DD ) enums = {} geojson = [] nullable = [] local_dates = ['end_local_dt'] def _populateDependencies(self): pass
Switch TextInput for Textarea for RichText widget base class
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Inboxen is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import Textarea class RichTextInput(Textarea): template_name = 'cms/forms/widgets/rich_text.html'
## # Copyright (C) 2017 Jessica Tallon & Matt Molyneaux # # This file is part of Inboxen. # # Inboxen is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Inboxen is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with Inboxen. If not, see <http://www.gnu.org/licenses/>. ## from django.forms.widgets import TextInput class RichTextInput(TextInput): template_name = 'cms/forms/widgets/rich_text.html'
Define component path in the test RequireJS config.
var allTestFiles = []; var TEST_REGEXP = /(spec|test)\.js$/i; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { allTestFiles.push(pathToModule(file)); } }); require.config({ baseUrl: "/base", paths: { // Libraries "jquery": "libraries/jquery/jquery", // /Libraries // Application "app": "app/scripts/app", "components/example": "app/scripts/components/example", // /Application // Fixtures "app-fixture": "tests/fixtures/app-fixture" // /Fixtures }, shim: { }, deps: allTestFiles, callback: window.__karma__.start });
var allTestFiles = []; var TEST_REGEXP = /(spec|test)\.js$/i; var pathToModule = function(path) { return path.replace(/^\/base\//, '').replace(/\.js$/, ''); }; Object.keys(window.__karma__.files).forEach(function(file) { if (TEST_REGEXP.test(file)) { allTestFiles.push(pathToModule(file)); } }); require.config({ baseUrl: "/base", paths: { // Libraries "jquery": "libraries/jquery/jquery", // /Libraries // Application "app": "app/scripts/app", // /Application // Fixtures "app-fixture": "tests/fixtures/app-fixture" // /Fixtures }, shim: { }, deps: allTestFiles, callback: window.__karma__.start });
Increase timeout to give time for loading transitions to complete TODO: Use JavaScript to try to predict when loading is done...
var page = require('webpage').create(), system = require('system'), fs = require('fs'); var userAgent = "Grabshot" var url = system.args[1]; var format = system.args[2] || "PNG" page.viewportSize = { width: 1280 // height: ... } function render() { result = { title: page.evaluate(function() { return document.title }), imageData: page.renderBase64(format), format: format } console.log(JSON.stringify(result)) phantom.exit(); } page.onError = phantom.onError = function() { console.log("PhantomJS error :("); phantom.exit(1); }; page.onLoadFinished = function (status) { if (status !== 'success') { phantom.exit(1); } setTimeout(render, 300); } page.open(url);
var page = require('webpage').create(), system = require('system'), fs = require('fs'); var userAgent = "Grabshot" var url = system.args[1]; var format = system.args[2] || "PNG" page.viewportSize = { width: 1280 // height: ... } function render() { result = { title: page.evaluate(function() { return document.title }), imageData: page.renderBase64(format), format: format } console.log(JSON.stringify(result)) phantom.exit(); } page.onError = phantom.onError = function() { console.log("PhantomJS error :("); phantom.exit(1); }; page.onLoadFinished = function (status) { if (status !== 'success') { phantom.exit(1); } setTimeout(render, 50); } page.open(url);
Make Connect4's __str__ more readable
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n|' or '|' for piece_column in self.pieces: try: output += piece_column[5 - i] and 'X|' or 'O|' except IndexError: output += ' |' output += '\n 0 1 2 3 4 5 6 ' return output def start(): pass
class Connect4(object): def __init__(self): self.pieces = [[] for i in xrange(7)] self.turn = 0 def move(self, column): for i in xrange(column, column + 7): if len(self.pieces[i % 7]) < 6: self.pieces[i % 7].append(self.turn) self.turn = 1 - self.turn return def __str__(self): output = '' for i in xrange(6): output += i and '\n ' or ' ' for piece_column in self.pieces: try: output += str(piece_column[5 - i]) + ' ' except IndexError: output += ' ' return output def start(): pass
Fix scroll being at an awkward position when switching back from print-friendly
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { try { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; } catch (e) { return `<blockquote class="katex-block">${e.message}</blockquote>`; } }; renderer.codespan = function(code) { try { return katex.renderToString(code, katexOpts); } catch (e) { return e.message; } }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.getSession().setUseWrapMode(true); editor.getSession().setMode("ace/mode/markdown"); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); document.body.classList.toggle('printable'); window.scrollTo(0, 0); event.preventDefault(); return false; } };
const renderer = new marked.Renderer(); const katexOpts = { throwOnError: false, errorColor: '#F44336', }; renderer.code = function(code) { try { const r = katex.renderToString(code, { displayMode: true, ...katexOpts, }); return `<blockquote class="katex-block">${r}</blockquote>`; } catch (e) { return `<blockquote class="katex-block">${e.message}</blockquote>`; } }; renderer.codespan = function(code) { try { return katex.renderToString(code, katexOpts); } catch (e) { return e.message; } }; const wrapper = document.getElementById('page-wrapper'); const preview = document.getElementById('preview'); const editor = ace.edit('editor'); editor.getSession().setUseSoftTabs(true); editor.getSession().setTabSize(2); editor.getSession().setUseWrapMode(true); editor.getSession().setMode("ace/mode/markdown"); function updateOutput() { const result = marked(editor.getValue(), { renderer: renderer, smartypants: true, }); preview.innerHTML = result; } editor.getSession().on('change', updateOutput); document.onkeydown = function(event) { if (event.keyCode === 77 && event.ctrlKey) { wrapper.classList.toggle('printable'); document.body.classList.toggle('printable'); event.preventDefault(); return false; } };
Caramel: Move pyramid_tm include to caramel.main Move the setting to include pyramid_tm to caramel.main from ini files. This is a vital setting that should never be changed by the user.
#! /usr/bin/env python # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = Configurator(settings=settings) config.include("pyramid_tm") config.add_route("ca", "/root.crt", request_method="GET") config.add_route("cabundle", "/bundle.crt", request_method="GET") config.add_route("csr", "/{sha256:[0-9a-f]{64}}", request_method="POST") config.add_route("cert", "/{sha256:[0-9a-f]{64}}", request_method="GET") config.scan() return config.make_wsgi_app()
#! /usr/bin/env python # vim: expandtab shiftwidth=4 softtabstop=4 tabstop=17 filetype=python : from pyramid.config import Configurator from sqlalchemy import engine_from_config from .models import ( init_session, ) def main(global_config, **settings): """This function returns a Pyramid WSGI application.""" engine = engine_from_config(settings, "sqlalchemy.") init_session(engine) config = Configurator(settings=settings) config.add_route("ca", "/root.crt", request_method="GET") config.add_route("cabundle", "/bundle.crt", request_method="GET") config.add_route("csr", "/{sha256:[0-9a-f]{64}}", request_method="POST") config.add_route("cert", "/{sha256:[0-9a-f]{64}}", request_method="GET") config.scan() return config.make_wsgi_app()
Tag 0.1.5, tweaks for PyPI compatibility
#from distribute_setup import use_setuptools #use_setuptools() from setuptools import setup, find_packages from os.path import dirname, join import os os.environ['SECP_BUNDLED_EXPERIMENTAL'] = "1" here = dirname(__file__) setup( name='ledgerblue', version='0.1.5', author='Ledger', author_email='hello@ledger.fr', description='Python library to communicate with Ledger Blue/Nano S', long_description=open(join(here, 'README.md')).read(), url='https://github.com/LedgerHQ/blue-loader-python', packages=find_packages(), install_requires=['hidapi>=0.7.99', 'secp256k1>=0.12.1', 'pycrypto>=2.6.1'], extras_require = { 'smartcard': [ 'python-pyscard>=1.6.12-4build1' ] }, include_package_data=True, zip_safe=False, classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: Microsoft :: Windows', 'Operating System :: MacOS :: MacOS X' ] )
#from distribute_setup import use_setuptools #use_setuptools() from setuptools import setup, find_packages from os.path import dirname, join here = dirname(__file__) setup( name='ledgerblue', version='0.1.4', author='Ledger', author_email='hello@ledger.fr', description='Python library to communicate with Ledger Blue/Nano S', long_description=open(join(here, 'README.md')).read(), packages=find_packages(), install_requires=['hidapi>=0.7.99', 'secp256k1>=0.12.1', 'pycrypto>=2.6.1'], extras_require = { 'smartcard': [ 'python-pyscard>=1.6.12-4build1' ] }, include_package_data=True, zip_safe=False, classifiers=[ 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: POSIX :: Windows', 'Operating System :: MacOS :: MacOS X' ] )
Add self.isLoggedIn and modify login function
app.controller('LoginController', ['$scope', '$mdDialog', '$firebaseAuth', 'AuthFactory', function($scope, $mdDialog, $firebaseAuth, AuthFactory){ console.log('login controller is running'); var auth = $firebaseAuth(); var self = this; self.isLoggedIn = AuthFactory.userStatus.isLoggedIn; console.log(self.isLoggedIn); self.logIn = function() { console.log('logging user in'); AuthFactory.logIn().then(function(response){ console.log('Logged In: ', AuthFactory.userStatus.isLoggedIn); }); // auth.$signInWithPopup("google").then(function(firebaseUser) { // console.log("Firebase Authenticated as: ", firebaseUser.user); // }).catch(function(error) { // console.log("Authentication failed: ", error); // }); }; self.logOut = function() { console.log('logging user out'); AuthFactory.logOut(); }; self.hide = function() { $mdDialog.hide(); }; self.cancel = function() { $mdDialog.cancel(); }; self.answer = function(answer) { logIn(); // $mdDialog.hide(answer); // console.log('from dialog controller', answer); }; }]);
app.controller('LoginController', ['$scope', '$mdDialog', '$firebaseAuth', 'AuthFactory', function($scope, $mdDialog, $firebaseAuth, AuthFactory){ console.log('login controller is running'); var auth = $firebaseAuth(); var self = this; self.logIn = function() { console.log('logging user in'); AuthFactory.logIn(); // auth.$signInWithPopup("google").then(function(firebaseUser) { // console.log("Firebase Authenticated as: ", firebaseUser.user); // }).catch(function(error) { // console.log("Authentication failed: ", error); // }); }; self.logOut = function() { console.log('logging user out'); AuthFactory.logOut(); }; self.hide = function() { $mdDialog.hide(); }; self.cancel = function() { $mdDialog.cancel(); }; self.answer = function(answer) { logIn(); // $mdDialog.hide(answer); // console.log('from dialog controller', answer); }; }]);
Add HttpCache to web application
<?php namespace Fyuze\Kernel\Application; use Fyuze\Http\Kernel; use Fyuze\Http\Request; use Fyuze\Http\Response; use Fyuze\Kernel\Fyuze; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\HttpKernel\HttpCache\HttpCache; use Symfony\Component\HttpKernel\HttpCache\Store; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; class Web extends Fyuze { /** * @return Response */ public function boot($request = null) { $request = $this->getRegistry()->make('Fyuze\Http\Request'); $routes = include $this->path . '/routes.php'; $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); $kernel = new Kernel($matcher, $resolver); $kernel = new HttpCache($kernel, new Store($this->path.'/app/cache')); return $kernel->handle($request); } }
<?php namespace Fyuze\Kernel\Application; use Fyuze\Http\Kernel; use Fyuze\Http\Request; use Fyuze\Http\Response; use Fyuze\Kernel\Fyuze; use Symfony\Component\HttpKernel\Controller\ControllerResolver; use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\RequestContext; class Web extends Fyuze { /** * @return Response */ public function boot($request = null) { $request = $this->getRegistry()->make('Fyuze\Http\Request'); $routes = include $this->path . '/routes.php'; $context = new RequestContext(); $matcher = new UrlMatcher($routes, $context); $resolver = new ControllerResolver(); $kernel = new Kernel($matcher, $resolver); return $kernel->handle($request); } }
JasonLeyba: Make a test case insensitive. r11860
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class TagNameTest extends AbstractDriverTestCase { @Test public void shouldReturnInput() { driver.get(pages.formPage); WebElement selectBox = driver.findElement(By.id("cheese")); assertThat(selectBox.getTagName().toLowerCase(), is("input")); } }
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class TagNameTest extends AbstractDriverTestCase { @Test public void shouldReturnInput() { driver.get(pages.formPage); WebElement selectBox = driver.findElement(By.id("cheese")); assertThat(selectBox.getTagName(), is("input")); } }
Add import:images call to ImportAll
<?php namespace App\Console\Commands; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class ImportAllCommand extends BaseCommand { protected $signature = 'import:all'; protected $description = 'Run all import commands'; public function handle() { $this->call('db:reset'); // Add --yes flag? $this->call('migrate'); $this->call('import:collections-full'); $this->call('import:exhibitions-legacy'); $this->call('import:events-ticketed-full', ['--yes' => 'default']); $this->call('import:events-legacy'); $this->call('import:dsc', ['--yes' => 'default', '-v' => 'default']); $this->call('import:mobile'); $this->call('import:library', ['--yes' => 'default']); $this->call('import:archive', ['--yes' => 'default']); $this->call('import:sites', ['--yes' => 'default']); $this->call('import:set-ulan-uris'); // TODO: Are we ready to remove this? // $this->call('import:terms-legacy'); $this->call('import:products-full', ['--yes' => 'default']); $this->call('import:images'); } }
<?php namespace App\Console\Commands; use Aic\Hub\Foundation\AbstractCommand as BaseCommand; class ImportAllCommand extends BaseCommand { protected $signature = 'import:all'; protected $description = 'Run all import commands'; public function handle() { $this->call('db:reset'); // Add --yes flag? $this->call('migrate'); $this->call('import:collections-full'); $this->call('import:exhibitions-legacy'); $this->call('import:events-ticketed-full', ['--yes' => 'default']); $this->call('import:events-legacy'); $this->call('import:dsc', ['--yes' => 'default', '-v' => 'default']); $this->call('import:mobile'); $this->call('import:library', ['--yes' => 'default']); $this->call('import:archive', ['--yes' => 'default']); $this->call('import:sites', ['--yes' => 'default']); $this->call('import:set-ulan-uris'); // TODO: Are we ready to remove this? // $this->call('import:terms-legacy'); $this->call('import:products-full', ['--yes' => 'default']); } }
Fix error when trying to start without user/pass This fixes #25
import logging import traceback import click # Ignore error, logging set up in logging utils from spoppy import logging_utils from spoppy.navigation import Leifur logger = logging.getLogger(__name__) @click.command() @click.argument('username', envvar='SPOPPY_USERNAME') @click.argument('password', envvar='SPOPPY_PASSWORD') @click.option('--debug', default=False) def main(username, password, debug): navigator = Leifur(username, password) if debug: try: navigator.start() except Exception: traceback.print_exc() logger.error(traceback.format_exc()) finally: navigator.shutdown() logger.debug('Finally, bye!') else: try: navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') if __name__ == '__main__': try: main(standalone_mode=False) except click.exceptions.MissingParameter: click.echo( 'You must either set the SPOPPY_USERNAME and SPOPPY_PASSWORD ' 'environment variables or add username and password to your ' 'the script\'s parameters!' )
import logging import traceback import click # Ignore error, logging set up in logging utils from spoppy import logging_utils from spoppy.navigation import Leifur logger = logging.getLogger(__name__) @click.command() @click.argument('username', envvar='SPOPPY_USERNAME') @click.argument('password', envvar='SPOPPY_PASSWORD') @click.option('--debug', default=False) def main(username, password, debug): navigator = Leifur(username, password) if debug: try: navigator.start() except Exception: traceback.print_exc() logger.error(traceback.format_exc()) finally: navigator.shutdown() logger.debug('Finally, bye!') else: try: navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') if __name__ == '__main__': main(auto_envvar_prefix='SPOPPY', standalone_mode=False)
Fix enum literal value parsing
import { getDescription } from 'graphql/utilities/buildASTSchema'; import { getNamedType } from 'graphql/type'; import produceType from './produceType'; export const buildFieldConfigArgumentMap = (fieldAST, types) => fieldAST.arguments.reduce((map, inputValueAST) => { const type = produceType(inputValueAST.type, types); const defaultValue = inputValueAST.defaultValue; const description = getDescription(inputValueAST); const argumentConfig = { type }; if (defaultValue !== null) { argumentConfig.defaultValue = getNamedType(type).parseLiteral(defaultValue); } if (description) argumentConfig.description = description; return { ...map, [inputValueAST.name.value]: argumentConfig }; }, {}); export default function buildFieldConfigMap(objectAST, configMap = {}, types) { return objectAST.fields.reduce((map, fieldAST) => { const name = fieldAST.name.value; const config = configMap[name] || {}; const type = produceType(fieldAST.type, types); const args = buildFieldConfigArgumentMap(fieldAST, types); const description = getDescription(fieldAST); const fieldConfig = { type }; if (Object.keys(args).length) fieldConfig.args = args; if ('resolve' in config) fieldConfig.resolve = config.resolve; if ('deprecationReason' in config) fieldConfig.deprecationReason = config.deprecationReason; if (description) fieldConfig.description = description; return { ...map, [name]: fieldConfig }; }, {}); }
import { getDescription } from 'graphql/utilities/buildASTSchema'; import produceType from './produceType'; export const buildFieldConfigArgumentMap = (fieldAST, types) => fieldAST.arguments.reduce((map, inputValueAST) => { const type = produceType(inputValueAST.type, types); const defaultValue = inputValueAST.defaultValue; const description = getDescription(inputValueAST); const argumentConfig = { type }; if (defaultValue !== null) argumentConfig.defaultValue = type.parseLiteral(defaultValue); if (description) argumentConfig.description = description; return { ...map, [inputValueAST.name.value]: argumentConfig }; }, {}); export default function buildFieldConfigMap(objectAST, configMap = {}, types) { return objectAST.fields.reduce((map, fieldAST) => { const name = fieldAST.name.value; const config = configMap[name] || {}; const type = produceType(fieldAST.type, types); const args = buildFieldConfigArgumentMap(fieldAST, types); const description = getDescription(fieldAST); const fieldConfig = { type }; if (Object.keys(args).length) fieldConfig.args = args; if ('resolve' in config) fieldConfig.resolve = config.resolve; if ('deprecationReason' in config) fieldConfig.deprecationReason = config.deprecationReason; if (description) fieldConfig.description = description; return { ...map, [name]: fieldConfig }; }, {}); }
Add code to replace not only `data-src`, but also `data-bgset` lazysizes width and quality values with calculated ones.
/** * Lazysizes * * Lazy loader class for (responsive) images * https://github.com/aFarkas/lazysizes */ var lazysizes = { /** * Init lazysizes */ init: function() { document.addEventListener('lazyriasmodifyoptions', function(e) { // If pixel ratio > 1.4 set (resrc) jpg quality to a lower percentage e.detail.quality = (window.devicePixelRatio || 1) > 1.4 ? 65 : 60; }); document.addEventListener('lazybeforeunveil', function(e){ // Replace default `data-src/bgset` placeholder width and quality // values, with the by lazyizes calculated {width} and {quality} values var srcAttr = 'data-src'; var src = e.target.getAttribute(srcAttr); if(!src) { srcAttr = 'data-bgset'; src = e.target.getAttribute(srcAttr); if(!src) { return; } } e.target.setAttribute(srcAttr, src.replace(/s=w(\d+)/, 's=w{width}').replace(/o=(\d+)/, 'o={quality}')); // // Basic support for background images (for without bgset plugin) // var bg = e.target.getAttribute('data-bg'); // if(bg) { // e.target.style.backgroundImage = 'url(' + bg + ')'; // e.target.removeAttribute('data-bg'); // } }); }, };
/** * Lazysizes * * Lazy loader class for (responsive) images * https://github.com/aFarkas/lazysizes */ var lazysizes = { /** * Init lazysizes */ init: function() { document.addEventListener('lazyriasmodifyoptions', function(e) { // If pixel ratio > 1.4 set (resrc) jpg quality to a lower percentage e.detail.quality = (window.devicePixelRatio || 1) > 1.4 ? 65 : 60; }); document.addEventListener('lazybeforeunveil', function(e){ // Replace default `data-src` placeholder {width} and {quality} with calculated values var src = e.target.getAttribute('data-src'); if(!src) { return; } e.target.setAttribute('data-src', src.replace(/s=w(\d+)/, 's=w{width}').replace(/o=(\d+)/, 'o={quality}')); // // Basic support for background images (for without bgset plugin) // var bg = e.target.getAttribute('data-bg'); // if(bg) { // e.target.style.backgroundImage = 'url(' + bg + ')'; // e.target.removeAttribute('data-bg'); // } }); }, };
Return an AsyncProcessor in wrapProcessorInInterceptors to make the Default channel happy git-svn-id: 72f01205ed0e830b17124003a563eb3e26365279@243 2ef4527c-bcc6-11de-8784-f7ad4773dbab
/** * */ package camelinaction; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.processor.DelegateAsyncProcessor; import org.apache.camel.spi.InterceptStrategy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author janstey * */ public class MyInterceptor implements InterceptStrategy { private static final transient Log log = LogFactory .getLog(MyInterceptor.class); /* * (non-Javadoc) * * @see * org.apache.camel.spi.InterceptStrategy#wrapProcessorInInterceptors(org * .apache.camel.CamelContext, org.apache.camel.model.ProcessorDefinition, * org.apache.camel.Processor, org.apache.camel.Processor) */ public Processor wrapProcessorInInterceptors(CamelContext context, ProcessorDefinition<?> definition, final Processor target, Processor nextTarget) throws Exception { // to make the Default channel happy return new DelegateAsyncProcessor(new Processor() { public void process(Exchange exchange) throws Exception { log.info("Before the processor..."); target.process(exchange); log.info("After the processor..."); } }); } }
/** * */ package camelinaction; import org.apache.camel.CamelContext; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.spi.InterceptStrategy; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author janstey * */ public class MyInterceptor implements InterceptStrategy { private static final transient Log log = LogFactory .getLog(MyInterceptor.class); /* * (non-Javadoc) * * @see * org.apache.camel.spi.InterceptStrategy#wrapProcessorInInterceptors(org * .apache.camel.CamelContext, org.apache.camel.model.ProcessorDefinition, * org.apache.camel.Processor, org.apache.camel.Processor) */ public Processor wrapProcessorInInterceptors(CamelContext context, ProcessorDefinition<?> definition, final Processor target, Processor nextTarget) throws Exception { return new Processor() { public void process(Exchange exchange) throws Exception { log.info("Before the processor..."); target.process(exchange); log.info("After the processor..."); } }; } }
Fix format constant for PHP 7.1
<?php namespace Limoncello\Flute\Types; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use DateTimeImmutable; use JsonSerializable; /** * Wrapper class for `DateTimeInterface` value with JSON serialization support. * * @package Limoncello\Flute */ class DateTime extends DateTimeImmutable implements JsonSerializable { /** DateTime format */ const JSON_API_FORMAT = \DateTime::ISO8601; /** * @inheritdoc */ public function jsonSerialize() { return $this->format(static::JSON_API_FORMAT); } }
<?php namespace Limoncello\Flute\Types; /** * Copyright 2015-2017 info@neomerx.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ use DateTimeImmutable; use JsonSerializable; /** * Wrapper class for `DateTimeInterface` value with JSON serialization support. * * @package Limoncello\Flute */ class DateTime extends DateTimeImmutable implements JsonSerializable { /** DateTime format */ const JSON_API_FORMAT = self::ISO8601; /** * @inheritdoc */ public function jsonSerialize() { return $this->format(static::JSON_API_FORMAT); } }
Add closing ) that got removed by acident2
import test from 'ava'; import TweetCardContent from '../lib/tweet-card-content'; const META_SECTION = "Tweet should be about"; test("Test static exports", (t) => { t.true("TWEET_CONTENT" in TweetCardContent); t.true("RETWEET" in TweetCardContent); t.true("SCHEDULED" in TweetCardContent); }); test("Create card", (t) => { const meta = "test"; const card = TweetCardContent.createCard(meta); t.true(card instanceof TweetCardContent); t.is(meta, card.getSection(META_SECTION)); t.false(card.isRetweet); t.true(card.hasSection(TweetCardContent.TWEET_CONTENT)); t.false(card.isValid); }); test("Retweet", (t) => { const meta = "test"; const card = TweetCardContent.createCard(meta, true); t.true(card instanceof TweetCardContent); t.is(meta, card.getSection(META_SECTION)); t.true(card.isRetweet); t.true(card.hasSection(TweetCardContent.RETWEET)); t.false(card.isValid); }); test.todo("Test setSection"); test.todo("Test tweet length"); test.todo("Test with valid RT url"); test.todo("Test due date/SCHEDULED"); test.todo("Test error messages");
import test from 'ava'; import TweetCardContent from '../lib/tweet-card-content'; const META_SECTION = "Tweet should be about"; test("Test static exports", (t) => { t.true("TWEET_CONTENT" in TweetCardContent); t.true("RETWEET" in TweetCardContent); t.true("SCHEDULED" in TweetCardContent); }); test("Create card", (t) => { const meta = "test"; const card = TweetCardContent.createCard(meta); t.true(card instanceof TweetCardContent); t.is(meta, card.getSection(META_SECTION)); t.false(card.isRetweet); t.true(card.hasSection(TweetCardContent.TWEET_CONTENT)); t.false(card.isValid); }); test("Retweet", (t) => { const meta = "test"; const card = TweetCardContent.createCard(meta, true); t.true(card instanceof TweetCardContent); t.is(meta, card.getSection(META_SECTION)); t.true(card.isRetweet); t.true(card.hasSection(TweetCardContent.RETWEET)); t.false(card.isValid; }); test.todo("Test setSection"); test.todo("Test tweet length"); test.todo("Test with valid RT url"); test.todo("Test due date/SCHEDULED"); test.todo("Test error messages");
Use underscore for private properties
/** * A lightweight promise-based Reddit API wrapper. * @module reddit-api */ exports = module.exports = Reddit; function Reddit() { this._baseApiUrl = 'http://www.reddit.com'; return this; }; /** * Logs in a Reddit user. * * @param {string} username * @param {string} password */ Reddit.prototype.login = function(username, password) { }; /** * Logs out a Reddit user. */ Reddit.prototype.logout = function() { }; /** * Retrieves the comments associated with a URL. * * @param {string} url */ Reddit.prototype.getComments = function(url) { }; /** * Posts a comment on a Reddit "thing". * * @param {string} parentId - The * {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent * "thing". * @param {string} text - The comment body. * @link http://www.reddit.com/dev/api#POST_api_comment */ Reddit.prototype.comment = function(parentId, text) { };
/** * A lightweight promise-based Reddit API wrapper. * @module reddit-api */ exports = module.exports = Reddit; function Reddit() { this.baseApiUrl = 'http://www.reddit.com'; return this; }; /** * Logs in a Reddit user. * * @param {string} username * @param {string} password */ Reddit.prototype.login = function(username, password) { }; /** * Logs out a Reddit user. */ Reddit.prototype.logout = function() { }; /** * Retrieves the comments associated with a URL. * * @param {string} url */ Reddit.prototype.getComments = function(url) { }; /** * Posts a comment on a Reddit "thing". * * @param {string} parentId - The * {@link http://www.reddit.com/dev/api#fullnames fullname} of a parent * "thing". * @param {string} text - The comment body. * @link http://www.reddit.com/dev/api#POST_api_comment */ Reddit.prototype.comment = function(parentId, text) { };
Use github api as example, because openweathermap now requires an access token.
var promisedHandlebars = require('../') var Handlebars = promisedHandlebars(require('handlebars')) var httpGet = require('get-promise') // A block helper (retrieve weather for a city from openweathermap.org) // Execute the helper-block with the weather result Handlebars.registerHelper('github-user', function (value, options) { var url = 'https://api.github.com/users/' + value return httpGet(url, { headers: { 'User-Agent': 'Node' } }) .get('data') .then(JSON.parse) .then(function (data) { // `options.fn` returns a promise. Wrapping brackets must be added after resolving return options.fn(data) }) }) var template = Handlebars.compile('{{username}}: {{#github-user username}}{{{name}}}{{/github-user}}') // The whole compiled function returns a promise as well template({ username: 'nknapp' }).done(console.log)
var promisedHandlebars = require('../') var Handlebars = promisedHandlebars(require('handlebars')) var httpGet = require('get-promise') // A block helper (retrieve weather for a city from openweathermap.org) // Execute the helper-block with the weather result Handlebars.registerHelper('weather', function (value, options) { var url = 'http://api.openweathermap.org/data/2.5/weather?q=' + value + '&units=metric' return httpGet(url) .get('data') .then(JSON.parse) .then(function (weather) { // `options.fn` returns a promise. Wrapping brackets must be added after resolving return options.fn(weather) }) }) var template = Handlebars.compile('{{city}}: {{#weather city}}{{{main.temp}}}°C{{/weather}}') // The whole compiled function returns a promise as well template({ city: 'Darmstadt' }).done(console.log)
Replace cubehelix with the viridis colormap in the RAG drawing example
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with viridis colormap") cmap = plt.get_cmap('viridis') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
""" ====================================== Drawing Region Adjacency Graphs (RAGs) ====================================== This example constructs a Region Adjacency Graph (RAG) and draws it with the `rag_draw` method. """ from skimage import data, segmentation from skimage.future import graph from matplotlib import pyplot as plt, colors img = data.coffee() labels = segmentation.slic(img, compactness=30, n_segments=400) g = graph.rag_mean_color(img, labels) out = graph.draw_rag(labels, g, img) plt.figure() plt.title("RAG with all edges shown in green.") plt.imshow(out) # The color palette used was taken from # http://www.colorcombos.com/color-schemes/2/ColorCombo2.html cmap = colors.ListedColormap(['#6599FF', '#ff9900']) out = graph.draw_rag(labels, g, img, node_color="#ffde00", colormap=cmap, thresh=30, desaturate=True) plt.figure() plt.title("RAG with edge weights less than 30, color " "mapped between blue and orange.") plt.imshow(out) plt.figure() plt.title("All edges drawn with cubehelix colormap") cmap = plt.get_cmap('cubehelix') out = graph.draw_rag(labels, g, img, colormap=cmap, desaturate=True) plt.imshow(out) plt.show()
Change type of time_posted to DATETIME and add author column
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.DateTime) author = sqlalchemy.Column(sqlalchemy.String) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
import sqlalchemy import sqlalchemy.ext.declarative Base = sqlalchemy.ext.declarative.declarative_base() class Post(Base): __tablename__ = "posts" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) title = sqlalchemy.Column(sqlalchemy.String) body = sqlalchemy.Column(sqlalchemy.Text,) #Should be text to avoid length problems time_posted = sqlalchemy.Column(sqlalchemy.Time) class Tag(Base): __tablename__ = "tags" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) name = sqlalchemy.Column(sqlalchemy.Text) #Used to relate tags to posts. class TagRelation(Base): __tablename__ = "tag_relation" id = sqlalchemy.Column(sqlalchemy.Integer, primary_key = True) post_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Post.__table__.columns.id)) tag_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey(Tag.__table__.columns.id)) #The Following tables will only be the ones added to the database ALL_TABLES = [Post, Tag, TagRelation]
pkg/eval/exc: Add missing unit tests for exc:is-pipeline-exc.
package exc import ( "testing" "github.com/elves/elvish/pkg/eval" ) var That = eval.That func TestExc(t *testing.T) { setup := func(ev *eval.Evaler) { ev.Global.AddNs("exc", Ns) } eval.TestWithSetup(t, setup, // Have a simple sanity test that exc:show writes something. That(`exc:show ?(fail foo) | > (count (slurp)) 0`).Puts(true), That("exc:is-external-cmd-exc ?("+failingExternalCmd+")").Puts(true), That("exc:is-external-cmd-exc ?(fail bad)").Puts(false), That("exc:is-nonzero-exit ?("+failingExternalCmd+")").Puts(true), That("exc:is-nonzero-exit ?(fail bad)").Puts(false), // TODO: Test positive case of exc:is-killed That("exc:is-killed ?(fail bad)").Puts(false), That("exc:is-fail-exc ?(fail bad)").Puts(true), That("exc:is-fail-exc ?("+failingExternalCmd+")").Puts(false), That("exc:is-pipeline-exc ?(fail bad)").Puts(false), That("exc:is-pipeline-exc ?(fail 1 | fail 2)").Puts(true), ) }
package exc import ( "testing" "github.com/elves/elvish/pkg/eval" ) var That = eval.That func TestExc(t *testing.T) { setup := func(ev *eval.Evaler) { ev.Global.AddNs("exc", Ns) } eval.TestWithSetup(t, setup, // Have a simple sanity test that exc:show writes something. That(`exc:show ?(fail foo) | > (count (slurp)) 0`).Puts(true), That("exc:is-external-cmd-exc ?("+failingExternalCmd+")").Puts(true), That("exc:is-external-cmd-exc ?(fail bad)").Puts(false), That("exc:is-nonzero-exit ?("+failingExternalCmd+")").Puts(true), That("exc:is-nonzero-exit ?(fail bad)").Puts(false), // TODO: Test positive case of exc:is-killed That("exc:is-killed ?(fail bad)").Puts(false), That("exc:is-fail-exc ?(fail bad)").Puts(true), That("exc:is-fail-exc ?("+failingExternalCmd+")").Puts(false), ) }
[AC-9452] Fix image field import and migration
# Generated by Django 2.2.28 on 2022-04-20 13:05 import sorl.thumbnail.fields from django.db import ( migrations, models, ) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0098_update_startup_update_20220408_0441'), ] operations = [ migrations.AddField( model_name='program', name='hubspot_url', field=models.URLField(blank=True, null=True), ), migrations.AddField( model_name='program', name='program_image', field=sorl.thumbnail.fields.ImageField( null=True, upload_to='program_images'), ), ]
# Generated by Django 2.2.28 on 2022-04-20 13:05 from django.db import ( migrations, models, ) class Migration(migrations.Migration): dependencies = [ ('accelerator', '0098_update_startup_update_20220408_0441'), ] operations = [ migrations.AddField( model_name='program', name='hubspot_url', field=models.URLField(blank=True, null=True), ), migrations.AddField( model_name='program', name='program_image', field=models.ImageField(null=True, upload_to=''), ), ]
Check if file exists to avoid trying to delete a non-existent file. Fixes GH-23.
/* * grunt-contrib-clean * http://gruntjs.com/ * * Copyright (c) 2012 Tim Branyen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.registerMultiTask('clean', 'Clean files and folders.', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ force: false }); grunt.verbose.writeflags(options, 'Options'); // Clean specified files / dirs. this.filesSrc.forEach(function(filepath) { if (!grunt.file.exists(filepath)) { return; } grunt.log.write('Cleaning "' + filepath + '"...'); try { grunt.file.delete(filepath, options); grunt.log.ok(); } catch (e) { grunt.log.error(); grunt.verbose.error(e); grunt.fail.warn('Clean operation failed.'); } }); }); };
/* * grunt-contrib-clean * http://gruntjs.com/ * * Copyright (c) 2012 Tim Branyen, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { grunt.registerMultiTask('clean', 'Clean files and folders.', function() { // Merge task-specific and/or target-specific options with these defaults. var options = this.options({ force: false }); grunt.verbose.writeflags(options, 'Options'); // Clean specified files / dirs. this.filesSrc.forEach(function(filepath) { grunt.log.write('Cleaning "' + filepath + '"...'); try { grunt.file.delete(filepath, options); grunt.log.ok(); } catch (e) { grunt.log.error(); grunt.verbose.error(e); grunt.fail.warn('Clean operation failed.'); } }); }); };
Fix error message for unsupported extension
package main import ( "fmt" "path/filepath" "strings" ) type Language struct { Image string Command string } // TODO: This should be extracted var Extensions = map[string]Language{ ".rb": Language{"ruby:2.2", "ruby %s"}, ".py": Language{"python:2.7", "python %s"}, ".js": Language{"node:0.12", "node %s"}, ".go": Language{"golang:1.5", "go run %s"}, ".php": Language{"php:5.6", "php %s"}, ".coffee": Language{"coffescript:0.12", "coffee %s"}, } func ValidLanguage(ext string) bool { for k, _ := range Extensions { if k == ext { return true } } return false } func GetLanguageConfig(filename string) (*Language, error) { ext := filepath.Ext(strings.ToLower(filename)) if !ValidLanguage(ext) { return nil, fmt.Errorf("Extension is not supported: %s", ext) } lang := Extensions[ext] return &lang, nil }
package main import ( "fmt" "path/filepath" "strings" ) type Language struct { Image string Command string } // TODO: This should be extracted var Extensions = map[string]Language{ ".rb": Language{"ruby:2.2", "ruby %s"}, ".py": Language{"python:2.7", "python %s"}, ".js": Language{"node:0.12", "node %s"}, ".go": Language{"golang:1.5", "go run %s"}, ".php": Language{"php:5.6", "php %s"}, ".coffee": Language{"coffescript:0.12", "coffee %s"}, } func ValidLanguage(ext string) bool { for k, _ := range Extensions { if k == ext { return true } } return false } func GetLanguageConfig(filename string) (*Language, error) { ext := filepath.Ext(strings.ToLower(filename)) if !ValidLanguage(ext) { return nil, fmt.Errorf("Extension is not supported:", filename) } lang := Extensions[ext] return &lang, nil }
Add test purported to capture the failure, but it still passes.
from ._compat import Protocol from typing import Any, Dict, Iterator, List, TypeVar, Union _T = TypeVar("_T") class PackageMetadata(Protocol): def __len__(self) -> int: ... # pragma: no cover def __contains__(self, item: str) -> bool: ... # pragma: no cover def __getitem__(self, key: str) -> str: ... # pragma: no cover def __iter__(self) -> Iterator[str]: ... # pragma: no cover def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]: """ Return all values associated with a possibly multi-valued key. """ @property def json(self) -> Dict[str, Union[str, List[str]]]: """ A JSON-compatible form of the metadata. """ class SimplePath(Protocol): """ A minimal subset of pathlib.Path required by PathDistribution. >>> import pathlib >>> import typing >>> _: SimplePath = typing.cast(pathlib.Path, None) """ def joinpath(self) -> 'SimplePath': ... # pragma: no cover def __div__(self) -> 'SimplePath': ... # pragma: no cover def parent(self) -> 'SimplePath': ... # pragma: no cover def read_text(self) -> str: ... # pragma: no cover
from ._compat import Protocol from typing import Any, Dict, Iterator, List, TypeVar, Union _T = TypeVar("_T") class PackageMetadata(Protocol): def __len__(self) -> int: ... # pragma: no cover def __contains__(self, item: str) -> bool: ... # pragma: no cover def __getitem__(self, key: str) -> str: ... # pragma: no cover def __iter__(self) -> Iterator[str]: ... # pragma: no cover def get_all(self, name: str, failobj: _T = ...) -> Union[List[Any], _T]: """ Return all values associated with a possibly multi-valued key. """ @property def json(self) -> Dict[str, Union[str, List[str]]]: """ A JSON-compatible form of the metadata. """ class SimplePath(Protocol): """ A minimal subset of pathlib.Path required by PathDistribution. """ def joinpath(self) -> 'SimplePath': ... # pragma: no cover def __div__(self) -> 'SimplePath': ... # pragma: no cover def parent(self) -> 'SimplePath': ... # pragma: no cover def read_text(self) -> str: ... # pragma: no cover
Make the message panel accessible via menu
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""): panel_view = self.window.create_output_panel(PANEL_NAME) panel_view.set_read_only(False) panel_view.run_command('append', {'characters': msg}) panel_view.set_read_only(True) panel_view.show(0) self.window.run_command("show_panel", {"panel": OUTPUT_PANEL}) class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand): def run(self): self.window.destroy_output_panel(PANEL_NAME)
import sublime import sublime_plugin PANEL_NAME = "SublimeLinter Messages" OUTPUT_PANEL = "output." + PANEL_NAME def plugin_unloaded(): for window in sublime.windows(): window.destroy_output_panel(PANEL_NAME) class SublimeLinterDisplayPanelCommand(sublime_plugin.WindowCommand): def run(self, msg=""): panel_view = self.window.create_output_panel(PANEL_NAME, True) panel_view.set_read_only(False) panel_view.run_command('append', {'characters': msg}) panel_view.set_read_only(True) panel_view.show(0) self.window.run_command("show_panel", {"panel": OUTPUT_PANEL}) class SublimeLinterRemovePanelCommand(sublime_plugin.WindowCommand): def run(self): self.window.destroy_output_panel(PANEL_NAME)
Add JS event for each page load. Signed-off-by: crynobone <e1a543840a942eb68427510a8a483282a7bfeddf@gmail.com>
<?php use Illuminate\Support\Facades\Request; use Orchestra\Support\Facades\Asset; ?> <footer> <div class="container"> <hr> <p>&copy; 2012 Orchestra Platform</p> </div> </footer> <?php $asset = Asset::container('orchestra/foundation::footer'); $asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js'); $asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js'); $asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui')); $asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui')); $asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js'); echo $asset->styles(); echo $asset->scripts(); ?> @placeholder("orchestra.layout: footer") <script> jQuery(function onPageReady ($) { 'use strict'; var events = new Javie.Events; events.fire("orchestra.ready: <?php echo Request::path(); ?>"); }); </script>
<?php use Orchestra\Support\Facades\Asset; ?> <footer> <div class="container"> <hr> <p>&copy; 2012 Orchestra Platform</p> </div> </footer> <?php $asset = Asset::container('orchestra/foundation::footer'); $asset->script('bootstrap', 'packages/orchestra/foundation/vendor/bootstrap/js/bootstrap.min.js'); $asset->script('jquery-ui', 'packages/orchestra/foundation/vendor/jquery.ui.js'); $asset->script('orchestra', 'packages/orchestra/foundation/js/script.min.js', array('bootstrap', 'jquery-ui')); $asset->script('jui-toggleSwitch', 'packages/orchestra/foundation/vendor/delta/js/jquery-ui.toggleSwitch.js', array('jquery-ui')); $asset->script('select2', 'packages/orchestra/foundation/vendor/select2/select2.min.js'); echo $asset->styles(); echo $asset->scripts(); ?> @placeholder("orchestra.layout: footer")
Add first draft of plugin.
/* * textnodes * * * Copyright (c) 2014 Mark Florian * Licensed under the MIT license. */ (function($) { var rNonWhiteSpace = /\S/; function getChildTextNodes($el, list, includeWhiteSpace) { $el.contents().each(function () { console.log("called"); if (this.nodeType === 3) { if ( includeWhiteSpace && rNonWhiteSpace.test(this.textContent || this.innerText) ) { list.push(this); } } else if (this.nodeType === 1) { getChildTextNodes($(this), list); } }); } $.fn.textNodes = function (includeWhiteSpace) { var textNodes = []; getChildTextNodes(this, textNodes, includeWhiteSpace); return $(textNodes); }; }(jQuery));
/* * textnodes * * * Copyright (c) 2014 Mark Florian * Licensed under the MIT license. */ (function($) { // Collection method. $.fn.textnodes = function() { return this.each(function(i) { // Do something awesome to each selected element. $(this).html('awesome' + i); }); }; // Static method. $.textnodes = function(options) { // Override default options with passed-in options. options = $.extend({}, $.textnodes.options, options); // Return something awesome. return 'awesome' + options.punctuation; }; // Static method default options. $.textnodes.options = { punctuation: '.' }; // Custom selector. $.expr[':'].textnodes = function(elem) { // Is this element awesome? return $(elem).text().indexOf('awesome') !== -1; }; }(jQuery));
Add pytest to mocked sys.argv If you want to use this for integration tests, the ARGV variable only has to contain the arguments. The first argument usually is the script name and is not read by tornado at all.
# vim: set fileencoding=utf-8 : # # Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com> # # 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. # # from __future__ import (absolute_import, division, print_function, with_statement) import sys from tornado.ioloop import IOLoop from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase import pytest class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase): ARGV = [] SERVICE = None @pytest.fixture(autouse=True) def set_commandline(self, monkeypatch): monkeypatch.setattr(sys, 'argv', ['pytest'] + self.ARGV) def get_new_ioloop(self): return IOLoop.instance() def get_app(self): service = self.SERVICE() service.initialize_logging() return service.get_app()
# vim: set fileencoding=utf-8 : # # Copyright (c) 2014 Daniel Truemper <truemped at googlemail.com> # # 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. # # from __future__ import (absolute_import, division, print_function, with_statement) import sys from tornado.ioloop import IOLoop from tornado.testing import AsyncHTTPTestCase as TornadoAsyncHTTPTestCase import pytest class AsyncHTTPTestCase(TornadoAsyncHTTPTestCase): ARGV = [] SERVICE = None @pytest.fixture(autouse=True) def set_commandline(self, monkeypatch): monkeypatch.setattr(sys, 'argv', self.ARGV) def get_new_ioloop(self): return IOLoop.instance() def get_app(self): service = self.SERVICE() service.initialize_logging() return service.get_app()
Remove conditional that checked type of arg
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
# IdeaScaly # Copyright 2015 Jorge Saldivar # See LICENSE for details. import six import dateutil.parser def parse_datetime(str_date): try: date_is = dateutil.parser.parse(str_date) return date_is except: return None def parse_html_value(html): return html[html.find('>')+1:html.rfind('<')] def parse_a_href(atag): start = atag.find('"') + 1 end = atag.find('"', start) return atag[start:end] def convert_to_utf8_str(arg): # written by Michael Norton (http://docondev.blogspot.com/) if isinstance(arg, bytes): arg = arg.decode('ascii') if isinstance(arg, six.text_type): arg = arg.encode('utf-8') elif not isinstance(arg, bytes): arg = six.text_type(arg).encode('utf-8') return arg def import_simplejson(): try: import simplejson as json except ImportError: try: import json # Python 2.6+ except ImportError: raise ImportError("Can't load a json library") return json
Add about: pages to open home page
const trimStart = (str) => { // NOTE String.trimStart is available on Firefox 61 return str.replace(/^\s+/, ''); }; const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:', 'about:']; const searchUrl = (keywords, searchSettings) => { try { let u = new URL(keywords); if (SUPPORTED_PROTOCOLS.includes(u.protocol.toLowerCase())) { return u.href; } } catch (e) { // fallthrough } if (keywords.includes('.') && !keywords.includes(' ')) { return 'http://' + keywords; } let template = searchSettings.engines[searchSettings.default]; let query = keywords; let first = trimStart(keywords).split(' ')[0]; if (Object.keys(searchSettings.engines).includes(first)) { template = searchSettings.engines[first]; query = trimStart(trimStart(keywords).slice(first.length)); } return template.replace('{}', encodeURIComponent(query)); }; const normalizeUrl = (url) => { try { let u = new URL(url); if (SUPPORTED_PROTOCOLS.includes(u.protocol.toLowerCase())) { return u.href; } } catch (e) { // fallthrough } return 'http://' + url; }; const homepageUrls = (value) => { return value.split('|').map(normalizeUrl); }; export { searchUrl, normalizeUrl, homepageUrls };
const trimStart = (str) => { // NOTE String.trimStart is available on Firefox 61 return str.replace(/^\s+/, ''); }; const SUPPORTED_PROTOCOLS = ['http:', 'https:', 'ftp:', 'mailto:']; const searchUrl = (keywords, searchSettings) => { try { let u = new URL(keywords); if (SUPPORTED_PROTOCOLS.includes(u.protocol.toLowerCase())) { return u.href; } } catch (e) { // fallthrough } if (keywords.includes('.') && !keywords.includes(' ')) { return 'http://' + keywords; } let template = searchSettings.engines[searchSettings.default]; let query = keywords; let first = trimStart(keywords).split(' ')[0]; if (Object.keys(searchSettings.engines).includes(first)) { template = searchSettings.engines[first]; query = trimStart(trimStart(keywords).slice(first.length)); } return template.replace('{}', encodeURIComponent(query)); }; const normalizeUrl = (url) => { try { let u = new URL(url); if (SUPPORTED_PROTOCOLS.includes(u.protocol.toLowerCase())) { return u.href; } } catch (e) { // fallthrough } return 'http://' + url; }; const homepageUrls = (value) => { return value.split('|').map(normalizeUrl); }; export { searchUrl, normalizeUrl, homepageUrls };
Fix stupid circular dependency bug - sorry
'use strict'; var path = require('path'); /** * Receives a `namespace`, and an Hash of `options` to invoke a given * generator. The usual list of arguments can be set with `options.args` * (ex. nopt's argv.remain array) * * DEPRECATION notice: As of version 0.17.0, `invoke()` should usually be * replaced by `composeWith()`. * * @param {String} namespace * @param {Object} options * @param {Function} cb * * @mixin * @alias actions/invoke */ module.exports = function invoke(namespace, options, cb) { var yeoman = require('../..'); cb = cb || function () {}; options = options || {}; options.args = options.args || []; // Create a new environment, and copy the generator store to prevent // the performance cost of redoing a lookup. var env = yeoman(); env.store = this.env.store; var generator = env.create(namespace, options); this.log.emit('up'); this.log.invoke(namespace); this.log.emit('up'); generator.on('end', this.log.emit.bind(this.log, 'down')); generator.on('end', this.log.emit.bind(this.log, 'down')); return generator.run(cb); };
'use strict'; var path = require('path'); var yeoman = require('../..'); /** * Receives a `namespace`, and an Hash of `options` to invoke a given * generator. The usual list of arguments can be set with `options.args` * (ex. nopt's argv.remain array) * * DEPRECATION notice: As of version 0.17.0, `invoke()` should usually be * replaced by `composeWith()`. * * @param {String} namespace * @param {Object} options * @param {Function} cb * * @mixin * @alias actions/invoke */ module.exports = function invoke(namespace, options, cb) { cb = cb || function () {}; options = options || {}; options.args = options.args || []; // Create a new environment, and copy the generator store to prevent // the performance cost of redoing a lookup. var env = yeoman(); env.store = this.env.store; var generator = env.create(namespace, options); this.log.emit('up'); this.log.invoke(namespace); this.log.emit('up'); generator.on('end', this.log.emit.bind(this.log, 'down')); generator.on('end', this.log.emit.bind(this.log, 'down')); return generator.run(cb); };
Set transport name as public
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self.name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.data_type self._handler = handler_class(self, **handler_options) self._connected = False def _assert_not_connected(self): assert not self._connected, 'transport connection already created' def _assert_connected(self): assert self._connected, 'transport connection has not created' def _encode_obj(self, obj): return self._data_format.encode(obj) def _decode_data(self, data): return self._data_format.decode(data) def _call_handler_method(self, name, *args): getattr(self._handler, name)(*args) def is_connected(self): return self._connected def connect(self, url, **options): raise NotImplementedError def request(self, action, request_object, **params): raise NotImplementedError def close(self): raise NotImplementedError def join(self, timeout=None): raise NotImplementedError
class BaseTransport(object): """Base transport class.""" def __init__(self, name, data_format_class, data_format_options, handler_class, handler_options): self._name = name self._data_format = data_format_class(**data_format_options) self._data_type = self._data_format.data_type self._handler = handler_class(self, **handler_options) self._connected = False def _assert_not_connected(self): assert not self._connected, 'transport connection already created' def _assert_connected(self): assert self._connected, 'transport connection has not created' def _encode_obj(self, obj): return self._data_format.encode(obj) def _decode_data(self, data): return self._data_format.decode(data) def _call_handler_method(self, name, *args): getattr(self._handler, name)(*args) def is_connected(self): return self._connected def connect(self, url, **options): raise NotImplementedError def request(self, action, request_object, **params): raise NotImplementedError def close(self): raise NotImplementedError def join(self, timeout=None): raise NotImplementedError
Support output to stdout for any action Signed-off-by: David Gageot <aa743a0aaec8f7d7a1f01442503957f4d7a2d634@gageot.net>
package files import ( "io" "os" "path/filepath" ) // Copy copies a file to a given destination. It makes sur parent folders are // created on the way. Use `-` to copy to stdout. func Copy(src, dst string) error { in, err := os.Open(src) if err != nil { return err } defer in.Close() return CopyFrom(dst, 0666, in) } func CopyFrom(dst string, mode os.FileMode, reader io.Reader) error { var out io.Writer if dst == "-" { out = os.Stdout } else { if err := MkdirAll(filepath.Dir(dst)); err != nil { return err } file, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) if err != nil { return err } defer file.Close() out = file } _, err := io.Copy(out, reader) return err }
package files import ( "io" "os" "path/filepath" ) // Copy copies a file to a given destination. It makes sur parent folders are // created on the way. Use `-` to copy to stdout. func Copy(src, dst string) error { if dst != "-" { if err := MkdirAll(filepath.Dir(dst)); err != nil { return err } } in, err := os.Open(src) if err != nil { return err } defer in.Close() var out io.Writer if dst != "-" { destOut, err := os.Create(dst) if err != nil { return err } defer destOut.Close() out = destOut } else { out = os.Stdout } _, err = io.Copy(out, in) return err } func CopyFrom(dst string, mode os.FileMode, reader io.Reader) error { if err := MkdirAll(filepath.Dir(dst)); err != nil { return err } file, err := os.OpenFile(dst, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, mode) if err != nil { return err } defer file.Close() _, err = io.Copy(file, reader) return err }
Exclude a few failing tests Rsd - failing on linux due to running out of memory Verilator - failing on Windows clang due to stack overflow caused by expression evaluation
import os import platform # If you are adding a new entry, please include a short comment # explaining why the specific test is blacklisted. _unix_black_list = set([name.lower() for name in [ 'blackparrot', 'blackucode', 'blackunicore', 'earlgrey_nexysvideo', # ram size in ci machines 'lpddr', 'rsd', # Out of memory on CI machines 'simpleparsertestcache', # race condition ]]) _windows_black_list = _unix_black_list.union(set([name.lower() for name in [ 'ariane', # Uses shell script with make command 'earlgrey_verilator_01_05_21', # lowmem is unsupported 'unitpython', # Python is unsupported 'verilator', # Stack overflow with clang due to expression evaluation ]])) _msys2_black_list = _unix_black_list.union(set([name.lower() for name in [ 'earlgrey_verilator_01_05_21', # lowmem is unsupported ]])) def is_blacklisted(name): if platform.system() == 'Windows': blacklist = _msys2_black_list if 'MSYSTEM' in os.environ else _windows_black_list else: blacklist = _unix_black_list return name.lower() in blacklist
import os import platform # If you are adding a new entry, please include a short comment # explaining why the specific test is blacklisted. _unix_black_list = set([name.lower() for name in [ 'blackparrot', 'blackucode', 'blackunicore', 'earlgrey_nexysvideo', # ram size in ci machines 'lpddr', 'simpleparsertestcache', # race condition ]]) _windows_black_list = _unix_black_list.union(set([name.lower() for name in [ 'ariane', # Uses shell script with make command 'earlgrey_verilator_01_05_21', # lowmem is unsupported 'unitpython', # Python is unsupported ]])) _msys2_black_list = _unix_black_list.union(set([name.lower() for name in [ 'earlgrey_verilator_01_05_21', # lowmem is unsupported ]])) def is_blacklisted(name): if platform.system() == 'Windows': blacklist = _msys2_black_list if 'MSYSTEM' in os.environ else _windows_black_list else: blacklist = _unix_black_list return name.lower() in blacklist
Use SwatDB's abstraction so that this function will work with both PostgreSQL and MySQL. svn commit r36046
<?php require_once 'Site/SitePath.php'; /** * @package Site * @copyright 2007 silverorange */ class SiteArticlePath extends SitePath { // {{{ public function __construct() /** * Creates a new article path object * * @param SiteWebApplication $app the application this path exists in. * @param integer $id the database id of the object to create the path for. * If no database id is specified, an empty path is * created. */ public function __construct(SiteWebApplication $app, $id = null) { if ($id !== null) $this->loadFromId($app, $id); } // }}} // {{{ protected function loadFromId() /** * Creates a new path object * * @param integer $article_id. */ public function loadFromId(SiteWebApplication $app, $article_id) { foreach ($this->queryPath($app, $article_id) as $row) $this->addEntry(new SitePathEntry( $row->id, $row->parent, $row->shortname, $row->title)); } // }}} // {{{ protected function queryPath() protected function queryPath($app, $article_id) { return SwatDB::executeStoredProc($app->db, 'getArticlePathInfo', $article_id); } // }}} } ?>
<?php require_once 'Site/SitePath.php'; /** * @package Site * @copyright 2007 silverorange */ class SiteArticlePath extends SitePath { // {{{ public function __construct() /** * Creates a new article path object * * @param SiteWebApplication $app the application this path exists in. * @param integer $id the database id of the object to create the path for. * If no database id is specified, an empty path is * created. */ public function __construct(SiteWebApplication $app, $id = null) { if ($id !== null) $this->loadFromId($app, $id); } // }}} // {{{ protected function loadFromId() /** * Creates a new path object * * @param integer $article_id. */ public function loadFromId(SiteWebApplication $app, $article_id) { foreach ($this->queryPath($app, $article_id) as $row) $this->addEntry(new SitePathEntry( $row->id, $row->parent, $row->shortname, $row->title)); } // }}} // {{{ protected function queryPath() protected function queryPath($app, $article_id) { $sql = sprintf('select * from getArticlePathInfo(%s)', $app->db->quote($article_id, 'integer')); return SwatDB::query($app->db, $sql); } // }}} } ?>
Remove references to User class
import datetime import psycopg2 from sqlalchemy import ( Column, DateTime, Integer, Unicode, UnicodeText, ForeignKey, ) from pyramid.security import Allow, Everyone from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class Entry(Base): """Our Journal Entry class.""" __tablename__ = 'entries' id = Column(Integer, primary_key=True) title = Column(Unicode(128), unique=True) text = Column(UnicodeText) created = Column(DateTime, default=datetime.datetime.utcnow) @property def __acl__(self): """Add permissions for specific instance of Entry object. self.author.username is the user who created this Entry instance. """ return [ (Allow, Everyone, 'view'), (Allow, self.author.username, 'edit') ]
import datetime import psycopg2 from sqlalchemy import ( Column, DateTime, Integer, Unicode, UnicodeText, ForeignKey, ) from pyramid.security import Allow, Everyone from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import ( scoped_session, sessionmaker, relationship, ) from zope.sqlalchemy import ZopeTransactionExtension DBSession = scoped_session(sessionmaker(extension=ZopeTransactionExtension())) Base = declarative_base() class Entry(Base): """Our Journal Entry class.""" __tablename__ = 'entries' id = Column(Integer, primary_key=True) title = Column(Unicode(128), unique=True) text = Column(UnicodeText) created = Column(DateTime, default=datetime.datetime.utcnow) author_id = Column(Integer, ForeignKey('users.id')) #Ties User model to Entry model author = relationship('User', back_populates='entries') @property def __acl__(self): """Add permissions for specific instance of Entry object. self.author.username is the user who created this Entry instance. """ return [ (Allow, Everyone, 'view'), (Allow, self.author.username, 'edit') ]
[2.8] Fix issues reported by static analyse
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\EventListener; use Symfony\Component\HttpFoundation\Session\SessionInterface; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Sets the session in the request. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ abstract class SessionListener implements EventSubscriberInterface { public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $session = $this->getSession(); if (null === $session || $request->hasSession()) { return; } $request->setSession($session); } public static function getSubscribedEvents() { return array( KernelEvents::REQUEST => array('onKernelRequest', 128), ); } /** * Gets the session object. * * @return SessionInterface|null A SessionInterface instance or null if no session is available */ abstract protected function getSession(); }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\HttpKernel\EventListener; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; use Symfony\Component\EventDispatcher\EventSubscriberInterface; /** * Sets the session in the request. * * @author Johannes M. Schmitt <schmittjoh@gmail.com> */ abstract class SessionListener implements EventSubscriberInterface { public function onKernelRequest(GetResponseEvent $event) { if (!$event->isMasterRequest()) { return; } $request = $event->getRequest(); $session = $this->getSession(); if (null === $session || $request->hasSession()) { return; } $request->setSession($session); } public static function getSubscribedEvents() { return array( KernelEvents::REQUEST => array('onKernelRequest', 128), ); } /** * Gets the session object. * * @return SessionInterface|null A SessionInterface instance or null if no session is available */ abstract protected function getSession(); }
hibernate: Use IDENTITY as strategy for entity
/* * MIT Licence * Copyright (c) 2017 Simon Frankenberger * * Please see LICENCE.md for complete licence text. */ package eu.fraho.spring.securityJwt.hibernate.dto; import lombok.*; import javax.persistence.*; import java.time.ZonedDateTime; @Entity @Table(name = "jwt_refresh") @Getter @Setter @EqualsAndHashCode(of = {"userId", "username", "token"}) @ToString(of = {"id", "userId", "username", "token"}) @NoArgsConstructor public class RefreshTokenEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Setter(AccessLevel.NONE) private Long id = 0L; @Column(updatable = false) @Setter(AccessLevel.NONE) @Convert(converter = ZonedDateTimeConverter.class) private ZonedDateTime created = ZonedDateTime.now(); private Long userId; private String username; @Column(unique = true) private String token; @Builder private RefreshTokenEntity(Long userId, String username, String token) { this.userId = userId; this.username = username; this.token = token; } }
/* * MIT Licence * Copyright (c) 2017 Simon Frankenberger * * Please see LICENCE.md for complete licence text. */ package eu.fraho.spring.securityJwt.hibernate.dto; import lombok.*; import javax.persistence.*; import java.time.ZonedDateTime; @Entity @Table(name = "jwt_refresh") @Getter @Setter @EqualsAndHashCode(of = {"userId", "username", "token"}) @ToString(of = {"id", "userId", "username", "token"}) @NoArgsConstructor public class RefreshTokenEntity { @Id @GeneratedValue @Setter(AccessLevel.NONE) private Long id = 0L; @Column(updatable = false) @Setter(AccessLevel.NONE) @Convert(converter = ZonedDateTimeConverter.class) private ZonedDateTime created = ZonedDateTime.now(); private Long userId; private String username; @Column(unique = true) private String token; @Builder private RefreshTokenEntity(Long userId, String username, String token) { this.userId = userId; this.username = username; this.token = token; } }
Return FALSE when account is not valid
<?php namespace Shoptet\Spayd\Utilities; use Shoptet\Spayd\Exceptions; class IbanUtilities { public static function computeIBANFromCzechBankAccount(\Shoptet\Spayd\Model\CzechAccount $czechAccount) { if ($czechAccount->isValid()) { $prefix = sprintf('%06d', $czechAccount->getPrefix()); $accountNumber = sprintf('%010d', $czechAccount->getAccountNumber()); $bankCode = sprintf('%04d', $czechAccount->getBankCode()); $accountBuffer = $bankCode . $prefix . $accountNumber . $czechAccount->getNumericLanguageCode(); $checksum = sprintf('%02d', (98 - bcmod($accountBuffer, 97))); // build the IBAN number return 'CZ' . $checksum . $bankCode . $prefix . $accountNumber; } else { return FALSE; } } }
<?php namespace Shoptet\Spayd\Utilities; use Shoptet\Spayd\Exceptions; class IbanUtilities { public static function computeIBANFromCzechBankAccount(\Shoptet\Spayd\Model\CzechAccount $czechAccount) { if ($czechAccount->isValid()) { $prefix = sprintf('%06d', $czechAccount->getPrefix()); $accountNumber = sprintf('%010d', $czechAccount->getAccountNumber()); $bankCode = sprintf('%04d', $czechAccount->getBankCode()); } $accountBuffer = $bankCode . $prefix . $accountNumber . $czechAccount->getNumericLanguageCode(); $checksum = sprintf('%02d', (98 - bcmod($accountBuffer, 97))); // build the IBAN number return 'CZ' . $checksum . $bankCode . $prefix . $accountNumber; } }
Fix tags index test because of layout changes
<?php namespace Frontend\Modules\Tags\Tests\Actions; use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags; use Backend\Modules\Tags\DataFixtures\LoadTagsTags; use Frontend\Core\Tests\FrontendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends FrontendWebTestCase { public function testTagsIndexShowsTags(Client $client): void { $this->loadFixtures( $client, [ LoadTagsTags::class, LoadTagsModulesTags::class, ] ); self::assertPageLoadedCorrectly( $client, '/en/tags', [ '<a href="/en/tags/detail/most-used" rel="tag">', LoadTagsTags::TAGS_TAG_2_NAME, '<span class="badge badge-primary">6</span>', ] ); } }
<?php namespace Frontend\Modules\Tags\Tests\Actions; use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags; use Backend\Modules\Tags\DataFixtures\LoadTagsTags; use Frontend\Core\Tests\FrontendWebTestCase; use Symfony\Bundle\FrameworkBundle\Client; class IndexTest extends FrontendWebTestCase { public function testTagsIndexShowsTags(Client $client): void { $this->loadFixtures( $client, [ LoadTagsTags::class, LoadTagsModulesTags::class, ] ); self::assertPageLoadedCorrectly( $client, '/en/tags', [ '<a href="/en/tags/detail/most-used" rel="tag">', LoadTagsTags::TAGS_TAG_2_NAME, '<span class="badge hidden-phone">6</span>', ] ); } }
Call Flush() in Fatal() methods of lib/log/serverlogger.Logger.
package serverlogger import ( "flag" "fmt" "github.com/Symantec/Dominator/lib/log/debuglogger" "github.com/Symantec/Dominator/lib/logbuf" "io" "os" ) var ( initialLogDebugLevel = flag.Int("initialLogDebugLevel", -1, "initial debug log level") ) type Logger struct { *debuglogger.Logger circularBuffer *logbuf.LogBuffer } // New will create a Logger which has an internal log buffer (see the // lib/logbuf package). It implements the log.DebugLogger interface. // By default, the max debug level is -1, meaning all debug logs are dropped // (ignored) func New() *Logger { return newLogger() } func (l *Logger) Fatal(v ...interface{}) { msg := fmt.Sprint(v...) l.Print(msg) l.circularBuffer.Flush() os.Exit(1) } func (l *Logger) Fatalf(format string, v ...interface{}) { l.Fatal(fmt.Sprintf(format, v...)) } func (l *Logger) Fatalln(v ...interface{}) { l.Fatal(fmt.Sprintln(v...)) } // Flush flushes the open log file (if one is open). This should only be called // just prior to process termination. The log file is automatically flushed // after short periods of inactivity. func (l *Logger) Flush() error { return l.circularBuffer.Flush() } // WriteHtml will write the contents of the internal log buffer to writer, with // appropriate HTML markups. func (l *Logger) WriteHtml(writer io.Writer) { l.circularBuffer.WriteHtml(writer) }
package serverlogger import ( "flag" "github.com/Symantec/Dominator/lib/log/debuglogger" "github.com/Symantec/Dominator/lib/logbuf" "io" ) var ( initialLogDebugLevel = flag.Int("initialLogDebugLevel", -1, "initial debug log level") ) type Logger struct { *debuglogger.Logger circularBuffer *logbuf.LogBuffer } // New will create a Logger which has an internal log buffer (see the // lib/logbuf package). It implements the log.DebugLogger interface. // By default, the max debug level is -1, meaning all debug logs are dropped // (ignored) func New() *Logger { return newLogger() } // Flush flushes the open log file (if one is open). This should only be called // just prior to process termination. The log file is automatically flushed // after short periods of inactivity. func (l *Logger) Flush() error { return l.circularBuffer.Flush() } // WriteHtml will write the contents of the internal log buffer to writer, with // appropriate HTML markups. func (l *Logger) WriteHtml(writer io.Writer) { l.circularBuffer.WriteHtml(writer) }
Change slug to key to match FlatList implementation
const fs = require('fs'); const _ = require('lodash'); _.mixin(require('lodash-inflection')); const IMAGE_PATH = process.argv[2]; const images = fs.readdirSync(IMAGE_PATH, 'utf8'); let baseStructure = { wrestlers: {} }; images.forEach(function(image) { const tempObj = {}; const cleanKey = image.slice(0, -4); const slug = createSlug(cleanKey); let imageFile = fs.readFileSync(IMAGE_PATH + '/' + image); imageFile = new Buffer(imageFile, 'binary').toString('base64'); tempObj[slug] = { key: slug, name: _.titleize(cleanKey.split('-').join(' ')), image: 'data:image/jpg;base64,' + imageFile } _.extend(baseStructure.wrestlers, tempObj); }); const output = JSON.stringify(baseStructure); fs.writeFile('wrestlers.json', output, 'utf8', function(err) { if(err) { console.log(err); } else { console.log('File created'); } }); function createSlug(key) { key = key.replace('$', 'S'); return key.toLowerCase(); }
const fs = require('fs'); const _ = require('lodash'); _.mixin(require('lodash-inflection')); const IMAGE_PATH = process.argv[2]; const images = fs.readdirSync(IMAGE_PATH, 'utf8'); let baseStructure = { wrestlers: {} }; images.forEach(function(image) { const tempObj = {}; const cleanKey = image.slice(0, -4); const slug = createSlug(cleanKey); let imageFile = fs.readFileSync(IMAGE_PATH + '/' + image); imageFile = new Buffer(imageFile, 'binary').toString('base64'); tempObj[slug] = { slug: slug, name: _.titleize(cleanKey.split('-').join(' ')), image: 'data:image/jpg;base64,' + imageFile } _.extend(baseStructure.wrestlers, tempObj); }); const output = JSON.stringify(baseStructure); fs.writeFile('wrestlers.json', output, 'utf8', function(err) { if(err) { console.log(err); } else { console.log('File created'); } }); function createSlug(key) { key = key.replace('$', 'S'); return key.toLowerCase(); }
Fix [object Object] in sendLocale extendable #494
const { APIMessage } = require('discord.js'); const { Extendable } = require('klasa'); const { TextChannel, DMChannel, GroupDMChannel, User } = require('discord.js'); module.exports = class extends Extendable { constructor(...args) { super(...args, { appliesTo: [TextChannel, DMChannel, GroupDMChannel, User] }); } sendCode(code, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { code })); } sendEmbed(embed, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { embed })); } sendFile(attachment, name, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { files: [{ attachment, name }] })); } sendFiles(files, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { files })); } sendLocale(key, args = [], options = {}) { if (!Array.isArray(args)) [options, args] = [args, []]; const language = this.guild ? this.guild.language : this.client.languages.default; return this.send(language.get(key, ...args), options); } sendMessage(content, options) { return this.send(content, options); } };
const { APIMessage } = require('discord.js'); const { Extendable } = require('klasa'); const { TextChannel, DMChannel, GroupDMChannel, User } = require('discord.js'); module.exports = class extends Extendable { constructor(...args) { super(...args, { appliesTo: [TextChannel, DMChannel, GroupDMChannel, User] }); } sendCode(code, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { code })); } sendEmbed(embed, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { embed })); } sendFile(attachment, name, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { files: [{ attachment, name }] })); } sendFiles(files, content, options = {}) { return this.send(APIMessage.transformOptions(content, options, { files })); } sendLocale(key, args = [], options = {}) { if (!Array.isArray(args)) [options, args] = [args, []]; const language = this.guild ? this.guild.language : this.client.languages.default; return this.send({ content: language.get(key, ...args), ...options }); } sendMessage(content, options) { return this.send(content, options); } };
Handle Ctrl + C when running demo in the terminal.
import speech_recognition as sr r = sr.Recognizer() m = sr.Microphone() try: print("A moment of silence, please...") with m as source: r.adjust_for_ambient_noise(source) print("Set minimum energy threshold to {}".format(r.energy_threshold)) while True: print("Say something!") audio = r.listen(source) print("Got it! Now to recognize it...") try: value = r.recognize(audio) if str is bytes: # this version of Python uses bytes for strings (Python 2) print(u"You said {}".format(value).encode("utf-8")) else: # this version of Python uses unicode for strings (Python 3+) print("You said {}".format(value)) except LookupError: print("Oops! Didn't catch that") except KeyboardInterrupt: pass
import speech_recognition as sr r = sr.Recognizer() m = sr.Microphone() print("A moment of silence, please...") with m as source: r.adjust_for_ambient_noise(source) print("Set minimum energy threshold to {}".format(r.energy_threshold)) while True: print("Say something!") audio = r.listen(source) print("Got it! Now to recognize it...") try: value = r.recognize(audio) if str is bytes: # this version of Python uses bytes for strings (Python 2) print(u"You said {}".format(value).encode("utf-8")) else: # this version of Python uses unicode for strings (Python 3+) print("You said {}".format(value)) except LookupError: print("Oops! Didn't catch that")
Use ShellMenu instead of DefaultMenu
package org.jboss.reddeer.eclipse.jface.wizard; import org.apache.log4j.Logger; import org.jboss.reddeer.swt.api.Menu; import org.jboss.reddeer.swt.impl.menu.ShellMenu; import org.jboss.reddeer.swt.impl.shell.ActiveShell; import org.jboss.reddeer.swt.impl.tree.DefaultTreeItem; /** * Abstract class to manage new wizard dialog * @author vpakan * */ public abstract class NewWizardDialog extends WizardDialog{ public static final String DIALOG_TITLE = "New"; private String[] path; protected final Logger log = Logger.getLogger(this.getClass()); /** * @param path - path to new object to be created within tree widget * inside New wizard dialog */ public NewWizardDialog(String... path) { this.path = path; } /** * Opens wizard for new object to be created */ public void open(){ log.info("Open New Wizard"); super.open(); Menu menu = new ShellMenu("File","New","Other..."); menu.select(); new ActiveShell(DIALOG_TITLE); if (path.length > 0){ new DefaultTreeItem(path).select(); next(); } } }
package org.jboss.reddeer.eclipse.jface.wizard; import org.apache.log4j.Logger; import org.jboss.reddeer.swt.api.Menu; import org.jboss.reddeer.swt.impl.menu.DefaultMenu; import org.jboss.reddeer.swt.impl.shell.ActiveShell; import org.jboss.reddeer.swt.impl.tree.DefaultTreeItem; /** * Abstract class to manage new wizard dialog * @author vpakan * */ public abstract class NewWizardDialog extends WizardDialog{ public static final String DIALOG_TITLE = "New"; private String[] path; protected final Logger log = Logger.getLogger(this.getClass()); /** * @param path - path to new object to be created within tree widget * inside New wizard dialog */ public NewWizardDialog(String... path) { this.path = path; } /** * Opens wizard for new object to be created */ public void open(){ log.info("Open New Wizard"); super.open(); Menu menu = new DefaultMenu("File","New","Other..."); menu.select(); new ActiveShell(DIALOG_TITLE); if (path.length > 0){ new DefaultTreeItem(path).select(); next(); } } }
Upgrade for the Redux DevTools extension.
// This file merely configures the store for hot reloading. // This boilerplate file is likely to be the same for each project that uses Redux. // With Redux, the actual stores are in /reducers. import {createStore, compose, applyMiddleware} from 'redux'; import reduxImmutableStateInvariant from 'redux-immutable-state-invariant'; import thunkMiddleware from 'redux-thunk'; import rootReducer from '../reducers'; export default function configureStore(initialState) { const middlewares = [ // Add other middleware on this line... // Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches. reduxImmutableStateInvariant(), // thunk middleware can also accept an extra argument to be passed to each thunk action // https://github.com/gaearon/redux-thunk#injecting-a-custom-argument thunkMiddleware, ]; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; // add support for Redux dev tools const store = createStore(rootReducer, initialState, composeEnhancers( applyMiddleware(...middlewares) ) ); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextReducer = require('../reducers').default; // eslint-disable-line global-require store.replaceReducer(nextReducer); }); } return store; }
// This file merely configures the store for hot reloading. // This boilerplate file is likely to be the same for each project that uses Redux. // With Redux, the actual stores are in /reducers. import {createStore, compose, applyMiddleware} from 'redux'; import reduxImmutableStateInvariant from 'redux-immutable-state-invariant'; import thunkMiddleware from 'redux-thunk'; import rootReducer from '../reducers'; export default function configureStore(initialState) { const middlewares = [ // Add other middleware on this line... // Redux middleware that spits an error on you when you try to mutate your state either inside a dispatch or between dispatches. reduxImmutableStateInvariant(), // thunk middleware can also accept an extra argument to be passed to each thunk action // https://github.com/gaearon/redux-thunk#injecting-a-custom-argument thunkMiddleware, ]; const store = createStore(rootReducer, initialState, compose( applyMiddleware(...middlewares), window.devToolsExtension ? window.devToolsExtension() : f => f // add support for Redux dev tools ) ); if (module.hot) { // Enable Webpack hot module replacement for reducers module.hot.accept('../reducers', () => { const nextReducer = require('../reducers').default; // eslint-disable-line global-require store.replaceReducer(nextReducer); }); } return store; }
Add Redux DevTools Extension & Hot reload reducers not working
import { createStore, applyMiddleware, compose, combineReducers } from 'redux'; import thunk from 'redux-thunk' import createLogger from 'redux-logger'; import rootReducer from '../reducers'; import interentDetector from '../middleware/interentDetector'; const logger = createLogger(); // https://github.com/zalmoxisus/redux-devtools-extension // https://github.com/chentsulin/electron-react-boilerplate/blob/master/app/store/configureStore.development.js // https://github.com/zalmoxisus/redux-devtools-extension#12-advanced-store-setup const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ // Options: http://zalmoxisus.github.io/redux-devtools-extension/API/Arguments.html // actionCreators, }) : compose; const enhancer = composeEnhancers( applyMiddleware(interentDetector, thunk, logger) ); export default function configureStore(initialState) { // Note: only Redux >= 3.1.0 supports passing enhancer as third argument. // See https://github.com/rackt/redux/releases/tag/v3.1.0 const store = createStore(rootReducer, initialState, enhancer); // FIXME: not working // Hot reload reducers (requires Webpack or Browserify HMR to be enabled) if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(require('../reducers')) ); } return store; }
import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk' import createLogger from 'redux-logger'; import rootReducer from '../reducers'; import interentDetector from '../middleware/interentDetector'; const logger = createLogger(); const enhancer = applyMiddleware(interentDetector, thunk, logger); export default function configureStore(initialState) { // Note: only Redux >= 3.1.0 supports passing enhancer as third argument. // See https://github.com/rackt/redux/releases/tag/v3.1.0 const store = createStore(rootReducer, initialState, enhancer); // Hot reload reducers (requires Webpack or Browserify HMR to be enabled) if (module.hot) { module.hot.accept('../reducers', () => store.replaceReducer(require('../reducers')/*.default if you use Babel 6+ */) ); } return store; }
Include management commands when installed.
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup setup( name='rna', version='0.0.1', description='', author='Josh Mize', author_email='jmize@mozilla.com', #url='', #license='', packages=[ 'rna', 'rna.migrations', 'rna.management.commands'], install_requires=[ 'South', 'Django>=1.4.9', 'djangorestframework==2.3.7', 'django-extensions==1.2.0'], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Programming Language :: Python'], )
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from setuptools import setup setup( name='rna', version='0.0.1', description='', author='Josh Mize', author_email='jmize@mozilla.com', #url='', #license='', packages=[ 'rna', 'rna.migrations'], install_requires=[ 'South', 'Django>=1.4.9', 'djangorestframework==2.3.7', 'django-extensions==1.2.0'], classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Programming Language :: Python'], )
Fix error when saving the claim to the wallet.
import json import logging class ClaimParser(object): """ Parses a generic claim. """ def __init__(self, claim: str) -> None: self.__logger = logging.getLogger(__name__) self.__orgData = claim self.__parse() def __parse(self): self.__logger.debug("Parsing claim ...") data = json.loads(self.__orgData) self.__claim_type = data["claim_type"] self.__claim = data["claim_data"] self.__issuer_did = data["claim_data"]["issuer_did"] def getField(self, field): return self.__claim["claim"][field][0] @property def schemaName(self) -> str: return self.__claim_type @property def issuerDid(self) -> str: return self.__issuer_did @property def json(self) -> str: return json.dumps(self.__claim)
import json import logging class ClaimParser(object): """ Parses a generic claim. """ def __init__(self, claim: str) -> None: self.__logger = logging.getLogger(__name__) self.__orgData = claim self.__parse() def __parse(self): self.__logger.debug("Parsing claim ...") data = json.loads(self.__orgData) self.__claim_type = data["claim_type"] self.__claim = data["claim_data"] self.__issuer_did = data["claim_data"]["issuer_did"] def getField(self, field): return self.__claim["claim"][field][0] @property def schemaName(self) -> str: return self.__claim_type @property def issuerDid(self) -> str: return self.__issuer_did @property def json(self) -> str: return self.__claim
Load keyboard shortcuts json using json requirejs plugin so that it can be compiled into build
define(['require', 'app', 'backbone.marionette', 'backbone', 'marked', 'underscore', 'json!./keyboardShortcuts.json'], function (require, App, Marionette, Backbone, marked, _, keyboardShortcuts) { 'use strict'; var controller = { showHelp: function () { require(['./views/HelpView'], function (HelpView) { _.each(keyboardShortcuts, function (category) { _.each(category.shortcuts, function (shortcut) { shortcut.description = marked(shortcut.description); }); }); var helpModel = new Backbone.Model({keyboardShortcuts: keyboardShortcuts}); App.mainRegion.show(new HelpView({model: helpModel})); }); } }; App.addInitializer(function () { new Marionette.AppRouter({ controller: controller, appRoutes: { 'help': 'showHelp' } }); }); });
define(['require', 'app', 'backbone.marionette', 'backbone', 'marked', 'underscore'], function (require, App, Marionette, Backbone, marked, _) { 'use strict'; var controller = { showHelp: function () { require(['./views/HelpView'], function (HelpView) { $.getJSON('/scripts/help/keyboardShortcuts.json', function (data) { _.each(data, function (category) { _.each(category.shortcuts, function (shortcut) { shortcut.description = marked(shortcut.description); }) }); var helpModel = new Backbone.Model({keyboardShortcuts: data}); App.mainRegion.show(new HelpView({model: helpModel})); }); }); } }; App.addInitializer(function () { new Marionette.AppRouter({ controller: controller, appRoutes: { 'help': 'showHelp' } }); }); });
Use dict in render_to_string when sending email Building a Context manually like this is deprecated in Django 1.11, so let's not do it this way.
import logging from django.conf import settings from django.core.mail import send_mail from django.contrib.sites.models import Site from django.template.loader import render_to_string logger = logging.getLogger(__file__) def send_ticket_email_to_customer(reservation, email, name=None): '''Send an email to the customer with a link to their tickets If the supplied email is empty, this will silently fail. The reason for this is that this is used in the payment flow, and if we raise an error here, it will crash the payment transaction, and at that point we have likely charged someone's card without giving them tickets. Therefore the trade-off is made that if the customer fails to provide a valid email address, they will not receive an email. They will however, have another chance to send the reservation information via email at the reservation-detail page. ''' if not email: return if not name: name = email to_address = f'{name} <{email}>' subject = 'Dina biljetter till Kårspexet' site = Site.objects.get_current() reservation_url = f'https://{site.domain}{reservation.get_absolute_url()}' body = render_to_string('reservation_email.txt', { 'reservation': reservation, 'url': reservation_url, }) send_mail( subject, body, settings.TICKET_EMAIL_FROM_ADDRESS, [to_address], fail_silently=False, )
import logging from django.conf import settings from django.core.mail import send_mail from django.contrib.sites.models import Site from django.template.loader import render_to_string from django.template import Context logger = logging.getLogger(__file__) def send_ticket_email_to_customer(reservation, email, name=None): '''Send an email to the customer with a link to their tickets If the supplied email is empty, this will silently fail. The reason for this is that this is used in the payment flow, and if we raise an error here, it will crash the payment transaction, and at that point we have likely charged someone's card without giving them tickets. Therefore the trade-off is made that if the customer fails to provide a valid email address, they will not receive an email. They will however, have another chance to send the reservation information via email at the reservation-detail page. ''' if not email: return if not name: name = email to_address = f'{name} <{email}>' subject = 'Dina biljetter till Kårspexet' site = Site.objects.get_current() reservation_url = f'https://{site.domain}{reservation.get_absolute_url()}' body = render_to_string('reservation_email.txt', Context({ 'reservation': reservation, 'url': reservation_url, })) send_mail( subject, body, settings.TICKET_EMAIL_FROM_ADDRESS, [to_address], fail_silently=False, )
Fix audio not played successively
'use babel'; import { CompositeDisposable } from 'atom'; import memoize from 'memoizee'; import path from 'path'; const KEYS = { DELETE: 8, ENTER : 13, SPACE : 32 }; const AUDIO_MAP = { [KEYS.DELETE]: 'delete_press.mp3', [KEYS.ENTER] : 'spacebar_press.mp3', [KEYS.SPACE] : 'spacebar_press.mp3', DEFAULT : 'key_press.mp3' }; let getAudio = memoize(name => new Audio(path.join(__dirname, 'audio', name)), { primitive: true }); export default { subscriptions: null, activate() { let disposables = atom.workspace.observeTextEditors(editor => { let view = atom.views.getView(editor); view.addEventListener('keydown', this.handleKeyDown); }); this.subscriptions = new CompositeDisposable(disposables); }, deactivate() { atom.workspace.getTextEditors().forEach(editor => { let view = atom.views.getView(editor); view.removeEventListener('keydown', this.handleKeyDown); }); this.subscriptions.dispose(); }, handleKeyDown({ keyCode }) { let audio = getAudio(AUDIO_MAP[keyCode] || AUDIO_MAP.DEFAULT); audio.currentTime = 0; audio.play(); } };
'use babel'; import { CompositeDisposable } from 'atom'; import memoize from 'memoizee'; import path from 'path'; const KEYS = { DELETE: 8, ENTER: 13, SPACE: 32 }; let getAudio = memoize(function(keyCode) { let name; switch (keyCode) { case KEYS.ENTER : case KEYS.SPACE : name = 'spacebar_press.mp3'; break; case KEYS.DELETE: name = 'delete_press.mp3'; break; default : name = 'key_press.mp3'; break; } return new Audio(path.join(__dirname, 'audio', name)); }, { primitive: true }); export default { subscriptions: null, activate() { let disposables = atom.workspace.observeTextEditors(editor => { let view = atom.views.getView(editor); view.addEventListener('keydown', this.handleKeyDown); }); this.subscriptions = new CompositeDisposable(disposables); }, deactivate() { atom.workspace.getTextEditors().forEach(editor => { let view = atom.views.getView(editor); view.removeEventListener('keydown', this.handleKeyDown); }); this.subscriptions.dispose(); }, handleKeyDown(e) { let audio = getAudio(e.keyCode); audio.play(); } };
Use SelectionButtons live selector, for JS/AJAX content Some GOV.UK pages, like Smart Answers, load content via JS, including radio buttons or checkboxes. These will be added to the DOM after the selector is run and the resulting elements are passed to SelectionButtons SelectionButtons can also take a string selector and use document events (https://github.com/alphagov/govuk_frontend_toolkit/pull/139/) so use that and any JS loaded content will get the behaviour too.
$(document).ready(function() { $('.print-link a').attr('target', '_blank'); var $searchFocus = $('.js-search-focus'); $searchFocus.each(function(i, el){ if($(el).val() !== ''){ $(el).addClass('focus'); } }); $searchFocus.on('focus', function(e){ $(e.target).addClass('focus'); }); $searchFocus.on('blur', function(e){ if($(e.target).val() === ''){ $(e.target).removeClass('focus'); } }); if (window.GOVUK) { if (GOVUK.userSatisfaction){ var currentURL = window.location.pathname; function stringContains(str, substr) { return str.indexOf(substr) > -1; } // We don't want the satisfaction survey appearing for users who // have completed a transaction as they may complete the survey with // the department's transaction in mind as opposed to the GOV.UK content. if (!stringContains(currentURL, "/done") && !stringContains(currentURL, "/transaction-finished") && !stringContains(currentURL, "/driving-transaction-finished")) { GOVUK.userSatisfaction.randomlyShowSurveyBar(); } } } // for radio buttons and checkboxes var buttonsSelector = "label.selectable input[type='radio'], label.selectable input[type='checkbox']"; new GOVUK.SelectionButtons(buttonsSelector); });
$(document).ready(function() { $('.print-link a').attr('target', '_blank'); var $searchFocus = $('.js-search-focus'); $searchFocus.each(function(i, el){ if($(el).val() !== ''){ $(el).addClass('focus'); } }); $searchFocus.on('focus', function(e){ $(e.target).addClass('focus'); }); $searchFocus.on('blur', function(e){ if($(e.target).val() === ''){ $(e.target).removeClass('focus'); } }); if (window.GOVUK) { if (GOVUK.userSatisfaction){ var currentURL = window.location.pathname; function stringContains(str, substr) { return str.indexOf(substr) > -1; } // We don't want the satisfaction survey appearing for users who // have completed a transaction as they may complete the survey with // the department's transaction in mind as opposed to the GOV.UK content. if (!stringContains(currentURL, "/done") && !stringContains(currentURL, "/transaction-finished") && !stringContains(currentURL, "/driving-transaction-finished")) { GOVUK.userSatisfaction.randomlyShowSurveyBar(); } } } // for radio buttons and checkboxes var $buttons = $("label.selectable input[type='radio'], label.selectable input[type='checkbox']"); new GOVUK.SelectionButtons($buttons); });
Fix bug that prevent commands with no values from being added
from django.db import models class Camera(models.Model): ssid = models.CharField(max_length=255) password = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) last_attempt = models.DateTimeField(auto_now=True) last_update = models.DateTimeField(null=True, blank=True) image_last_update = models.DateTimeField(null=True, blank=True) image = models.TextField(blank=True) summary = models.TextField(blank=True) status = models.TextField(blank=True) connection_attempts = models.IntegerField(default=0) connection_failures = models.IntegerField(default=0) def __unicode__(self): return self.ssid class Command(models.Model): camera = models.ForeignKey(Camera) command = models.CharField(max_length=255) value = models.CharField(blank=True, max_length=255) date_added = models.DateTimeField(auto_now_add=True) time_completed = models.DateTimeField(null=True, blank=True) def __unicode__(self): return self.camera.__unicode__() + ' > ' + self.command
from django.db import models class Camera(models.Model): ssid = models.CharField(max_length=255) password = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) last_attempt = models.DateTimeField(auto_now=True) last_update = models.DateTimeField(null=True, blank=True) image_last_update = models.DateTimeField(null=True, blank=True) image = models.TextField(blank=True) summary = models.TextField(blank=True) status = models.TextField(blank=True) connection_attempts = models.IntegerField(default=0) connection_failures = models.IntegerField(default=0) def __unicode__(self): return self.ssid class Command(models.Model): camera = models.ForeignKey(Camera) command = models.CharField(max_length=255) value = models.CharField(max_length=255) date_added = models.DateTimeField(auto_now_add=True) time_completed = models.DateTimeField(null=True, blank=True) def __unicode__(self): return self.camera.__unicode__() + ' > ' + self.command
Remove link for documentation on list view
<?php include 'header_meta_inc_view.php';?> <?php include 'header_inc_view.php';?> <?php include 'office_table_inc_view.php';?> <div class="container"> <!-- Example row of columns --> <div class="row"> <div> <h2>Agencies</h2> <?php if(!empty($cfo_offices)) { status_table('CFO Act Agencies', $cfo_offices); } if(!empty($executive_offices)) { status_table('Other Offices Reporting to the White House', $executive_offices); } if(!empty($independent_offices)) { status_table('Other Independent Offices', $independent_offices); } ?> </div> </div> <hr> <?php include 'footer.php'; ?>
<?php include 'header_meta_inc_view.php';?> <?php include 'header_inc_view.php';?> <?php include 'office_table_inc_view.php';?> <div class="container"> <!-- Example row of columns --> <div class="row"> <div> <h2>Agencies</h2> <p> See the <a href="/docs">documentation</a> for an explanation of this table. </p> <?php if(!empty($cfo_offices)) { status_table('CFO Act Agencies', $cfo_offices); } if(!empty($executive_offices)) { status_table('Other Offices Reporting to the White House', $executive_offices); } if(!empty($independent_offices)) { status_table('Other Independent Offices', $independent_offices); } ?> </div> </div> <hr> <?php include 'footer.php'; ?>
Throw exception if packet id is wrong
package protocolsupport.protocol.core.initial; import io.netty.buffer.ByteBuf; import io.netty.handler.codec.DecoderException; import protocolsupport.api.ProtocolVersion; import protocolsupport.utils.netty.ChannelUtils; public class ProtocolUtils { protected static ProtocolVersion get16PingVersion(int protocolId) { switch (protocolId) { case 78: { return ProtocolVersion.MINECRAFT_1_6_4; } case 74: { return ProtocolVersion.MINECRAFT_1_6_2; } case 73: { return ProtocolVersion.MINECRAFT_1_6_1; } default: { return ProtocolVersion.MINECRAFT_1_6_4; } } } @SuppressWarnings("deprecation") protected static ProtocolVersion readOldHandshake(ByteBuf data) { ProtocolVersion version = ProtocolVersion.fromId(data.readUnsignedByte()); return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_LEGACY; } @SuppressWarnings("deprecation") protected static ProtocolVersion readNettyHandshake(ByteBuf data) { int packetId = ChannelUtils.readVarInt(data); if (packetId == 0x00) { ProtocolVersion version = ProtocolVersion.fromId(ChannelUtils.readVarInt(data)); return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_FUTURE; } else { throw new DecoderException(packetId + "is not a valid packet id"); } } }
package protocolsupport.protocol.core.initial; import io.netty.buffer.ByteBuf; import protocolsupport.api.ProtocolVersion; import protocolsupport.utils.netty.ChannelUtils; public class ProtocolUtils { protected static ProtocolVersion get16PingVersion(int protocolId) { switch (protocolId) { case 78: { return ProtocolVersion.MINECRAFT_1_6_4; } case 74: { return ProtocolVersion.MINECRAFT_1_6_2; } case 73: { return ProtocolVersion.MINECRAFT_1_6_1; } default: { return ProtocolVersion.MINECRAFT_1_6_4; } } } @SuppressWarnings("deprecation") protected static ProtocolVersion readOldHandshake(ByteBuf data) { ProtocolVersion version = ProtocolVersion.fromId(data.readUnsignedByte()); return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_LEGACY; } @SuppressWarnings("deprecation") protected static ProtocolVersion readNettyHandshake(ByteBuf data) { if (ChannelUtils.readVarInt(data) == 0x00) { ProtocolVersion version = ProtocolVersion.fromId(ChannelUtils.readVarInt(data)); return version != ProtocolVersion.UNKNOWN ? version : ProtocolVersion.MINECRAFT_FUTURE; } return null; } }
Add return type-hint for sanity
<?php namespace Spotman\Api; abstract class AbstractMethodsCollectionApiResource extends AbstractApiResource implements ApiMethodsCollectionInterface { /** * @var \Spotman\Api\API */ protected $api; /** * AbstractMethodsCollectionApiResource constructor. * * @param \Spotman\Api\API $api */ public function __construct(API $api) { $this->api = $api; } /** * Allow magic calls * * @param string $name * @param array $arguments * * @return \Spotman\Api\ApiMethodResponse */ final public function __call($name, array $arguments) { return $this->call($name, $arguments); } /** * Manually call ApiMethod from MethodsCollection method-helper * * @param string $name * @param array $arguments * * @return \Spotman\Api\ApiMethodResponse */ protected function call($name, array $arguments): ApiMethodResponse { // Forward call to API subsystem return $this->api->get($this->getName())->call($name, $arguments); } }
<?php namespace Spotman\Api; abstract class AbstractMethodsCollectionApiResource extends AbstractApiResource implements ApiMethodsCollectionInterface { /** * @var \Spotman\Api\API */ protected $api; /** * AbstractMethodsCollectionApiResource constructor. * * @param \Spotman\Api\API $api */ public function __construct(API $api) { $this->api = $api; } /** * Allow magic calls * * @param string $name * @param array $arguments * * @return \Spotman\Api\ApiMethodResponse */ final public function __call($name, array $arguments) { return $this->call($name, $arguments); } /** * Manually call ApiMethod from MethodsCollection method-helper * * @param string $name * @param array $arguments * * @return \Spotman\Api\ApiMethodResponse */ protected function call($name, array $arguments) { // Forward call to API subsystem return $this->api->get($this->getName())->call($name, $arguments); } }