text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Move dependencies into their own bundle to improve caching
var path = require('path') module.exports = { entry: { app: './src/main.js', vendors: [ 'vue', 'vue-resource', 'vue-router', ], }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.vue'], alias: { 'src': path.resolve(__dirname, '../src'), } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.vue$/, loader: 'vue', }, { test: /\.js$/, loader: 'babel', // babel!eslint exclude: /node_modules/, }, { test: /\.json$/, loader: 'json', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url', query: { limit: 10000, name: '[name].[ext]?[hash:7]', }, }, ], }, vue: { loaders: { js: 'babel', // babel!eslint }, }, // eslint: { // formatter: require('eslint-friendly-formatter'), // }, };
var path = require('path') module.exports = { entry: { app: './src/main.js', }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.vue'], alias: { 'src': path.resolve(__dirname, '../src'), } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.vue$/, loader: 'vue', }, { test: /\.js$/, loader: 'babel', // babel!eslint exclude: /node_modules/, }, { test: /\.json$/, loader: 'json', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url', query: { limit: 10000, name: '[name].[ext]?[hash:7]', }, }, ], }, vue: { loaders: { js: 'babel', // babel!eslint }, }, // eslint: { // formatter: require('eslint-friendly-formatter'), // }, };
[AllBundles] Fix doctrine common deprecations and resolve doctrine bundle v2 incompatibility
<?php namespace Kunstmaan\PagePartBundle\Tests\Form; use Kunstmaan\NodeBundle\Form\Type\URLChooserType; use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Forms; use Symfony\Component\OptionsResolver\OptionsResolver; /** * PagePartAdminTypeTestCase */ class PagePartAdminTypeTestCase extends WebTestCase { /** * @var FormBuilder */ protected $builder; /** * @var EventDispatcher */ protected $dispatcher; /** * @var \Symfony\Component\Form\FormFactoryInterface */ protected $factory; /** * @var OptionsResolver */ protected $resolver; protected function setUp(): void { $formFactoryBuilderInterface = Forms::createFormFactoryBuilder(); $formFactoryBuilderInterface->addType(new URLChooserType()); $formFactoryBuilderInterface->addTypeGuesser(new DoctrineOrmTypeGuesser($this->createMock('Doctrine\Persistence\ManagerRegistry'))); $this->factory = $formFactoryBuilderInterface->getFormFactory(); $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory); $this->resolver = new OptionsResolver(); } }
<?php namespace Kunstmaan\PagePartBundle\Tests\Form; use Kunstmaan\NodeBundle\Form\Type\URLChooserType; use Symfony\Bridge\Doctrine\Form\DoctrineOrmTypeGuesser; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Forms; use Symfony\Component\OptionsResolver\OptionsResolver; /** * PagePartAdminTypeTestCase */ class PagePartAdminTypeTestCase extends WebTestCase { /** * @var FormBuilder */ protected $builder; /** * @var EventDispatcher */ protected $dispatcher; /** * @var \Symfony\Component\Form\FormFactoryInterface */ protected $factory; /** * @var OptionsResolver */ protected $resolver; protected function setUp(): void { $formFactoryBuilderInterface = Forms::createFormFactoryBuilder(); $formFactoryBuilderInterface->addType(new URLChooserType()); $formFactoryBuilderInterface->addTypeGuesser(new DoctrineOrmTypeGuesser($this->createMock('Doctrine\Common\Persistence\ManagerRegistry'))); $this->factory = $formFactoryBuilderInterface->getFormFactory(); $this->dispatcher = $this->createMock('Symfony\Component\EventDispatcher\EventDispatcherInterface'); $this->builder = new FormBuilder(null, null, $this->dispatcher, $this->factory); $this->resolver = new OptionsResolver(); } }
ecs: Use `instanceof` checks when retrieving components.
/* exported withEntity */ function withEntity(Class) { return class WithEntity extends Class { constructor(...args) { super(...args); this.components = []; } addComponent(...components) { components.forEach(component => { if (this.hasComponent(component)) { return; } component.parent = this; this.components.push(component); }); return this; } hasComponent(component) { return this.components.includes(component); } getComponent(Type) { return this.components.find(component => component instanceof Type); } getComponents(Type) { return this.components.filter(component => component instanceof Type); } removeComponent(...components) { components.forEach(component => { const index = this.components.indexOf(component); if (index >= 0) { this.components .splice(index, 1) .forEach(component => (component.parent = undefined)); } }); return this; } fixedUpdate(...args) { this.components.forEach(component => component.fixedUpdate(...args)); } update(...args) { this.components.forEach(component => component.update(...args)); } }; }
/* exported withEntity */ function withEntity(Class) { return class WithEntity extends Class { constructor(...args) { super(...args); this.components = []; } addComponent(...components) { components.forEach(component => { if (this.hasComponent(component)) { return; } component.parent = this; this.components.push(component); }); return this; } hasComponent(component) { return this.components.includes(component); } getComponent(type) { return this.components.find(component => component.type === type); } getComponents(type) { return this.components.filter(component => component.type === type); } removeComponent(...components) { components.forEach(component => { const index = this.components.indexOf(component); if (index >= 0) { this.components .splice(index, 1) .forEach(component => (component.parent = undefined)); } }); return this; } fixedUpdate(...args) { this.components.forEach(component => component.fixedUpdate(...args)); } update(...args) { this.components.forEach(component => component.update(...args)); } }; }
Handle sugar rest api version properly.
<?php namespace BisonLab\SugarCrmBundle\Service; /* * Just a service object for the sugar7crm-wrapper class. */ class SugarWrapper { private $sugar; private $options; public function __construct($base_url, $username, $password, $platform = "sugar-wrapper") { if (!preg_match("/rest\/v[\d_]+/", $base_url)) { $base_url .= '/rest/v11_5/'; } $this->options = [ 'base_url' => $base_url, 'username' => $username, 'password' => $password, 'platform' => $platform ]; } public function getSugar() { if (!$this->sugar) $this->connectSugar(); return $this->sugar; } public function connectSugar() { $this->sugar = new \Spinegar\SugarRestClient\Rest(); $this->sugar ->setUrl($this->options['base_url']) ->setUsername($this->options['username']) ->setPassword($this->options['password']) ->setPlatform($this->options['platform']) ; } }
<?php namespace BisonLab\SugarCrmBundle\Service; /* * Just a service object for the sugar7crm-wrapper class. */ class SugarWrapper { private $sugar; private $options; public function __construct($base_url, $username, $password, $platform = "sugar-wrapper") { if (!preg_match("/rest\/v\d\d/", $base_url)) { $base_url .= '/rest/v11_5/'; } $this->options = [ 'base_url' => $base_url, 'username' => $username, 'password' => $password, 'platform' => $platform ]; } public function getSugar() { if (!$this->sugar) $this->connectSugar(); return $this->sugar; } public function connectSugar() { $this->sugar = new \Spinegar\SugarRestClient\Rest(); $this->sugar ->setUrl($this->options['base_url']) ->setUsername($this->options['username']) ->setPassword($this->options['password']) ->setPlatform($this->options['platform']) ; } }
Allow for URI with already existing query string
<?php namespace Laravel\Passport\Http\Controllers; use Illuminate\Support\Arr; use Illuminate\Http\Request; use Illuminate\Contracts\Routing\ResponseFactory; class DenyAuthorizationController { use RetrievesAuthRequestFromSession; /** * The response factory implementation. * * @var \Illuminate\Contracts\Routing\ResponseFactory */ protected $response; /** * Create a new controller instance. * * @param \Illuminate\Contracts\Routing\ResponseFactory $response * @return void */ public function __construct(ResponseFactory $response) { $this->response = $response; } /** * Deny the authorization request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse */ public function deny(Request $request) { $authRequest = $this->getAuthRequestFromSession($request); $clientUris = Arr::wrap($authRequest->getClient()->getRedirectUri()); if (! in_array($uri = $authRequest->getRedirectUri(), $clientUris)) { $uri = Arr::first($clientUris); } $separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : (strstr($uri,'?') ? '&' : '?'); return $this->response->redirectTo( $uri.$separator.'error=access_denied&state='.$request->input('state') ); } }
<?php namespace Laravel\Passport\Http\Controllers; use Illuminate\Support\Arr; use Illuminate\Http\Request; use Illuminate\Contracts\Routing\ResponseFactory; class DenyAuthorizationController { use RetrievesAuthRequestFromSession; /** * The response factory implementation. * * @var \Illuminate\Contracts\Routing\ResponseFactory */ protected $response; /** * Create a new controller instance. * * @param \Illuminate\Contracts\Routing\ResponseFactory $response * @return void */ public function __construct(ResponseFactory $response) { $this->response = $response; } /** * Deny the authorization request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse */ public function deny(Request $request) { $authRequest = $this->getAuthRequestFromSession($request); $clientUris = Arr::wrap($authRequest->getClient()->getRedirectUri()); if (! in_array($uri = $authRequest->getRedirectUri(), $clientUris)) { $uri = Arr::first($clientUris); } $separator = $authRequest->getGrantTypeId() === 'implicit' ? '#' : '?'; return $this->response->redirectTo( $uri.$separator.'error=access_denied&state='.$request->input('state') ); } }
Create person with last seen
var MissingPerson = require('../../app/models/missingPerson'); exports.create = function (req, res) { var firstname = req.body.firstname; var surname = req.body.surname; var missingPerson = new MissingPerson(); if (firstname) { missingPerson.forenames = firstname; } if (surname) { missingPerson.surname = surname; } missingPerson.gender = 'M'; missingPerson.status = 'Missing'; missingPerson.category = 'Missing'; missingPerson.birthYear = req.body.birthYear; missingPerson.borough = req.body.town; missingPerson.latitude = req.body.latitude; missingPerson.longitude = req.body.longitude; missingPerson.wentMissing = new Date(); missingPerson.created = new Date(); missingPerson.updated = new Date(); missingPerson.id = generateGUID(); var lastSeen = {}; lastSeen.date = new Date(); lastSeen.longitude = req.body.longitude; lastSeen.latitude = req.body.latitude; lastSeen.accountId = req.body.accountId; lastSeen.description = ''; missingPerson.lastSeen.push(lastSeen); missingPerson.save(function (err) { if (err) { console.log(err); res.json({ message: 'Error' }); } else { res.json(missingPerson); } }); } generateGUID = function() { var _sym = 'ABCDEF1234567890'; var str = ''; var count = 20; for (var i = 0; i < count; i++) { str += _sym[parseInt(Math.random() * (_sym.length))]; } return str; }
var MissingPerson = require('../../app/models/missingPerson'); exports.create = function (req, res) { var firstname = req.body.firstname; var surname = req.body.surname; var missingPerson = new MissingPerson(); if (firstname) { missingPerson.forenames = firstname; } if (surname) { missingPerson.surname = surname; } missingPerson.gender = 'M'; missingPerson.status = 'Missing'; missingPerson.category = 'Missing'; missingPerson.birthYear = req.body.birthYear; missingPerson.borough = req.body.town; missingPerson.latitude = req.body.latitude; missingPerson.longitude = req.body.longitude; missingPerson.wentMissing = new Date(); missingPerson.created = new Date(); missingPerson.updated = new Date(); missingPerson.id = generateGUID(); missingPerson.save(function (err) { if (err) { console.log(err); res.json({ message: 'Error' }); } else { res.json(missingPerson); } }); } generateGUID = function() { var _sym = 'ABCDEF1234567890'; var str = ''; var count = 20; for (var i = 0; i < count; i++) { str += _sym[parseInt(Math.random() * (_sym.length))]; } return str; }
Test login with valid credentials
"use strict"; describe('Login component', () => { let element = undefined; let $rootScope = undefined; let $compile = undefined; let mod = angular.module('tests.login', []).service('Authentication', function () { this.check = false; this.attempt = credentials => { if (credentials.username == 'test' && credentials.password == 'test') { this.check = true; } }; this.status = () => this.check; }); beforeEach(angular.mock.module(mod.name)); beforeEach(inject((_$rootScope_, _$compile_) => { $rootScope = _$rootScope_; $compile = _$compile_; })); describe('Not logged in', () => { it('should show the login form prior to authentication', () => { let tpl = angular.element(` <monad-login> <h1>logged in</h1> </monad-login> `); element = $compile(tpl)($rootScope); $rootScope.$digest(); expect(element.find('form').length).toBe(1); }); }); describe('Logged in', () => { it('should display a h1', () => { let tpl = angular.element(` <monad-login> <h1>logged in</h1> </monad-login> `); element = $compile(tpl)($rootScope); $rootScope.$digest(); element.find('input').eq(0).val('test').triggerHandler('input'); element.find('input').eq(1).val('test').triggerHandler('input'); element.find('form').triggerHandler('submit'); expect(element.find('h1').length).toBe(1); }); }); });
"use strict"; describe('Login component', () => { let element = undefined; let $rootScope = undefined; let $compile = undefined; let tpl = angular.element(` <monad-login> <h1>logged in</h1> </monad-login> `); let mod = angular.module('tests.login', []).service('Authentication', function () { this.check = false; this.attempt = credentials => { if (credentials.username == 'test' && credentials.password == 'test') { this.check = true; } }; this.status = () => this.check; }); beforeEach(angular.mock.module(mod.name)); beforeEach(inject((_$rootScope_, _$compile_) => { $rootScope = _$rootScope_; $compile = _$compile_; })); describe('Not logged in', () => { it('should show the login form prior to authentication', () => { $rootScope.$apply(() => { $rootScope.credentials = {}; }); element = $compile(tpl)($rootScope); $rootScope.$digest(); expect(element.find('form').length).toBe(1); }); }); });
Fix for using NAG Fortran 95, due to James Graham <[email protected]> git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@2515 94b884b6-d6fd-0310-90d3-974f1d3f35e1
import os import sys from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler class NAGFCompiler(FCompiler): compiler_type = 'nag' version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)' executables = { 'version_cmd' : ["f95", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : ["f95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,-shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return ['-target=native'] def get_flags_debug(self): return ['-g','-gline','-g90','-nan','-C'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='nag') compiler.customize() print compiler.get_version()
import os import sys from numpy.distutils.cpuinfo import cpu from numpy.distutils.fcompiler import FCompiler class NAGFCompiler(FCompiler): compiler_type = 'nag' version_pattern = r'NAGWare Fortran 95 compiler Release (?P<version>[^\s]*)' executables = { 'version_cmd' : ["f95", "-V"], 'compiler_f77' : ["f95", "-fixed"], 'compiler_fix' : ["f95", "-fixed"], 'compiler_f90' : ["f95"], 'linker_so' : ["f95"], 'archiver' : ["ar", "-cr"], 'ranlib' : ["ranlib"] } def get_flags_linker_so(self): if sys.platform=='darwin': return ['-unsharedf95','-Wl,-bundle,-flat_namespace,-undefined,suppress'] return ["-Wl,shared"] def get_flags_opt(self): return ['-O4'] def get_flags_arch(self): return ['-target=native'] def get_flags_debug(self): return ['-g','-gline','-g90','-nan','-C'] if __name__ == '__main__': from distutils import log log.set_verbosity(2) from numpy.distutils.fcompiler import new_fcompiler compiler = new_fcompiler(compiler='nag') compiler.customize() print compiler.get_version()
Allow absolute path on twig getPath function
<?php namespace Victoire\Bundle\CoreBundle\Twig\Extension; use Symfony\Bridge\Twig\Extension\RoutingExtension; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Victoire\Bundle\PageBundle\Helper\PageHelper; /** * class RoutingExtension */ class RoutingExtention extends RoutingExtension { private $pageHelper; private $generator; public function __construct(PageHelper $pageHelper, UrlGeneratorInterface $generator) { $this->pageHelper = $pageHelper; $this->generator = $generator; parent::__construct($generator); } public function getPath($name, $parameters = array(), $relative = false) { if ($name == 'victoire_core_page_show_by_id') { $params = array('viewId' => $parameters['viewId']); unset($parameters['viewId']); if (!empty($parameters['entityId'])) { $params['entityId'] = $parameters['entityId']; unset($parameters['entityId']); } $page = $this->pageHelper->findPageByParameters($params); $parameters['url'] = $page->getUrl(); $name = 'victoire_core_page_show'; } return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::ABSOLUTE_PATH : UrlGeneratorInterface::ABSOLUTE_URL); } }
<?php namespace Victoire\Bundle\CoreBundle\Twig\Extension; use Symfony\Bridge\Twig\Extension\RoutingExtension; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; use Victoire\Bundle\PageBundle\Helper\PageHelper; /** * class RoutingExtension */ class RoutingExtention extends RoutingExtension { private $pageHelper; private $generator; public function __construct(PageHelper $pageHelper, UrlGeneratorInterface $generator) { $this->pageHelper = $pageHelper; $this->generator = $generator; parent::__construct($generator); } public function getPath($name, $parameters = array(), $relative = false) { if ($name == 'victoire_core_page_show_by_id') { $params = array('viewId' => $parameters['viewId']); unset($parameters['viewId']); if (!empty($parameters['entityId'])) { $params['entityId'] = $parameters['entityId']; unset($parameters['entityId']); } $page = $this->pageHelper->findPageByParameters($params); $parameters['url'] = $page->getUrl(); return $this->generator->generate('victoire_core_page_show', $parameters); } return $this->generator->generate($name, $parameters, $relative ? UrlGeneratorInterface::RELATIVE_PATH : UrlGeneratorInterface::ABSOLUTE_PATH); } }
Bump the version number - 0.2.0-dev. Signed-off-by: Lewis Gunsch <[email protected]>
import os from distutils.core import setup VERSION = '0.2.0-dev' README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() required = [ 'Django >= 1.5.0', ] setup( name='madmin', version=VERSION, description="Virtual mail administration django app", author="Lewis Gunsch", author_email="[email protected]", url="https://github.com/lgunsch/madmin", license='MIT', long_description=README, packages=[ 'madmin', 'madmin.management', 'madmin.management.commands', 'madmin.migrations', 'madmin.tests', ], scripts=[], install_requires=required, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Communications :: Email', 'Topic :: Communications :: Email :: Mail Transport Agents', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
import os from distutils.core import setup VERSION = '0.1.0' README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read() required = [ 'Django >= 1.5.0', ] setup( name='madmin', version=VERSION, description="Virtual mail administration django app", author="Lewis Gunsch", author_email="[email protected]", url="https://github.com/lgunsch/madmin", license='MIT', long_description=README, packages=[ 'madmin', 'madmin.management', 'madmin.management.commands', 'madmin.migrations', 'madmin.tests', ], scripts=[], install_requires=required, include_package_data=True, classifiers=[ 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Topic :: Communications :: Email', 'Topic :: Communications :: Email :: Mail Transport Agents', 'Topic :: Internet :: WWW/HTTP', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], )
Make jshint happy with new bind polyfill
if ( ! Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target !== "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = Array.prototype.slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(Array.prototype.slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(Array.prototype.slice.call(arguments)) ); } }; if(target.prototype) { var Empty = function() {}; empty.prototype = target.prototype; bound.prototype = new Empty(); } return bound; }; }
if ( ! Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = Array.prototype.slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(Array.prototype.slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(Array.prototype.slice.call(arguments)) ); } }; if(target.prototype) { var empty = function() { } empty.prototype = target.prototype; bound.prototype = new empty(); } return bound; }; }
Use the cool new array syntax
<?php namespace STS\Tunneler; use Illuminate\Support\ServiceProvider; use STS\Tunneler\Console\TunnelerCommand; use STS\Tunneler\Jobs\CreateTunnel; class TunnelerServiceProvider extends ServiceProvider{ /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Default path to configuration * @var string */ protected $configPath = __DIR__ . '/../config/tunneler.php'; public function boot() { // helps deal with Lumen vs Laravel differences if (function_exists('config_path')) { $publishPath = config_path('tunneler.php'); } else { $publishPath = base_path('config/tunneler.php'); } $this->publishes([$this->configPath => $publishPath], 'config'); if (config('tunneler.on_boot')){ dispatch(new CreateTunnel()); } } public function register() { if ( is_a($this->app,'Laravel\Lumen\Application')){ $this->app->configure('tunneler'); } $this->mergeConfigFrom($this->configPath, 'tunneler'); $this->app->singleton('command.tunneler.activate', function ($app) { return new TunnelerCommand(); } ); $this->commands('command.tunneler.activate'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return ['command.tunneler.activate']; } }
<?php namespace STS\Tunneler; use Illuminate\Support\ServiceProvider; use STS\Tunneler\Console\TunnelerCommand; use STS\Tunneler\Jobs\CreateTunnel; class TunnelerServiceProvider extends ServiceProvider{ /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = false; /** * Default path to configuration * @var string */ protected $configPath = __DIR__ . '/../config/tunneler.php'; public function boot() { // helps deal with Lumen vs Laravel differences if (function_exists('config_path')) { $publishPath = config_path('tunneler.php'); } else { $publishPath = base_path('config/tunneler.php'); } $this->publishes([$this->configPath => $publishPath], 'config'); if (config('tunneler.on_boot')){ dispatch(new CreateTunnel()); } } public function register() { if ( is_a($this->app,'Laravel\Lumen\Application')){ $this->app->configure('tunneler'); } $this->mergeConfigFrom($this->configPath, 'tunneler'); $this->app->singleton('command.tunneler.activate', function ($app) { return new TunnelerCommand(); } ); $this->commands('command.tunneler.activate'); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('command.tunneler.activate'); } }
Fix a bug in redis queue
# -*- coding: utf-8 -*- import redis class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self, name, namespace='queue', **redis_kwargs): """The default connection parameters are: host='localhost', port=6379, db=0""" self.db = redis.Redis(**redis_kwargs) self.key = '%s:%s' %(namespace, name) def qsize(self): """Return the approximate size of the queue.""" return self.db.llen(self.key) def empty(self): """Return True if the queue is empty, False otherwise.""" return self.qsize() == 0 def put(self, item): """Put item into the queue.""" self.db.rpush(self.key, item) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.""" if block: item = self.db.blpop(self.key, timeout=timeout) if item: item = item[1] else: item = self.db.lpop(self.key) return item def get_nowait(self): """Equivalent to get(False).""" return self.get(False) def __iter__(self): return self def next(self): item = self.get(False) if item is None: raise StopIteration return item
# -*- coding: utf-8 -*- import redis class RedisQueue(object): """Simple Queue with Redis Backend""" def __init__(self, name, namespace='queue', **redis_kwargs): """The default connection parameters are: host='localhost', port=6379, db=0""" self.db = redis.Redis(**redis_kwargs) self.key = '%s:%s' %(namespace, name) def qsize(self): """Return the approximate size of the queue.""" return self.db.llen(self.key) def empty(self): """Return True if the queue is empty, False otherwise.""" return self.qsize() == 0 def put(self, item): """Put item into the queue.""" self.db.rpush(self.key, item) def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available.""" if block: item = self.db.blpop(self.key, timeout=timeout) else: item = self.db.lpop(self.key) if item: item = item[1] return item def get_nowait(self): """Equivalent to get(False).""" return self.get(False) def __iter__(self): return self def next(self): item = self.get(False) if item is None: raise StopIteration return item
Check gamerule before translating formattings
package com.ptsmods.morecommands.commands.server.elevated; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.ptsmods.morecommands.MoreCommands; import com.ptsmods.morecommands.miscellaneous.Command; import com.ptsmods.morecommands.miscellaneous.MoreGameRules; import net.minecraft.item.ItemStack; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.util.Formatting; public class RenameCommand extends Command { @Override public void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literalReqOp("rename") .then(argument("name", StringArgumentType.greedyString()) .executes(ctx -> { ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack(); if (stack.isEmpty()) sendError(ctx, "You are not holding an item."); else { String nameRaw = ctx.getArgument("name", String.class); String name = MoreGameRules.get().checkBooleanWithPerm(ctx.getSource().getWorld().getGameRules(), MoreGameRules.get().doItemColoursRule(), ctx.getSource().getEntity()) ? MoreCommands.translateFormattings(nameRaw) : nameRaw; stack.setCustomName(literalText(name).build()); sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + "."); return 1; } return 0; }))); } @Override public String getDocsPath() { return "/elevated/rename"; } }
package com.ptsmods.morecommands.commands.server.elevated; import com.mojang.brigadier.CommandDispatcher; import com.mojang.brigadier.arguments.StringArgumentType; import com.ptsmods.morecommands.MoreCommands; import com.ptsmods.morecommands.miscellaneous.Command; import net.minecraft.item.ItemStack; import net.minecraft.server.command.ServerCommandSource; import net.minecraft.util.Formatting; public class RenameCommand extends Command { @Override public void register(CommandDispatcher<ServerCommandSource> dispatcher) { dispatcher.register(literalReqOp("rename") .then(argument("name", StringArgumentType.greedyString()) .executes(ctx -> { ItemStack stack = ctx.getSource().getPlayerOrThrow().getMainHandStack(); if (stack.isEmpty()) sendError(ctx, "You are not holding an item."); else { String name = MoreCommands.translateFormattings(ctx.getArgument("name", String.class)); stack.setCustomName(literalText(name).build()); sendMsg(ctx, "The item has been renamed to " + name + Formatting.RESET + "."); return 1; } return 0; }))); } @Override public String getDocsPath() { return "/elevated/rename"; } }
Add boleta xml generator tests
<?php /** * Created by PhpStorm. * User: Giansalex * Date: 16/07/2017 * Time: 22:54 */ declare(strict_types=1); namespace Tests\Greenter\Xml\Builder; use Greenter\Data\Generator\BoletaStore; use Greenter\Data\Generator\InvoiceFullStore; use Greenter\Data\Generator\InvoiceStore; use Greenter\Model\Sale\Invoice; use PHPUnit\Framework\TestCase; /** * Class FeInvoiceBuilderTest * @package Tests\Greenter\Xml\Builder */ class FeInvoiceBuilderTest extends TestCase { use FeBuilderTrait; use XsdValidatorTrait; public function testCreateXmlInvoice() { $invoice = $this->createDocument(InvoiceFullStore::class); $xml = $this->build($invoice); $this->assertNotEmpty($xml); $this->assertSchema($xml); } public function testInvoiceFilename() { /**@var $invoice Invoice*/ $invoice = $this->createDocument(InvoiceStore::class); $filename = $invoice->getName(); $this->assertEquals($this->getFilename($invoice), $filename); } public function testCreateXmlBoleta() { $invoice = $this->createDocument(BoletaStore::class); $xml = $this->build($invoice); $this->assertNotEmpty($xml); $this->assertSchema($xml); } private function getFileName(Invoice $invoice) { $parts = [ $invoice->getCompany()->getRuc(), $invoice->getTipoDoc(), $invoice->getSerie(), $invoice->getCorrelativo(), ]; return join('-', $parts); } }
<?php /** * Created by PhpStorm. * User: Giansalex * Date: 16/07/2017 * Time: 22:54 */ declare(strict_types=1); namespace Tests\Greenter\Xml\Builder; use Greenter\Data\Generator\InvoiceFullStore; use Greenter\Data\Generator\InvoiceStore; use Greenter\Model\Sale\Invoice; use PHPUnit\Framework\TestCase; /** * Class FeInvoiceBuilderTest * @package Tests\Greenter\Xml\Builder */ class FeInvoiceBuilderTest extends TestCase { use FeBuilderTrait; use XsdValidatorTrait; public function testCreateXmlInvoice() { $invoice = $this->createDocument(InvoiceFullStore::class); $xml = $this->build($invoice); $this->assertNotEmpty($xml); $this->assertSchema($xml); } public function testInvoiceFilename() { /**@var $invoice Invoice*/ $invoice = $this->createDocument(InvoiceStore::class); $filename = $invoice->getName(); $this->assertEquals($this->getFilename($invoice), $filename); } private function getFileName(Invoice $invoice) { $parts = [ $invoice->getCompany()->getRuc(), $invoice->getTipoDoc(), $invoice->getSerie(), $invoice->getCorrelativo(), ]; return join('-', $parts); } }
Save and restore state of view on attach to presenter
package com.neoranga55.androidconfchangeloaders.presenters; /** * Created by neoranga on 28/03/2016. */ public class DemoPresenter implements DemoContract.UserActions<DemoContract.ViewActions> { private DemoContract.ViewActions mViewActions; private Thread mSlowTask; private boolean isLoading; private boolean isContentLoaded; private boolean isLoadCancelled; @Override public void onViewAttached(DemoContract.ViewActions viewActions) { mViewActions = viewActions; if (isLoading) { mViewActions.showLoading(); } if (isContentLoaded) { mViewActions.showContentLoaded(); } if (isLoadCancelled) { mViewActions.showCancelledRequest(); } } @Override public void onViewDetached() { mViewActions = null; } @Override public void onDestroyed() { // Nothing to clean up } @Override public void loadButtonPressed() { isLoading = true; isContentLoaded = false; isLoadCancelled = false; mViewActions.showLoading(); mSlowTask = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); isLoading = false; isContentLoaded = true; mViewActions.showContentLoaded(); mSlowTask = null; } catch (InterruptedException ignored) { } } }); mSlowTask.start(); } @Override public void cancelButtonPressed() { isLoading = false; if (mSlowTask != null) { isLoadCancelled = true; isContentLoaded = false; mSlowTask.interrupt(); mSlowTask = null; mViewActions.showCancelledRequest(); } } }
package com.neoranga55.androidconfchangeloaders.presenters; import android.os.AsyncTask; /** * Created by neoranga on 28/03/2016. */ public class DemoPresenter implements DemoContract.UserActions<DemoContract.ViewActions> { private DemoContract.ViewActions mViewActions; private Thread mSlowTask; @Override public void onViewAttached(DemoContract.ViewActions viewActions) { mViewActions = viewActions; } @Override public void onViewDetached() { mViewActions = null; } @Override public void onDestroyed() { // Nothing to clean up } @Override public void loadButtonPressed() { mViewActions.showLoading(); mSlowTask = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(30000); mViewActions.showContentLoaded(); } catch (InterruptedException ignored) { } } }); mSlowTask.start(); } @Override public void cancelButtonPressed() { if (mSlowTask != null) { mSlowTask.interrupt(); } mViewActions.showCancelledRequest(); } }
Enlarge the waiting before start count down
'use strict'; (function () { angular .module('dailyMummApp') .controller('NavbarDirectiveCtrl', NavbarDirectiveController); NavbarDirectiveController.$inject = ['$scope', 'AuthService', '$state', '$timeout', 'CountDownService', 'CurrentOrderService']; function NavbarDirectiveController($scope, AuthService, $state, $timeout, CountDownService, CurrentOrderService) { $scope.logout = logout; $scope.orderStarted = false; $scope.currentUsername = ""; if (AuthService.isLoggedIn()) { $scope.currentUsername = (AuthService.getCurrentUserInfo()).username; } if (CurrentOrderService.orderData && CurrentOrderService.orderData.startTime) { console.log(CurrentOrderService.orderData.startTime); $scope.orderStarted = true; CountDownService.initializeClock("count-down", new Date(Date.parse(CurrentOrderService.orderData.startTime) + 30 * 60 * 1000)) } function logout() { AuthService.clearCredintials(); $state.go('home'); } $scope.$on('orderStarted', function () { $timeout(function () { $scope.orderStarted = true; CountDownService.initializeClock("count-down", new Date(Date.parse(CurrentOrderService.orderData.startTime) + 30 * 60 * 1000)) }, 500); }); } })();
'use strict'; (function () { angular .module('dailyMummApp') .controller('NavbarDirectiveCtrl', NavbarDirectiveController); NavbarDirectiveController.$inject = ['$scope', 'AuthService', '$state', '$timeout', 'CountDownService', 'CurrentOrderService']; function NavbarDirectiveController($scope, AuthService, $state, $timeout, CountDownService, CurrentOrderService) { $scope.logout = logout; $scope.orderStarted = false; $scope.currentUsername = ""; if (AuthService.isLoggedIn()) { $scope.currentUsername = (AuthService.getCurrentUserInfo()).username; } if (CurrentOrderService.orderData && CurrentOrderService.orderData.startTime) { debugger console.log(CurrentOrderService.orderData.startTime); $scope.orderStarted = true; CountDownService.initializeClock("count-down", new Date(Date.parse(CurrentOrderService.orderData.startTime) + 30 * 60 * 1000)) } function logout() { AuthService.clearCredintials(); $state.go('home'); } $scope.$on('orderStarted', function () { $timeout(function () { $scope.orderStarted = true; CountDownService.initializeClock("count-down", new Date(Date.parse(CurrentOrderService.orderData.startTime) + 30 * 60 * 1000)) }, 300); }); } })();
Return title numbers in disc and track order, increment disc number if duplicated track number
from .BaseIndexEntry import BaseIndexEntry class AlbumIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(AlbumIndexEntry, self).__init__(name, titles, number) self._discs_and_tracks = {} for title in self._titles: # Set the album number on each of the titles title.album_number = self._number # Store titles according to disc and track number # TODO: Cope with more than two discs discnumber = title.discnumber if discnumber not in self._discs_and_tracks: self._discs_and_tracks[discnumber] = {} if title.tracknumber in self._discs_and_tracks[discnumber]: print ("Duplicate track numbers:") print ("\tFirst", title.tracknumber, self._discs_and_tracks[discnumber][title.tracknumber].title) print ("\tSecond", title.tracknumber, title.title) discnumber = title.discnumber + 1 if discnumber not in self._discs_and_tracks: self._discs_and_tracks[discnumber] = {} print ("\tSetting disc number to: {} - you may want to edit the file and set disc number yourself.".format(discnumber)) self._discs_and_tracks[discnumber][title.tracknumber] = title self._freeze() # Getters @property def title_numbers(self): return [self._discs_and_tracks[d][t].index for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])] @property def tracks(self): '''Return titles in album disc and track order''' return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
from .BaseIndexEntry import BaseIndexEntry class AlbumIndexEntry(BaseIndexEntry): def __init__(self, name, titles, number): super(AlbumIndexEntry, self).__init__(name, titles, number) self._title_numbers = [] self._discs_and_tracks = {} for title in self._titles: # Set the album number on each of the titles title.album_number = self._number # Append the title index to the list self._title_numbers.append(title.index) # Store titles according to disc and track number if title.discnumber not in self._discs_and_tracks: self._discs_and_tracks[title.discnumber] = {} if title.tracknumber in self._discs_and_tracks[title.discnumber]: print ("Duplicate track number", title.tracknumber, title.title) self._discs_and_tracks[title.discnumber][title.tracknumber] = title self._freeze() # Getters @property def title_numbers(self): return self._title_numbers @property def tracks(self): '''Return titles in album disc and track order''' return [self._discs_and_tracks[d][t] for d in sorted(self._discs_and_tracks) for t in sorted(self._discs_and_tracks[d])]
Allow disabling logging when Winston is not being used
var util = require('util'); var levels = [ 'silly', 'input', 'verbose', 'prompt', 'debug', 'http', 'info', 'data', 'help', 'warn', 'error' ]; levels.forEach(function(level) { exports[level] = function(msg) { if (!exports.disabled) { console.log( level + ':', util.format.apply( this, [msg].concat([].slice.call(arguments, 1)))); } }; }); exports.disabled = false; exports.wrap = function(getPrefix, func) { if (typeof getPrefix != 'function') { var msg = getPrefix; getPrefix = function() { return msg; }; } return function() { var args = arguments, that = this, prefix = getPrefix.apply(that, args); wrapper = {}; levels.forEach(function(level) { wrapper[level] = function(msg) { msg = (prefix ? prefix + ': ' : '') + msg; exports[level].apply( this, [msg].concat([].slice.call(arguments, 1))); }; }); return func.apply(that, [wrapper].concat([].slice.call(args))); }; };
var util = require('util'); var levels = [ 'silly', 'input', 'verbose', 'prompt', 'debug', 'http', 'info', 'data', 'help', 'warn', 'error' ]; levels.forEach(function(level) { exports[level] = function(msg) { console.log( level + ':', util.format.apply( this, [msg].concat([].slice.call(arguments, 1)))); }; }); exports.wrap = function(getPrefix, func) { if (typeof getPrefix != 'function') { var msg = getPrefix; getPrefix = function() { return msg; }; } return function() { var args = arguments, that = this, prefix = getPrefix.apply(that, args); wrapper = {}; levels.forEach(function(level) { wrapper[level] = function(msg) { msg = (prefix ? prefix + ': ' : '') + msg; exports[level].apply( this, [msg].concat([].slice.call(arguments, 1))); }; }); return func.apply(that, [wrapper].concat([].slice.call(args))); }; };
Update return value order in normalize_signature docstring [skip ci]
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): """ Return whether *sig* is a potentially valid signature specification (for user-facing APIs). """ return isinstance(sig, (str, tuple, typing.Signature)) def _parse_signature_string(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__) def normalize_signature(sig): """ From *sig* (a signature specification), return a ``(args, return_type)`` tuple, where ``args`` itself is a tuple of types, and ``return_type`` can be None if not specified. """ if isinstance(sig, str): parsed = _parse_signature_string(sig) else: parsed = sig if isinstance(parsed, tuple): args, return_type = parsed, None elif isinstance(parsed, typing.Signature): args, return_type = parsed.args, parsed.return_type else: raise TypeError("invalid signature: %r (type: %r) evaluates to %r " "instead of tuple or Signature" % ( sig, sig.__class__.__name__, parsed.__class__.__name__ )) def check_type(ty): if not isinstance(ty, types.Type): raise TypeError("invalid type in signature: expected a type " "instance, got %r" % (ty,)) if return_type is not None: check_type(return_type) for ty in args: check_type(ty) return args, return_type
from __future__ import print_function, division, absolute_import from numba import types, typing def is_signature(sig): """ Return whether *sig* is a potentially valid signature specification (for user-facing APIs). """ return isinstance(sig, (str, tuple, typing.Signature)) def _parse_signature_string(signature_str): # Just eval signature_str using the types submodules as globals return eval(signature_str, {}, types.__dict__) def normalize_signature(sig): """ From *sig* (a signature specification), return a ``(return_type, args)`` tuple, where ``args`` itself is a tuple of types, and ``return_type`` can be None if not specified. """ if isinstance(sig, str): parsed = _parse_signature_string(sig) else: parsed = sig if isinstance(parsed, tuple): args, return_type = parsed, None elif isinstance(parsed, typing.Signature): args, return_type = parsed.args, parsed.return_type else: raise TypeError("invalid signature: %r (type: %r) evaluates to %r " "instead of tuple or Signature" % ( sig, sig.__class__.__name__, parsed.__class__.__name__ )) def check_type(ty): if not isinstance(ty, types.Type): raise TypeError("invalid type in signature: expected a type " "instance, got %r" % (ty,)) if return_type is not None: check_type(return_type) for ty in args: check_type(ty) return args, return_type
Allow adding new connection from connection picker
import Select from 'antd/lib/select'; import Icon from 'antd/lib/icon'; import React, { useContext, useState } from 'react'; import { ConnectionsContext } from '../connections/ConnectionsStore'; import ConnectionEditDrawer from '../connections/ConnectionEditDrawer'; const { Option } = Select; function ConnectionDropdown() { const connectionsContext = useContext(ConnectionsContext); const [showEdit, setShowEdit] = useState(false); const handleChange = id => { if (id === 'new') { return setShowEdit(true); } connectionsContext.selectConnection(id); }; const handleConnectionSaved = connection => { connectionsContext.addUpdateConnection(connection); connectionsContext.selectConnection(connection._id); setShowEdit(false); }; return ( <> <Select showSearch placeholder="Choose a connection" // TODO className is overridden by antdesign css? // className="w5" style={{ width: 260 }} optionFilterProp="children" value={connectionsContext.selectedConnectionId} onChange={handleChange} filterOption={(input, option) => option.props.value && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > <Option value=""> <em>Choose a connection...</em> </Option> {connectionsContext.connections.map(conn => { return ( <Option key={conn._id} value={conn._id}> {conn.name} </Option> ); })} <Option value="new"> <Icon type="plus-circle" /> <em>New connection</em> </Option> </Select> <ConnectionEditDrawer visible={showEdit} placement="left" onClose={() => setShowEdit(false)} onConnectionSaved={handleConnectionSaved} /> </> ); } export default ConnectionDropdown;
import Select from 'antd/lib/select'; import React from 'react'; import { ConnectionsContext } from '../connections/ConnectionsStore'; const { Option } = Select; function ConnectionDropdown() { return ( <ConnectionsContext.Consumer> {context => ( <Select showSearch placeholder="Choose a connection" // TODO className is overridden by antdesign css? // className="w5" style={{ width: 260 }} optionFilterProp="children" value={context.selectedConnectionId} onChange={id => context.selectConnection(id)} filterOption={(input, option) => option.props.value && option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > <Option value="">Choose a connection...</Option> {context.connections.map(conn => { return ( <Option key={conn._id} value={conn._id}> {conn.name} </Option> ); })} </Select> )} </ConnectionsContext.Consumer> ); } export default ConnectionDropdown;
Remove trailing whitespace in line 31
package seedu.ezdo.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.ezdo.model.todo.StartDate; public class StartDateTest { @Test public void isValidStartDate() { // invalid dates assertFalse(StartDate.isValidTaskDate(" ")); // spaces only assertFalse(StartDate.isValidTaskDate("next")); // non-numeric assertFalse(StartDate.isValidTaskDate("13 12 1999")); // spaces within // digits assertFalse(StartDate.isValidTaskDate("05.10.1977")); // fullstops // within digits assertFalse(StartDate.isValidTaskDate("22/11/q2r1")); // alphabets // within digits // valid dates assertTrue(StartDate.isValidTaskDate("15/12/1992 10:12")); // month with // 31 days assertTrue(StartDate.isValidTaskDate("11/02/2014 07:21")); // month with // 30 days assertTrue(StartDate.isValidTaskDate("29/02/2003 20:21")); // leap year } }
package seedu.ezdo.model.task; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Test; import seedu.ezdo.model.todo.StartDate; public class StartDateTest { @Test public void isValidStartDate() { // invalid dates assertFalse(StartDate.isValidTaskDate(" ")); // spaces only assertFalse(StartDate.isValidTaskDate("next")); // non-numeric assertFalse(StartDate.isValidTaskDate("13 12 1999")); // spaces within // digits assertFalse(StartDate.isValidTaskDate("05.10.1977")); // fullstops // within digits assertFalse(StartDate.isValidTaskDate("22/11/q2r1")); // alphabets // within digits // valid dates assertTrue(StartDate.isValidTaskDate("15/12/1992 10:12")); // month with // 31 days assertTrue(StartDate.isValidTaskDate("11/02/2014 07:21")); // month with // 30 days assertTrue(StartDate.isValidTaskDate("29/02/2003 20:21")); // leap year } }
Check if the cookie exists before accessing it. Little bit of refactoring also.
<?php namespace Hydrarulz\LaravelMixpanel; use Illuminate\Support\Facades\Config; use Mixpanel; class LaravelMixpanel extends Mixpanel { protected $token; private static $_instance; /** * @param array $token * @param array $options */ public function __construct($token, array $options = array()) { $this->setToken($token); self::$_instance = parent::__construct($this->token, $options = array()); } private static function getUniqueId() { if (isset($_COOKIE['mp_'. self::getToken() .'_mixpanel'])) { $mixpanel_cookie = json_decode($_COOKIE['mp_'. $token .'_mixpanel']); return $mixpanel_cookie->distinct_id; } return false; } /** * @param bool $token * @param array $options * @return LaravelMixpanel */ public static function getInstance($token = false, $options = array()) { if (!$token) { $token = Config::get('laravel-mixpanel.token'); } /** * Init the library and use the generated cookie by the Javascript to identify the user. */ if (!isset(self::$_instance)) { self::$_instance = new LaravelMixpanel($token, $options); if (self::getUniqueId()) { self::$_instance->identify(self::getUniqueId()); } } return self::$_instance; } /** * @return mixed */ public function getToken() { return $this->token; } /** * @param mixed $token */ public function setToken($token) { $this->token = $token; } }
<?php namespace Hydrarulz\LaravelMixpanel; use Illuminate\Support\Facades\Config; use Mixpanel; class LaravelMixpanel extends Mixpanel { protected $token; private static $_instance; /** * @param array $token * @param array $options */ public function __construct($token, array $options = array()) { $this->setToken($token); self::$_instance = parent::__construct($this->token, $options = array()); } /** * @param bool $token * @param array $options * @return LaravelMixpanel */ public static function getInstance($token = false, $options = array()) { if (!$token) { $token = Config::get('laravel-mixpanel.token'); } /** * Init the library and use the generated cookie by the Javascript to identify the user. */ if (!isset(self::$_instance)) { self::$_instance = new LaravelMixpanel($token, $options); $mixpanel_cookie = json_decode($_COOKIE['mp_'. $token .'_mixpanel']); self::$_instance->identify($mixpanel_cookie->distinct_id); } return self::$_instance; } /** * @return mixed */ public function getToken() { return $this->token; } /** * @param mixed $token */ public function setToken($token) { $this->token = $token; } }
Implement most of test class
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms.util; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import java.util.Properties; import static org.junit.jupiter.api.Assertions.*; /** * Test class for {@link PropertyOperator}. * * @since December 14, 2016 * @author Ted Frohlich <[email protected]> * @author Abby Walker <[email protected]> */ class PropertyOperatorTest { private static final String LOAD_FILE = "util/TestProperties.properties"; private static final String SAVE_FILE = "util/TestProperties.properties"; private Properties propertiesToTest; @BeforeEach void setUp() { propertiesToTest = new Properties(); propertiesToTest.setProperty("key_string", "value_string"); propertiesToTest.setProperty("key_int", "380"); propertiesToTest.setProperty("key_float", "216.368"); } @AfterEach void tearDown() { propertiesToTest.clear(); propertiesToTest = null; } @Test void loadProperties() { Properties propertiesToLoad = PropertyOperator.loadProperties(LOAD_FILE); // TODO: needs to be implemented assert false; } @Test void saveProperties() { Properties propertiesToSave = propertiesToTest; propertiesToSave.setProperty("new_key", "new_value"); boolean success = PropertyOperator.saveProperties( propertiesToSave, SAVE_FILE, "New Description!"); assert success; } }
/* *\ ** SICU Stress Measurement System ** ** Project P04 | C380 Team A ** ** EBME 380: Biomedical Engineering Design Experience ** ** Case Western Reserve University ** ** 2016 Fall Semester ** \* */ package edu.cwru.sicu_sms.util; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; /** * Test class for {@link PropertyOperator}. * * @since December 14, 2016 * @author Ted Frohlich <[email protected]> * @author Abby Walker <[email protected]> */ class PropertyOperatorTest { @BeforeEach void setUp() { } @AfterEach void tearDown() { } @Test void loadProperties() { } @Test void saveProperties() { } }
Move the babel task to the test task.
'use strict'; const loadGruntTasks = require('load-grunt-tasks'); const rollupPluginBabel = require('rollup-plugin-babel'); module.exports = function register(grunt) { loadGruntTasks(grunt); grunt.initConfig({ eslint: { all: ['lib', 'test'], }, clean: { all: ['dist', 'tmp'], }, rollup: { all: { options: { external: 'react', plugins: [ rollupPluginBabel(), ], format: 'cjs', }, files: { 'dist/index.js': 'lib/index.js', }, }, }, babel: { all: { files: [{ expand: true, cwd: 'lib/', src: '**/*.js', dest: 'tmp/', }], }, }, mochaTest: { test: { options: { timeout: 500, }, src: [ 'test/boot.js', 'test/**/*.test.js', ], }, }, }); grunt.registerTask('prepublish', ['eslint', 'clean', 'rollup']); grunt.registerTask('test', ['prepublish', 'babel', 'mochaTest']); grunt.registerTask('default', ['test']); };
'use strict'; const loadGruntTasks = require('load-grunt-tasks'); const rollupPluginBabel = require('rollup-plugin-babel'); module.exports = function register(grunt) { loadGruntTasks(grunt); grunt.initConfig({ eslint: { all: ['lib', 'test'], }, clean: { all: ['dist', 'tmp'], }, rollup: { all: { options: { external: 'react', plugins: [ rollupPluginBabel(), ], format: 'cjs', }, files: { 'dist/index.js': 'lib/index.js', }, }, }, babel: { all: { files: [{ expand: true, cwd: 'lib/', src: '**/*.js', dest: 'tmp/', }], }, }, mochaTest: { test: { options: { timeout: 500, }, src: [ 'test/boot.js', 'test/**/*.test.js', ], }, }, }); grunt.registerTask('prepublish', ['eslint', 'clean', 'babel', 'rollup']); grunt.registerTask('test', ['prepublish', 'mochaTest']); grunt.registerTask('default', ['test']); };
Remove bson, datetime, and mongo Current BSON fails to work datetime can't be serialized by json_util mongodb is not needed; just use JSON
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='+') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') args = parser.parse_args() for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} # url and title bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() if link.string\ else bookmark['url'] # tags tags = link.get('tags') bookmark['tags'] = tags.split(',') if tags else [] if args.tags: bookmark['tags'] += args.tags # comment sibling = link.parent.next_sibling bookmark['comment'] = \ sibling.string.strip() if sibling and sibling.name == 'dd' \ else '' print(json.dumps(bookmark, sort_keys=False, indent=4))
#!/usr/bin/env python # # Convert browser bookmark export (NETSCAPE-Bookmark-file-1 format) to json # from argparse import ArgumentParser from bs4 import BeautifulSoup from datetime import datetime, timezone from bson import json_util import json parser = ArgumentParser(description='Convert Netscape bookmarks to JSON') parser.add_argument(dest='filenames', metavar='filename', nargs='+') parser.add_argument('-t', '--tag', metavar='tag', dest='tags', action='append', help='add tag to bookmarks, repeat \ for multiple tags') parser.add_argument('-m', '--mongodb', action='store_true', dest='mongo', help='output in mongodb import format') args = parser.parse_args() for filename in args.filenames: soup = BeautifulSoup(open(filename, encoding='utf8'), "html5lib") for link in soup.find_all('a'): bookmark = {} # url and title bookmark['url'] = link.get('href') bookmark['title'] = link.string.strip() if link.string\ else bookmark['url'] # add date secs = link.get('add_date') date = datetime.fromtimestamp(int(secs), tz=timezone.utc) bookmark['add_date'] = date # tags tags = link.get('tags') bookmark['tags'] = tags.split(',') if tags else [] if args.tags: bookmark['tags'] += args.tags # comment sibling = link.parent.next_sibling bookmark['comment'] = \ sibling.string.strip() if sibling and sibling.name == 'dd' \ else '' # make json if args.mongo: print(json_util.dumps(bookmark, sort_keys=False, indent=4)) else: print(json.dumps(bookmark, sort_keys=False, indent=4))
Remove leftover `console.log` in `clever env import`
'use strict'; const readline = require('readline'); const _ = require('lodash'); const Bacon = require('baconjs'); function parseLine (line) { const p = line.split('='); const key = p[0]; p.shift(); const value = p.join('='); if (line.trim()[0] !== '#' && p.length > 0) { return [key.trim(), value.trim()]; } return null; }; function render (variables, addExport) { return _(variables) .map(({ name, value }) => { if (addExport) { const escapedValue = value.replace(/'/g, '\'\\\'\''); return `export ${name}='${escapedValue}';`; } return `${name}=${value}`; }) .join('\n'); }; function readFromStdin () { return Bacon.fromBinder((sink) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, }); const vars = {}; rl.on('line', (line) => { const res = parseLine(line); if (res) { const [name, value] = res; vars[name] = value; } }); rl.on('close', () => { sink(new Bacon.Next(vars)); sink(new Bacon.End()); }); }); }; module.exports = { parseLine, render, readFromStdin, };
'use strict'; const readline = require('readline'); const _ = require('lodash'); const Bacon = require('baconjs'); function parseLine (line) { const p = line.split('='); const key = p[0]; p.shift(); const value = p.join('='); if (line.trim()[0] !== '#' && p.length > 0) { return [key.trim(), value.trim()]; } return null; }; function render (variables, addExport) { return _(variables) .map(({ name, value }) => { if (addExport) { const escapedValue = value.replace(/'/g, '\'\\\'\''); return `export ${name}='${escapedValue}';`; } return `${name}=${value}`; }) .join('\n'); }; function readFromStdin () { return Bacon.fromBinder((sink) => { const rl = readline.createInterface({ input: process.stdin, output: process.stdout, terminal: false, }); const vars = {}; rl.on('line', (line) => { const res = parseLine(line); if (res) { const [name, value] = res; vars[name] = value; } }); rl.on('close', () => { console.log(vars); sink(new Bacon.Next(vars)); sink(new Bacon.End()); }); }); }; module.exports = { parseLine, render, readFromStdin, };
Fix the issue of override url by mistake.
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
from django.conf.urls import patterns, include, url from django.conf import settings from django.conf.urls.static import static # Uncomment the next two lines to enable the admin: from django.contrib import admin # from mezzanine.core.views import direct_to_template admin.autodiscover() # Must be defined before auto discover and urlpatterns var. So when there is root url # injection, we first insert root url to this, then the last line will insert it to real urlpatterns default_app_url_patterns = [] from djangoautoconf import auto_conf_urls auto_conf_urls.autodiscover() urlpatterns = patterns('', # Examples: # url(r'^default_django_15_and_below/', include('default_django_15_and_below.foo.urls')), # Uncomment the admin/doc line below to enable admin documentation: url(r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: url(r'^admin/', include(admin.site.urls)), # url(r'^', include('demo.urls')), # url(r'^obj_sys/', include('obj_sys.urls')), # url("^$", direct_to_template, {"template": "index.html"}, name="home"), ) urlpatterns = [ # ... the rest of your URLconf goes here ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += default_app_url_patterns
Fix bug in round results property
package es.tid.smartsteps.dispersion; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.hadoop.conf.Configuration; /** * * @author dmicol */ public abstract class Config { public static final String DELIMITER = "delimiter"; public static final String DATE_TO_FILTER = "date_to_filter"; public static final String COUNT_FIELDS = "count_fields"; public static final String ROUND_RESULTS = "round_results"; private Config() { } public static Configuration load(InputStream configInput, final Configuration configuration) throws IOException { Properties props = new Properties(); props.load(configInput); Configuration conf = new Configuration(configuration); conf.set(DELIMITER, props.getProperty(DELIMITER)); conf.set(DATE_TO_FILTER, props.getProperty(DATE_TO_FILTER)); List<String> countFields = new LinkedList<String>(); for (String countField : props.getProperty(COUNT_FIELDS).split(",")) { countFields.add(countField.trim().replaceAll("\"", "")); } conf.setStrings(COUNT_FIELDS, countFields.toArray(new String[countFields.size()])); conf.setBoolean(ROUND_RESULTS, props.getProperty(ROUND_RESULTS).equalsIgnoreCase("true") ? true : false); return conf; } }
package es.tid.smartsteps.dispersion; import java.io.IOException; import java.io.InputStream; import java.util.LinkedList; import java.util.List; import java.util.Properties; import org.apache.hadoop.conf.Configuration; /** * * @author dmicol */ public abstract class Config { public static final String DELIMITER = "delimiter"; public static final String DATE_TO_FILTER = "date_to_filter"; public static final String COUNT_FIELDS = "count_fields"; public static final String ROUND_RESULTS = "round_results"; private Config() { } public static Configuration load(InputStream configInput, final Configuration configuration) throws IOException { Properties props = new Properties(); props.load(configInput); Configuration conf = new Configuration(configuration); conf.set(DELIMITER, props.getProperty(DELIMITER)); conf.set(DATE_TO_FILTER, props.getProperty(DATE_TO_FILTER)); List<String> countFields = new LinkedList<String>(); for (String countField : props.getProperty(COUNT_FIELDS).split(",")) { countFields.add(countField.trim().replaceAll("\"", "")); } conf.setStrings(COUNT_FIELDS, countFields.toArray(new String[countFields.size()])); conf.setBoolean(ROUND_RESULTS, props.getProperty(DELIMITER).equalsIgnoreCase("true") ? true : false); return conf; } }
Update requirements to things that work
from setuptools import setup setup(name='eventum', version='0.2.6', description='A content management system for event-driven Flask apps', url='http://github.com/danrschlosser/eventum', author='Dan Schlosser', author_email='[email protected]', license='MIT', packages=['eventum'], include_package_data=True, install_requires=[ 'Flask>=0.10.1', 'Flask-Assets>=0.11', 'Flask-WTF>=0.9.5', 'Jinja2>=2.7.2', 'Markdown>=2.4', 'WTForms>=1.0.5', 'argparse>=1.2.1', 'blinker>=1.3', 'cssmin>=0.2.0', 'flask-mongoengine>=0.7.0,<0.8.0', 'gaenv>=0.1.7', 'google-api-python-client>=1.2', 'gunicorn>=19.2.1', 'httplib2>=0.8', 'mongoengine>=0.8.7', 'pyRFC3339>=0.2', 'pymongo>=2.7.2', 'python-gflags>=2.0', 'pytz>=2015.2', 'requests>=2.3.0', 'webassets>=0.11.1,<0.12.0' ], zip_safe=False)
from setuptools import setup setup(name='eventum', version='0.2.6', description='A content management system for event-driven Flask apps', url='http://github.com/danrschlosser/eventum', author='Dan Schlosser', author_email='[email protected]', license='MIT', packages=['eventum'], include_package_data=True, install_requires=[ 'Flask>=0.10.1', 'Flask-Assets>=0.11', 'Flask-WTF>=0.9.5', 'Jinja2>=2.7.2', 'Markdown>=2.4', 'WTForms>=1.0.5', 'argparse>=1.2.1', 'blinker==1.3', 'flask-mongoengine>=0.7.0', 'gaenv>=0.1.7', 'google-api-python-client>=1.2', 'gunicorn>=19.2.1', 'httplib2>=0.8', 'mongoengine>=0.8.7', 'pyRFC3339>=0.2', 'pymongo>=2.7.2', 'python-gflags>=2.0', 'pytz>=2015.2', 'requests>=2.3.0', 'webassets>=0.11.1' ], zip_safe=False)
Fix wrong model id key (1011)
<?php declare(strict_types=1); namespace Inowas\ModflowModel\Model\Command; use Inowas\Common\Id\ModflowId; use Inowas\Common\Id\UserId; use Inowas\Common\Soilmodel\LayerId; use Prooph\Common\Messaging\Command; use Prooph\Common\Messaging\PayloadConstructable; use Prooph\Common\Messaging\PayloadTrait; class RemoveLayer extends Command implements PayloadConstructable { use PayloadTrait; public static function forModflowModel(UserId $userId, ModflowId $modelId, LayerId $layerId): RemoveLayer { $self = new static( [ 'id' => $modelId->toString(), 'layer_id' => $layerId->toString() ] ); /** @var RemoveLayer $self */ $self = $self->withAddedMetadata('user_id', $userId->toString()); return $self; } public function schema(): string { return 'file://spec/schema/modflow/command/removeLayerPayload.json'; } public function modelId(): ModflowId { return ModflowId::fromString($this->payload['id']); } public function userId(): UserId { return UserId::fromString($this->metadata['user_id']); } public function layerId(): LayerId { return LayerId::fromString($this->payload['layer_id']); } }
<?php declare(strict_types=1); namespace Inowas\ModflowModel\Model\Command; use Inowas\Common\Id\ModflowId; use Inowas\Common\Id\UserId; use Inowas\Common\Soilmodel\LayerId; use Prooph\Common\Messaging\Command; use Prooph\Common\Messaging\PayloadConstructable; use Prooph\Common\Messaging\PayloadTrait; class RemoveLayer extends Command implements PayloadConstructable { use PayloadTrait; public static function forModflowModel(UserId $userId, ModflowId $modelId, LayerId $layerId): RemoveLayer { $self = new static( [ 'model_id' => $modelId->toString(), 'layer_id' => $layerId->toString() ] ); /** @var RemoveLayer $self */ $self = $self->withAddedMetadata('user_id', $userId->toString()); return $self; } public function schema(): string { return 'file://spec/schema/modflow/command/removeLayerPayload.json'; } public function modelId(): ModflowId { return ModflowId::fromString($this->payload['model_id']); } public function userId(): UserId { return UserId::fromString($this->metadata['user_id']); } public function layerId(): LayerId { return LayerId::fromString($this->payload['layer_id']); } }
Fix init of local recognizer
import unittest import os from speech_recognition import WavFile from mycroft.client.speech.listener import RecognizerLoop __author__ = 'seanfitz' DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data") class LocalRecognizerTest(unittest.TestCase): def setUp(self): rl = RecognizerLoop() self.recognizer = RecognizerLoop.create_mycroft_recognizer(rl, 16000, "en-us") def testRecognizerWrapper(self): source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower() source = WavFile(os.path.join(DATA_DIR, "mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower() def testRecognitionInLongerUtterance(self): source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower()
import unittest import os from speech_recognition import WavFile from mycroft.client.speech.listener import RecognizerLoop __author__ = 'seanfitz' DATA_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), "data") class LocalRecognizerTest(unittest.TestCase): def setUp(self): self.recognizer = RecognizerLoop.create_mycroft_recognizer(16000, "en-us") def testRecognizerWrapper(self): source = WavFile(os.path.join(DATA_DIR, "hey_mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower() source = WavFile(os.path.join(DATA_DIR, "mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower() def testRecognitionInLongerUtterance(self): source = WavFile(os.path.join(DATA_DIR, "weather_mycroft.wav")) with source as audio: hyp = self.recognizer.transcribe(audio.stream.read()) assert self.recognizer.key_phrase in hyp.hypstr.lower()
Remove locale related reassignment to global window object
import React from 'react'; import PropTypes from 'prop-types'; import getDisplayName from '../utils/getDisplayName'; import { localeShape } from '../constants/PropTypes'; export default Page => { class WithLocale extends React.Component { static displayName = getDisplayName('WithLocale', Page); static propTypes = { defaultLocale: PropTypes.string, siteLocales: PropTypes.arrayOf(PropTypes.string.isRequired), locale: localeShape, }; static async getInitialProps(ctx) { const { defaultLocale, siteLocales, locale } = ctx.req || window.__NEXT_DATA__.props; if (!ctx.req) { if (ctx.query.locale) { const [language, country] = ctx.query.locale.split('-'); if (siteLocales.indexOf(`${language}-${country}`) !== -1) { locale.language = language; locale.country = country; } } } const props = Page.getInitialProps && await Page.getInitialProps({ ...ctx, defaultLocale, siteLocales, locale, }); return { ...props, defaultLocale, siteLocales, locale, }; } render() { return <Page {...this.props} />; } } return WithLocale; };
import React from 'react'; import PropTypes from 'prop-types'; import getDisplayName from '../utils/getDisplayName'; import { localeShape } from '../constants/PropTypes'; export default Page => { class WithLocale extends React.Component { static displayName = getDisplayName('WithLocale', Page); static propTypes = { defaultLocale: PropTypes.string, siteLocales: PropTypes.arrayOf(PropTypes.string.isRequired), locale: localeShape, }; static async getInitialProps(ctx) { let defaultLocale, siteLocales, locale; if (ctx.req) { defaultLocale = ctx.req.defaultLocale; siteLocales = ctx.req.siteLocales; locale = ctx.req.locale; } else { defaultLocale = window.defaultLocale; siteLocales = window.siteLocales; locale = window.locale; if (ctx.query.locale) { const [language, country] = ctx.query.locale.split('-'); if (siteLocales.indexOf(`${language}-${country}`) !== -1) { locale = { language, country, }; } } } const props = Page.getInitialProps && await Page.getInitialProps({ ...ctx, defaultLocale, siteLocales, locale, }); return { ...props, defaultLocale, siteLocales, locale, }; } componentDidMount() { window.defaultLocale = this.props.defaultLocale; window.siteLocales = this.props.siteLocales; window.locale = this.props.locale; } render() { return <Page {...this.props} />; } } return WithLocale; };
BAP-12468: Update ApplicationsHelper and ActionApplicationsHelper - fix phpdoc
<?php namespace Oro\Bundle\ActionBundle\Helper; use Symfony\Component\Routing\RouterInterface; class ApplicationsUrlHelper { /** @var ApplicationsHelper */ private $applicationsHelper; /** @var RouterInterface */ private $router; /** * @param ApplicationsHelperInterface $applicationsHelper * @param RouterInterface $router */ public function __construct(ApplicationsHelperInterface $applicationsHelper, RouterInterface $router) { $this->applicationsHelper = $applicationsHelper; $this->router = $router; } /** * @param array $parameters * * @return string */ public function getExecutionUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getExecutionRoute(), $parameters); } /** * @param array $parameters * * @return string */ public function getDialogUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getFormDialogRoute(), $parameters); } /** * @param array $parameters * * @return string */ public function getPageUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getFormPageRoute(), $parameters); } /** * @param string $routeName * @param array $parameters * * @return string */ private function generateUrl($routeName, array $parameters = []) { return $this->router->generate($routeName, $parameters); } }
<?php namespace Oro\Bundle\ActionBundle\Helper; use Symfony\Component\Routing\RouterInterface; class ApplicationsUrlHelper { /** @var ApplicationsHelper */ private $applicationsHelper; /** @var RouterInterface */ private $router; /** * @param ApplicationsHelperInterface $applicationsHelper * @param RouterInterface $router */ public function __construct(ApplicationsHelperInterface $applicationsHelper, RouterInterface $router) { $this->applicationsHelper = $applicationsHelper; $this->router = $router; } /** * @param array $parameters * * @return string */ public function getExecutionUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getExecutionRoute(), $parameters); } /** * @param array $parameters * * @return string */ public function getDialogUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getFormDialogRoute(), $parameters); } /** * @param array $parameters * * @return string */ public function getPageUrl(array $parameters = []) { return $this->generateUrl($this->applicationsHelper->getFormPageRoute(), $parameters); } /** * @param $routeName * @param array $parameters * * @return string */ private function generateUrl($routeName, array $parameters = []) { return $this->router->generate($routeName, $parameters); } }
Set period to 24 hours now that it works
"""Updates atom feeds.""" import datetime import time import db import tools # Time in seconds between re-processing a domain. PERIOD = 86400 if __name__ == '__main__': while True: try: start = time.time() # Pick the oldest domain. with db.cursor() as cursor: threshold = ( datetime.datetime.now() - datetime.timedelta(seconds=PERIOD) ) # Get the first entry with an updated date older than the # threshold. cursor.execute(""" SELECT domain, updated FROM stored WHERE updated < (%s) ORDER BY updated ASC LIMIT 1 """, (threshold,)) result = cursor.fetchone() # If we're idle, that's great. if result is None: time.sleep(1) continue domain, updated = result age = (datetime.datetime.now() - updated).total_seconds() # Generate a new report. latest = {} for entry in tools.analyse(domain)[1]['fuzzy_domains'][1:]: ip, error = tools.resolve(entry['domain-name']) if error or not ip or ip is None: continue latest[entry['domain-name']] = ip # Update the "latest" version of the report. db.stored_set(domain, latest) print ','.join(map(str, ( domain, age, time.time() - start ))) except Exception as ex: db.DB = None time.sleep(1) print 'crashed... {}'.format(ex)
"""Updates atom feeds.""" import datetime import time import db import tools # Time in seconds between re-processing a domain. PERIOD = 60#86400 if __name__ == '__main__': while True: try: start = time.time() # Pick the oldest domain. with db.cursor() as cursor: threshold = ( datetime.datetime.now() - datetime.timedelta(seconds=PERIOD) ) # Get the first entry with an updated date older than the # threshold. cursor.execute(""" SELECT domain, updated FROM stored WHERE updated < (%s) ORDER BY updated ASC LIMIT 1 """, (threshold,)) result = cursor.fetchone() # If we're idle, that's great. if result is None: time.sleep(1) continue domain, updated = result age = (datetime.datetime.now() - updated).total_seconds() # Generate a new report. latest = {} for entry in tools.analyse(domain)[1]['fuzzy_domains'][1:]: ip, error = tools.resolve(entry['domain-name']) if error or not ip or ip is None: continue latest[entry['domain-name']] = ip # Update the "latest" version of the report. db.stored_set(domain, latest) print ','.join(map(str, ( domain, age, time.time() - start ))) except Exception as ex: db.DB = None time.sleep(1) print 'crashed... {}'.format(ex)
Change the singleRun Karma option to true for Travis builds
module.exports = function karma(config) { config.set({ frameworks: ['mocha'], files: [ { pattern: 'src/**/*.js', included: false }, 'tests/**/*.js', ], preprocessors: { 'tests/**/*.js': ['webpack', 'sourcemap'], }, webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: [ ['env', { targets: { edge: 12, firefox: 42, chrome: 49, safari: 10, node: 6, }, modules: false, }], ], plugins: ['transform-object-rest-spread'], }, }, ], }, devtool: 'inline-source-map', }, webpackMiddleware: { noInfo: 'true', }, reporters: ['mocha'], logLevel: config.LOG_WARN, browsers: [process.env.TRAVIS ? 'Chrome_travis_ci' : 'Chrome', 'Firefox'], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'], }, }, singleRun: process.env.TRAVIS, }); };
module.exports = function karma(config) { config.set({ frameworks: ['mocha'], files: [ { pattern: 'src/**/*.js', included: false }, 'tests/**/*.js', ], preprocessors: { 'tests/**/*.js': ['webpack', 'sourcemap'], }, webpack: { module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets: [ ['env', { targets: { edge: 12, firefox: 42, chrome: 49, safari: 10, node: 6, }, modules: false, }], ], plugins: ['transform-object-rest-spread'], }, }, ], }, devtool: 'inline-source-map', }, webpackMiddleware: { noInfo: 'true', }, reporters: ['mocha'], logLevel: config.LOG_WARN, browsers: [process.env.TRAVIS ? 'Chrome_travis_ci' : 'Chrome', 'Firefox'], customLaunchers: { Chrome_travis_ci: { base: 'Chrome', flags: ['--no-sandbox'], }, }, }); };
Fix condition, make sure not to include non-pivot relations
<?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot' && str_contains($relation, 'pivot'); }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } }
<?php class EloquentBuilder extends \Illuminate\Database\Eloquent\Builder { /** * Eager load pivot relations. * * @param array $models * @return void */ protected function loadPivotRelations($models) { $query = head($models)->pivot->newQuery()->with('unit'); $pivots = array_pluck($models, 'pivot'); $pivots = head($pivots)->newCollection($pivots); $pivots->load($this->getPivotRelations()); } /** * Get the pivot relations to be eager loaded. * * @return array */ protected function getPivotRelations() { $relations = array_filter(array_keys($this->eagerLoad), function ($relation) { return $relation != 'pivot'; }); return array_map(function ($relation) { return substr($relation, strlen('pivot.')); }, $relations); } /** * Override. Eager load relations of pivot models. * Eagerly load the relationship on a set of models. * * @param array $models * @param string $name * @param \Closure $constraints * @return array */ protected function loadRelation(array $models, $name, Closure $constraints) { // In this part, if the relation name is 'pivot', // therefore there are relations in a pivot to be eager loaded. if ($name === 'pivot') { $this->loadPivotRelations($models); return $models; } return parent::loadRelation($models, $name, $constraints); } }
Send userID if it exists
import React from 'react'; import './Rating.scss'; import { AuthCtx } from '../withUser'; class Rating extends React.Component { constructor(props) { super(props); this.ratingVals = [ 1, 2, 3, 4, 5 ]; this.state = { rating: 0, hasRating: false, } } componentDidMount() { this.dataLayer = window.dataLayer || []; } rateDoc = user => (e) => { const rating = parseInt( e.target.dataset.rating ); const userID = user ? user.userid : false; this.setState({ rating, hasRating: true, }) analytics.track("Doc Rated", { docID: window.location.pathname, userID, // SendGrid userID or false rating }); } getStars() { return this.ratingVals.map(rating => { const isSelected = rating <= this.state.rating ? 'is-selected' : ''; return ( <span key={rating} className={isSelected} data-rating={rating}>☆</span> ) }); } render() { return ( <div className="rate-this-doc"> <AuthCtx.Consumer> {(ctx) => ( <React.Fragment> <div className="rating" onClick={this.rateDoc(ctx.user)}> {this.getStars()} </div> </React.Fragment> )} </AuthCtx.Consumer> </div> ); } } export default Rating;
import React from 'react'; import './Rating.scss'; import { AuthCtx } from '../withUser'; class Rating extends React.Component { constructor(props) { super(props); this.ratingVals = [ 1, 2, 3, 4, 5 ]; this.state = { rating: 0, hasRating: false, } } componentDidMount() { this.dataLayer = window.dataLayer || []; } rateDoc = user => (e) => { const rating = parseInt( e.target.dataset.rating ); this.setState({ rating, hasRating: true, }) analytics.track("Doc Rated", { userID: false, // SendGrid userID or false docID: window.location.pathname, rating }); } getStars() { return this.ratingVals.map(rating => { const isSelected = rating <= this.state.rating ? 'is-selected' : ''; return ( <span key={rating} className={isSelected} data-rating={rating}>☆</span> ) }); } render() { return ( <div className="rate-this-doc"> <AuthCtx.Consumer> {(ctx) => ( <React.Fragment> <div className="rating" onClick={this.rateDoc(ctx.user)}> {this.getStars()} </div> </React.Fragment> )} </AuthCtx.Consumer> </div> ); } } export default Rating;
Make the anchor working when edit a XML file
'use strict'; /** * @ngdoc directive * @name waxeApp.directive:editor * @description * # editor */ angular.module('waxeApp') .directive('editor', ['$interval', '$anchorScroll', '$location', 'Session', 'FileUtils', function ($interval, $anchorScroll, $location, Session, FileUtils) { return { template: '<div></div>', restrict: 'E', scope: { 'html': '=' }, link: function postLink(scope, element) { element.append(scope.html); var listener = scope.$watch(function(){ if(element.text()) { $anchorScroll($location.hash()); // Remove the watch since the form is fully loaded listener(); waxe.form = new waxe.Form(scope.$parent.treeData); Session.form = waxe.form; angular.element(document).on('click', '.btn-external-editor', function() { eval('scope.$parent.' + angular.element(this).attr('ng-click')); }); } }); Session.autosave_interval = $interval(function() { if (Session.form && Session.form.filename && Session.form.status === 'updated'){ FileUtils.save(); } }, 1000 * 10); } }; }]);
'use strict'; /** * @ngdoc directive * @name waxeApp.directive:editor * @description * # editor */ angular.module('waxeApp') .directive('editor', ['$interval', 'Session', 'FileUtils', function ($interval, Session, FileUtils) { return { template: '<div></div>', restrict: 'E', scope: { 'html': '=' }, link: function postLink(scope, element) { element.append(scope.html); var listener = scope.$watch(function(){ if(element.text()) { // Remove the watch since the form is fully loaded listener(); waxe.form = new waxe.Form(scope.$parent.treeData); Session.form = waxe.form; angular.element(document).on('click', '.btn-external-editor', function() { eval('scope.$parent.' + angular.element(this).attr('ng-click')); }); } }); Session.autosave_interval = $interval(function() { if (Session.form && Session.form.filename && Session.form.status === 'updated'){ FileUtils.save(); } }, 1000 * 10); } }; }]);
Handle zero-arguments case in bitcoinj-cli
package com.msgilligan.bitcoinj.cli; import com.msgilligan.bitcoinj.rpc.JsonRPCException; import java.io.IOException; import java.util.List; /** * An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj * */ public class BitcoinJCli extends CliCommand { public final static String commandName = "bitcoinj-cli"; public BitcoinJCli(String[] args) { super(commandName, new CliOptions(), args); } public static void main(String[] args) { BitcoinJCli command = new BitcoinJCli(args); Integer status = command.run(); System.exit(status); } public Integer runImpl() throws IOException { // Hacked together parsing that barely supports the two RPC methods in the Spock test // TODO: Make this better and complete @SuppressWarnings("unchecked") List<Object> args = (List<Object>) line.getArgList(); if (args.size() == 0) { printError("rpc method required"); printHelp(); return(1); } String method = (String) args.get(0); args.remove(0); // remove method from list if (args.size() > 0 && args.get(0) != null) { args.set(0, true); } Object result; try { result = client.cliSend(method, args.toArray()); } catch (JsonRPCException e) { e.printStackTrace(); return 1; } if (result != null) { pwout.println(result.toString()); } return 0; } }
package com.msgilligan.bitcoinj.cli; import com.msgilligan.bitcoinj.rpc.JsonRPCException; import java.io.IOException; import java.util.List; /** * An attempt at cloning the bitcoin-cli tool, but using Java and bitcoinj * */ public class BitcoinJCli extends CliCommand { public final static String commandName = "bitcoinj-cli"; public BitcoinJCli(String[] args) { super(commandName, new CliOptions(), args); } public static void main(String[] args) { BitcoinJCli command = new BitcoinJCli(args); Integer status = command.run(); System.exit(status); } public Integer runImpl() throws IOException { // Hacked together parsing that barely supports the two RPC methods in the Spock test // TODO: Make this better and complete @SuppressWarnings("unchecked") List<Object> args = (List<Object>) line.getArgList(); String method = (String) args.get(0); args.remove(0); // remove method from list if (args.size() > 0 && args.get(0) != null) { args.set(0, true); } Object result; try { result = client.cliSend(method, args.toArray()); } catch (JsonRPCException e) { e.printStackTrace(); return 1; } if (result != null) { pwout.println(result.toString()); } return 0; } }
Fix import error when compiling without OpenSSL support
#################################################################### #Dtool_funcToMethod(func, class) #del func ##################################################################### from panda3d import core from .extension_native_helpers import Dtool_funcToMethod """ HTTPChannel-extensions module: contains methods to extend functionality of the HTTPChannel class """ def spawnTask(self, name = None, callback = None, extraArgs = []): """Spawns a task to service the download recently requested via beginGetDocument(), etc., and/or downloadToFile() or downloadToRam(). If a callback is specified, that function is called when the download is complete, passing in the extraArgs given. Returns the newly-spawned task. """ if not name: name = str(self.getUrl()) from direct.task import Task task = Task.Task(self.doTask) task.callback = callback task.callbackArgs = extraArgs return taskMgr.add(task, name) if hasattr(core, 'HTTPChannel'): Dtool_funcToMethod(spawnTask, core.HTTPChannel) del spawnTask ##################################################################### def doTask(self, task): from direct.task import Task if self.run(): return Task.cont if task.callback: task.callback(*task.callbackArgs) return Task.done if hasattr(core, 'HTTPChannel'): Dtool_funcToMethod(doTask, core.HTTPChannel) del doTask #####################################################################
#################################################################### #Dtool_funcToMethod(func, class) #del func ##################################################################### from panda3d.core import HTTPChannel from .extension_native_helpers import Dtool_funcToMethod """ HTTPChannel-extensions module: contains methods to extend functionality of the HTTPChannel class """ def spawnTask(self, name = None, callback = None, extraArgs = []): """Spawns a task to service the download recently requested via beginGetDocument(), etc., and/or downloadToFile() or downloadToRam(). If a callback is specified, that function is called when the download is complete, passing in the extraArgs given. Returns the newly-spawned task. """ if not name: name = str(self.getUrl()) from direct.task import Task task = Task.Task(self.doTask) task.callback = callback task.callbackArgs = extraArgs return taskMgr.add(task, name) Dtool_funcToMethod(spawnTask, HTTPChannel) del spawnTask ##################################################################### def doTask(self, task): from direct.task import Task if self.run(): return Task.cont if task.callback: task.callback(*task.callbackArgs) return Task.done Dtool_funcToMethod(doTask, HTTPChannel) del doTask #####################################################################
Update grunt for bin file
module.exports = function(grunt) { var path = require('path'); grunt.initConfig({ clean: [ 'dist' ], jshint: { all: { src: [ 'Gruntfile.js', 'lib/**/*.js' ] }, options: { jshintrc: '.jshintrc', force: true } }, transpile: { app: { type: 'cjs', files: [{ expand: true, src: ['lib/**/*.js'], dest: 'tmp/transpiled/' }] } }, es6ify: { app: { files: [{ expand: true, cwd: 'tmp/transpiled/', src: ['lib/**/*.js'], dest: 'dist/' }] } }, simplemocha: { options: { globals: ['should'], timeout: 3000, ignoreLeaks: false }, all: { src: ['test/*.js'] } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-es6-module-transpiler'); grunt.loadNpmTasks('grunt-simple-mocha'); // Load local tasks. grunt.task.loadTasks('./tasks'); // Note not exposing a build + test endpoint as there are conflicts with // transpile + es6ify (waiting for https://github.com/google/traceur-compiler/pull/323) grunt.registerTask('test', ['simplemocha']); grunt.registerTask('default', ['test']); };
module.exports = function(grunt) { var path = require('path'); grunt.initConfig({ clean: [ 'dist' ], transpile: { app: { type: 'cjs', files: [{ expand: true, src: ['bin/es6-module-packager', 'lib/**/*.js'], dest: 'tmp/transpiled/' }] } }, es6ify: { app: { files: [{ expand: true, cwd: 'tmp/transpiled/', src: ['bin/es6-module-packager', 'lib/**/*.js'], dest: 'dist/' }] } }, jshint: { all: { src: [ 'Gruntfile.js', 'lib/**/*.js' ] }, options: { jshintrc: '.jshintrc', force: true } }, simplemocha: { options: { globals: ['should'], timeout: 3000, ignoreLeaks: false }, all: { src: ['test/*.js'] } } }); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-es6-module-transpiler'); grunt.loadNpmTasks('grunt-simple-mocha'); // Load local tasks. grunt.task.loadTasks('./tasks'); // Note not exposing a build + test endpoint as there are conflicts with // transpile + es6ify (waiting for https://github.com/google/traceur-compiler/pull/323) grunt.registerTask('test', ['simplemocha']); grunt.registerTask('default', ['test']); };
Change development status from pre-alpha to alpha
import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) # "import" __version__ for line in open("jack.py"): if line.startswith("__version__"): exec(line) break setup( name="JACK-Client", version=__version__, py_modules=["jack"], install_requires=['cffi'], author="Matthias Geier", author_email="[email protected]", description="JACK Audio Connection Kit (JACK) Client for Python", long_description=open("README.rst").read(), license="MIT", keywords="JACK audio low-latency multi-channel".split(), url="http://jackclient-python.rtfd.org/", platforms="any", classifiers=[ "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Multimedia :: Sound/Audio", ], tests_require=['pytest'], cmdclass={'test': PyTest}, )
import sys from setuptools import setup from setuptools.command.test import test as TestCommand class PyTest(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test_args = [] self.test_suite = True def run_tests(self): # import here, cause outside the eggs aren't loaded import pytest errno = pytest.main(self.test_args) sys.exit(errno) # "import" __version__ for line in open("jack.py"): if line.startswith("__version__"): exec(line) break setup( name="JACK-Client", version=__version__, py_modules=["jack"], install_requires=['cffi'], author="Matthias Geier", author_email="[email protected]", description="JACK Audio Connection Kit (JACK) Client for Python", long_description=open("README.rst").read(), license="MIT", keywords="JACK audio low-latency multi-channel".split(), url="http://jackclient-python.rtfd.org/", platforms="any", classifiers=[ "Development Status :: 2 - Pre-Alpha", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Multimedia :: Sound/Audio", ], tests_require=['pytest'], cmdclass={'test': PyTest}, )
Disable automatic header numbering for now
function Structure() { this.outline = null; } Structure.prototype.numberHeadings = function() { var sectionNumbers = [0,0,0,0,0,0]; for (var child = document.body.firstChild; child != null; child = child.nextSibling) { if (isHeadingElement(child)) { var level = parseInt(child.nodeName.slice(1))-1; sectionNumbers[level]++; for (var i = level+1; i < 6; i++) sectionNumbers[i] = 0; var str = ""; for (var i = 0; i <= level; i++) { if (str == "") str += sectionNumbers[i]; else str += "."+sectionNumbers[i]; } var text = document.createTextNode(str+" "); var span = document.createElement("SPAN"); span.setAttribute("class","uxwrite.headingnumber"); span.appendChild(text); child.insertBefore(span,child.firstChild); } } } Structure.prototype.examineDocument = function() { // this.numberHeadings(); } structure = new Structure();
function Structure() { this.outline = null; } Structure.prototype.numberHeadings = function() { var sectionNumbers = [0,0,0,0,0,0]; for (var child = document.body.firstChild; child != null; child = child.nextSibling) { if (isHeadingElement(child)) { var level = parseInt(child.nodeName.slice(1))-1; sectionNumbers[level]++; for (var i = level+1; i < 6; i++) sectionNumbers[i] = 0; var str = ""; for (var i = 0; i <= level; i++) { if (str == "") str += sectionNumbers[i]; else str += "."+sectionNumbers[i]; } var text = document.createTextNode(str+" "); var span = document.createElement("SPAN"); span.setAttribute("class","uxwrite.headingnumber"); span.appendChild(text); child.insertBefore(span,child.firstChild); } } } Structure.prototype.examineDocument = function() { this.numberHeadings(); } structure = new Structure();
[Dns] Fix parse errors in resolver stub
<?php namespace React\Dns; use React\Socket\Connection; class Resolver { public function resolve($domain, $callback) { $nameserver = '8.8.8.8'; $query = new Query($domain, 'A', 'IN'); $this->query($nameserver, $query, function (Message $response) use ($callback) { $answer = $response->answer[array_rand($response->answer)]->data->address; $callback($address); }); } public function query($nameserver, Query $query, $callback) { $dumper = new BinaryDumper(); $parser = new Parser(); $message = new Message(); $message->header = array( // $query... ); $message->question = array( // $query... ); $response = new Message(); $conn = new Connection(fopen("udp://$nameserver:53"), $this->loop); $conn->on('data', function ($data) use ($conn, $response, $callback) { if ($parser->parseChunk($data, $response)) { $conn->end(); $callback($response); } }); $conn->write($dumper->toBinary($message)); } }
<?php namespace React\Dns; use React\Socket\Connection; class Resolver { public function resolve($domain, $callback) { $nameserver = '8.8.8.8'; $query = new Query($domain, 'A', 'IN'); $this->query($nameserver, $query, function (Message $response) use ($callback) { $answer = $response->answer[array_rand($response->answer)]->data->address; $callback($address); }); } public function query($nameserver, Query $query, $callback) { $dumper = new BinaryDumper(); $parser = new Parser(); $message = new Message(); $message->header = array( $query... ); $message->question = array( $query... ); $response = new Message(); $conn = new Connection(fopen("udp://$nameserver:53"), $this->loop); $conn->on('data', function ($data) use ($conn, $response, $callback) { if ($parser->parseChunk($data, $response)) { $conn->end(); $callback($response); } }); $conn->write($dumper->toBinary($message)); } }
Make visible to interpreter "compositions" outside this package. svn path=/spoofax/trunk/spoofax/org.spoofax.interpreter.adapter.ecj/; revision=16660
/* * * Copyright (c) 2005, Karl Trygve Kalleberg <[email protected]> * * Licensed under the GNU General Public License, v2 */ package org.spoofax.interpreter.library.ecj; import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry; public class ECJLibrary extends AbstractStrategoOperatorRegistry { public static final String REGISTRY_NAME = "ECJ"; public ECJLibrary() { init(); } private void init() { add(new ECJ_parse_only()); add(new ECJ_parse_and_resolve()); add(new ECJ_open_project()); add(new ECJ_create_project()); add(new ECJ_add_source_folder()); add(new ECJ_add_jar()); add(new ECJ_binding_of_name()); add(new ECJ_type_of_type()); add(new ECJ_type_of_typedecl()); add(new ECJ_type_of_typeparameter()); add(new ECJ_method_of_methoddecl()); add(new ECJ_method_of_methodinvoc()); add(new ECJ_method_of_supermethodinvoc()); add(new ECJ_method_of_superctorinvoc()); add(new ECJ_type_of_expr()); add(new ECJ_is_cast_compatible()); add(new ECJ_is_subtype_compatible()); } }
/* * * Copyright (c) 2005, Karl Trygve Kalleberg <[email protected]> * * Licensed under the GNU General Public License, v2 */ package org.spoofax.interpreter.library.ecj; import org.spoofax.interpreter.library.AbstractStrategoOperatorRegistry; public class ECJLibrary extends AbstractStrategoOperatorRegistry { public static final String REGISTRY_NAME = "ECJ"; ECJLibrary() { init(); } private void init() { add(new ECJ_parse_only()); add(new ECJ_parse_and_resolve()); add(new ECJ_open_project()); add(new ECJ_create_project()); add(new ECJ_add_source_folder()); add(new ECJ_add_jar()); add(new ECJ_binding_of_name()); add(new ECJ_type_of_type()); add(new ECJ_type_of_typedecl()); add(new ECJ_type_of_typeparameter()); add(new ECJ_method_of_methoddecl()); add(new ECJ_method_of_methodinvoc()); add(new ECJ_method_of_supermethodinvoc()); add(new ECJ_method_of_superctorinvoc()); add(new ECJ_type_of_expr()); add(new ECJ_is_cast_compatible()); add(new ECJ_is_subtype_compatible()); } }
Adjust check to reject single-column entries
/** * @class csv * @module Parsers */ module.exports = (function() { var FileParser = require('../interfaces/FileParser'); /** * @method Parser * @constructor */ function Parser(file, options) { FileParser.apply(this, arguments); if (options && options.separator) { this._separator = options.separator; } } Parser.prototype = Object.create(FileParser.prototype); Parser.prototype._separator = ','; Parser.constructor = Parser; Parser.prototype.decode = function(data) { var lines = data.split('\n'); var result = []; var length = null; lines.forEach(function(line) { if (!line) { return; } var values = line.split(this._separator); if (values.length <= 1) { return; } else if (!length) { length = values.length; } else if (length !== values.length) { return; } result.push(values); }.bind(this)); return result; }; return Parser; }());
/** * @class csv * @module Parsers */ module.exports = (function() { var FileParser = require('../interfaces/FileParser'); /** * @method Parser * @constructor */ function Parser(file, options) { FileParser.apply(this, arguments); if (options && options.separator) { this._separator = options.separator; } } Parser.prototype = Object.create(FileParser.prototype); Parser.prototype._separator = ','; Parser.constructor = Parser; Parser.prototype.decode = function(data) { var lines = data.split('\n'); var result = []; var length = null; lines.forEach(function(line) { if (!line) { return; } var values = line.split(this._separator); if (!values.length) { return; } else if (!length) { length = values.length; } else if (length !== values.length) { return; } result.push(values); }.bind(this)); return result; }; return Parser; }());
Configure a title for the subscribe page
@extends('layout.master') @section('title', trans('cachet.subscriber.subscribe'). " | ". $site_title)) @section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title])) @section('content') <div class="pull-right"> <p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-page') }}"><i class="ion ion-home"></i></a></p> </div> <div class="clearfix"></div> @include('dashboard.partials.errors') <div class="row"> <div class="col-xs-12 col-lg-offset-2 col-lg-8"> <div class="panel panel-default"> <div class="panel-heading">{{ trans('cachet.subscriber.subscribe') }}</div> <div class="panel-body"> <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="[email protected]"> </div> <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button> </form> </div> </div> </div> </div> @stop
@extends('layout.master') @section('description', trans('cachet.meta.description.subscribe', ['app' => $site_title])) @section('content') <div class="pull-right"> <p><a class="btn btn-success btn-outline" href="{{ cachet_route('status-page') }}"><i class="ion ion-home"></i></a></p> </div> <div class="clearfix"></div> @include('dashboard.partials.errors') <div class="row"> <div class="col-xs-12 col-lg-offset-2 col-lg-8"> <div class="panel panel-default"> <div class="panel-heading">{{ trans('cachet.subscriber.subscribe') }}</div> <div class="panel-body"> <form action="{{ cachet_route('subscribe', [], 'post') }}" method="POST" class="form"> <input type="hidden" name="_token" value="{{ csrf_token() }}"> <div class="form-group"> <input class="form-control" type="email" name="email" placeholder="[email protected]"> </div> <button type="submit" class="btn btn-success">{{ trans('cachet.subscriber.button') }}</button> </form> </div> </div> </div> </div> @stop
Add placeholders for new secondary repo details
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL', 'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER', 'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN', 'REDISCLOUD_URL', 'SECONDARY_REPO_OWNER', 'SECONDARY_REPO_NAME') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # Details of the repo where all articles are stored. The GITHUB_CLIENT_ID # and GITHUB_SECRET should allow full-access to this database. REPO_OWNER = None REPO_NAME = None REPO_OWNER_ACCESS_TOKEN = None # Secondary (optional) repo for articles that are not editable SECONDARY_REPO_OWNER = None SECONDARY_REPO_NAME = None REDISCLOUD_URL = None # This should automatically be set by heroku if you've added a database to # your app. try: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] except KeyError: print 'Failed finding DATABASE_URL environment variable' SQLALCHEMY_DATABASE_URI = '' class DevelopmentConfig(Config): DEBUG = True
""" File to easily switch between configurations between production and development, etc. """ import os # You must set each of these in your heroku environment with the heroku # config:set command. See README.md for more information. HEROKU_ENV_REQUIREMENTS = ('HEROKU', 'SECRET_KEY', 'GITHUB_CLIENT_ID', 'GITHUB_SECRET', 'DATABASE_URL', 'SQLALCHEMY_DATABASE_URI', 'REPO_OWNER', 'REPO_NAME', 'REPO_OWNER_ACCESS_TOKEN', 'REDISCLOUD_URL') class Config(object): DEBUG = False CSRF_ENABLED = True GITHUB_CLIENT_ID = 'replace-me' GITHUB_SECRET = 'replace-me' HEROKU = False SECRET_KEY = 'not-a-good-value' # Details of the repo where all articles are stored. The GITHUB_CLIENT_ID # and GITHUB_SECRET should allow full-access to this database. REPO_OWNER = None REPO_NAME = None REPO_OWNER_ACCESS_TOKEN = None REDISCLOUD_URL = None # This should automatically be set by heroku if you've added a database to # your app. try: SQLALCHEMY_DATABASE_URI = os.environ['DATABASE_URL'] except KeyError: print 'Failed finding DATABASE_URL environment variable' SQLALCHEMY_DATABASE_URI = '' class DevelopmentConfig(Config): DEBUG = True
Fix doc styles in Firefox
import React from 'react'; import CodeBlock from './CodeBlock'; export default class StaticHTMLBlock { static propTypes = { html: React.PropTypes.string.isRequired }; render() { const { html } = this.props; // Here goes a really hack-ish way to convert // areas separated by Markdown <hr>s into code tabs. const blocks = html.split('<hr/>'); const elements = []; let es5Content = null; let es6Content = null; let es7Content = null; for (let i = 0; i < blocks.length; i++) { const content = blocks[i]; switch (i % 4) { case 0: elements.push( <div key={i} style={{ width: '100%' }} dangerouslySetInnerHTML={{__html: content}} /> ); break; case 1: es5Content = content; break; case 2: es6Content = content; break; case 3: es7Content = content; elements.push( <CodeBlock key={i} es5={es5Content} es6={es6Content} es7={es7Content} /> ); break; } } return ( <div style={{ width: '100%' }}> {elements} </div> ); } }
import React from 'react'; import CodeBlock from './CodeBlock'; export default class StaticHTMLBlock { static propTypes = { html: React.PropTypes.string.isRequired }; render() { const { html } = this.props; // Here goes a really hack-ish way to convert // areas separated by Markdown <hr>s into code tabs. const blocks = html.split('<hr/>'); const elements = []; let es5Content = null; let es6Content = null; let es7Content = null; for (let i = 0; i < blocks.length; i++) { const content = blocks[i]; switch (i % 4) { case 0: elements.push( <div key={i} dangerouslySetInnerHTML={{__html: content}} /> ); break; case 1: es5Content = content; break; case 2: es6Content = content; break; case 3: es7Content = content; elements.push( <CodeBlock key={i} es5={es5Content} es6={es6Content} es7={es7Content} /> ); break; } } return ( <div> {elements} </div> ); } }
Work around a problem in later (currently unsupported) embers where Ember.computed.bool is not a function
import { run } from '@ember/runloop'; import Helper from '@ember/component/helper'; import { get, observer, computed } from '@ember/object'; import { inject as service } from '@ember/service'; export default Helper.extend({ moment: service(), disableInterval: false, globalAllowEmpty: computed('moment.__config__.allowEmpty', function() { return this.get('moment.__config__.allowEmpty'); }), supportsGlobalAllowEmpty: true, localeOrTimeZoneChanged: observer('moment.locale', 'moment.timeZone', function() { this.recompute(); }), compute(value, { interval }) { if (get(this, 'disableInterval')) { return; } this.clearTimer(); if (interval) { /* * NOTE: intentionally a setTimeout so tests do not block on it * as the run loop queue is never clear so tests will stay locked waiting * for queue to clear. */ this.intervalTimer = setTimeout(() => { run(() => this.recompute()); }, parseInt(interval, 10)); } }, morphMoment(time, { locale, timeZone }) { const momentService = get(this, 'moment'); locale = locale || get(momentService, 'locale'); timeZone = timeZone || get(momentService, 'timeZone'); if (locale && time.locale) { time = time.locale(locale); } if (timeZone && time.tz) { time = time.tz(timeZone); } return time; }, clearTimer() { clearTimeout(this.intervalTimer); }, destroy() { this.clearTimer(); this._super(...arguments); } });
import { run } from '@ember/runloop'; import Helper from '@ember/component/helper'; import { get, observer, computed } from '@ember/object'; import { inject as service } from '@ember/service'; export default Helper.extend({ moment: service(), disableInterval: false, globalAllowEmpty: computed.bool('moment.__config__.allowEmpty'), supportsGlobalAllowEmpty: true, localeOrTimeZoneChanged: observer('moment.locale', 'moment.timeZone', function() { this.recompute(); }), compute(value, { interval }) { if (get(this, 'disableInterval')) { return; } this.clearTimer(); if (interval) { /* * NOTE: intentionally a setTimeout so tests do not block on it * as the run loop queue is never clear so tests will stay locked waiting * for queue to clear. */ this.intervalTimer = setTimeout(() => { run(() => this.recompute()); }, parseInt(interval, 10)); } }, morphMoment(time, { locale, timeZone }) { const momentService = get(this, 'moment'); locale = locale || get(momentService, 'locale'); timeZone = timeZone || get(momentService, 'timeZone'); if (locale && time.locale) { time = time.locale(locale); } if (timeZone && time.tz) { time = time.tz(timeZone); } return time; }, clearTimer() { clearTimeout(this.intervalTimer); }, destroy() { this.clearTimer(); this._super(...arguments); } });
Add the repo name to the github package repo url see https://github.com/freefair/gradle-plugins/issues/50#issuecomment-517961934
package io.freefair.gradle.plugins.github; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; /** * @author Lars Grefer */ public class GithubPackageRegistryMavenPublishPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(MavenPublishPlugin.class); project.getPlugins().apply(GithubPomPlugin.class); GithubExtension githubExtension = project.getRootProject().getExtensions().getByType(GithubExtension.class); project.afterEvaluate(p -> p.getExtensions().getByType(PublishingExtension.class) .getRepositories() .maven(githubRepo -> { String owner = githubExtension.getOwner().get(); githubRepo.setName("GitHub " + owner + " Maven Packages"); githubRepo.setUrl("https://maven.pkg.github.com/" + githubExtension.getSlug()); if (githubExtension.getUsername().isPresent() && githubExtension.getToken().isPresent()) { githubRepo.credentials(passwordCredentials -> { passwordCredentials.setUsername(githubExtension.getUsername().get()); passwordCredentials.setPassword(githubExtension.getToken().get()); }); } })); } }
package io.freefair.gradle.plugins.github; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.publish.PublishingExtension; import org.gradle.api.publish.maven.plugins.MavenPublishPlugin; /** * @author Lars Grefer */ public class GithubPackageRegistryMavenPublishPlugin implements Plugin<Project> { @Override public void apply(Project project) { project.getPlugins().apply(MavenPublishPlugin.class); project.getPlugins().apply(GithubPomPlugin.class); GithubExtension githubExtension = project.getRootProject().getExtensions().getByType(GithubExtension.class); project.afterEvaluate(p -> p.getExtensions().getByType(PublishingExtension.class) .getRepositories() .maven(githubRepo -> { String owner = githubExtension.getOwner().get(); githubRepo.setName("GitHub " + owner + " Maven Packages"); githubRepo.setUrl("https://maven.pkg.github.com/" + owner); if (githubExtension.getUsername().isPresent() && githubExtension.getToken().isPresent()) { githubRepo.credentials(passwordCredentials -> { passwordCredentials.setUsername(githubExtension.getUsername().get()); passwordCredentials.setPassword(githubExtension.getToken().get()); }); } })); } }
Fix a typo in the comparison string which caused the test to always fail.
<?php /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ /* Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php. Related custom constants are defined in ./phpunit.xml. Example PHPUnit run command from this file's parent directory: ./vendor/bin/phpunit --testsuite apigateway-getbasepathmapping */ use PHPUnit\Framework\TestCase; use Aws\MockHandler; use Aws\Result; use Aws\ApiGateway\ApiGatewayClient; class GetBasePathMappingTest extends TestCase { public function testGetsTheBasePathMapping() { require('./Get_BasePathmapping.php'); $mock = new MockHandler(); $mock->append(new Result(array(true))); $apiGatewayClient = new ApiGatewayClient([ 'profile' => AWS_ACCOUNT_PROFILE_NAME, 'region' => AWS_REGION_ID, 'version' => API_GATEWAY_API_VERSION, 'handler' => $mock ]); $this->assertEquals(getBasePathMapping( $apiGatewayClient, API_GATEWAY_BASE_PATH, API_GATEWAY_DOMAIN_NAME ), 'The base path mapping\'s effective URI is: ' . 'https://apigateway.us-east-1.amazonaws.com/domainnames/example.com/basepathmappings/%28none%29'); } }
<?php /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ /* Relies on PHPUnit to test the functionality in ./Get_BasePathmapping.php. Related custom constants are defined in ./phpunit.xml. Example PHPUnit run command from this file's parent directory: ./vendor/bin/phpunit --testsuite apigateway-getbasepathmapping */ use PHPUnit\Framework\TestCase; use Aws\MockHandler; use Aws\Result; use Aws\ApiGateway\ApiGatewayClient; class GetBasePathMappingTest extends TestCase { public function testGetsTheBasePathMapping() { require('./Get_BasePathmapping.php'); $mock = new MockHandler(); $mock->append(new Result(array(true))); $apiGatewayClient = new ApiGatewayClient([ 'profile' => AWS_ACCOUNT_PROFILE_NAME, 'region' => AWS_REGION_ID, 'version' => API_GATEWAY_API_VERSION, 'handler' => $mock ]); $this->assertEquals(getBasePathMapping( $apiGatewayClient, API_GATEWAY_BASE_PATH, API_GATEWAY_DOMAIN_NAME ), 'The base path mapping\'s effective URI is: : ' . 'https://apigateway.us-east-1.amazonaws.com/domainnames/example.com/basepathmappings/%28none%29'); } }
Add 2 more tests to cover cases where parent node isn't `computed`
describe('lib/rules/disallow-computedany', function () { var checker = global.checker({ plugins: ['./lib/index'] }); describe('not configured', function() { it('should report with undefined', function() { global.expect(function() { checker.configure({disallowComputedAny: undefined}); }).to.throws(/requires a true value/i); }); it('should report with an object', function() { global.expect(function() { checker.configure({disallowComputedAny: {}}); }).to.throws(/requires a true value/i); }); }); describe('with true', function() { checker.rules({disallowComputedAny: true}); checker.cases([ /* jshint ignore:start */ { it: 'should not report Ember.computed.or()', code: function() { var Hamster = Ember.Object.extend({ hasClothes: Ember.computed.or('hat', 'shirt') }); } }, { it: 'should not report Foo.any()', code: function() { var Hamster = Ember.Object.extend({ hasClothes: Foo.any('hat', 'shirt') }); } }, { it: 'should not report Ember.notathing.any()', code: function() { var Hamster = Ember.Object.extend({ hasClothes: Ember.notathing.any('hat', 'shirt') }); } }, { it: 'should report Ember.computed.any()', errors: 1, code: function() { var Hamster = Ember.Object.extend({ hasClothes: Ember.computed.any('hat', 'shirt') }); } } /* jshint ignore:end */ ]); }); });
describe('lib/rules/disallow-computedany', function () { var checker = global.checker({ plugins: ['./lib/index'] }); describe('not configured', function() { it('should report with undefined', function() { global.expect(function() { checker.configure({disallowComputedAny: undefined}); }).to.throws(/requires a true value/i); }); it('should report with an object', function() { global.expect(function() { checker.configure({disallowComputedAny: {}}); }).to.throws(/requires a true value/i); }); }); describe('with true', function() { checker.rules({disallowComputedAny: true}); checker.cases([ /* jshint ignore:start */ { it: 'should not report Ember.computed.or()', code: function() { var Hamster = Ember.Object.extend({ hasClothes: Ember.computed.or('hat', 'shirt') }); } }, { it: 'should report Ember.computed.any()', errors: 1, code: function() { var Hamster = Ember.Object.extend({ hasClothes: Ember.computed.any('hat', 'shirt') }); } } /* jshint ignore:end */ ]); }); });
:bug: Abort clickoutside for null target
function getTest(el) { if (Array.isArray(el)) { return target => el.includes(target); } if (typeof el === 'function') { return target => el(target); } return target => target === el; } export default function clickOutside(el, fn) { const test = getTest(el); function onClickOutside(event) { let target = event.target; let inside = false; while (target && target !== document.body) { if (test(target)) { event.stopImmediatePropagation(); inside = true; break; } target = target.parentNode; } if (!inside) { fn(event); } } function onTouchOutside(event) { document.body.removeEventListener('click', onClickOutside); onClickOutside(event); } function destroy() { document.body.removeEventListener('click', onClickOutside); document.body.removeEventListener('touchstart', onTouchOutside); } destroy(); document.body.addEventListener('click', onClickOutside); document.body.addEventListener('touchstart', onTouchOutside); return { destroy }; }
function getTest(el) { if (Array.isArray(el)) { return target => el.includes(target); } if (typeof el === 'function') { return target => el(target); } return target => target === el; } export default function clickOutside(el, fn) { const test = getTest(el); function onClickOutside(event) { let target = event.target; let inside = false; while (target !== document.body) { if (test(target)) { event.stopImmediatePropagation(); inside = true; break; } target = target.parentNode; } if (!inside) { fn(event); } } function onTouchOutside(event) { document.body.removeEventListener('click', onClickOutside); onClickOutside(event); } function destroy() { document.body.removeEventListener('click', onClickOutside); document.body.removeEventListener('touchstart', onTouchOutside); } destroy(); document.body.addEventListener('click', onClickOutside); document.body.addEventListener('touchstart', onTouchOutside); return { destroy }; }
Normalize check email step errors
'use strict'; const AccountManager = require('../account-manager'); const {handleResponseData} = require('../utils'); module.exports = class CheckEmail { constructor({name, retryStep} = {}) { this.name = name; this.retryStep = retryStep; } start(data) { return AccountManager.checkEmail(data) .then(resp => Promise.all([ Promise.resolve(resp.statusCode), handleResponseData(resp), ])) .then(([status, raw]) => { const json = status === 200 ? {} : JSON.parse(raw); switch (status) { case 200: return { email: data.email, invalid: false, exists: false, hasPassword: false, reason: null, }; case 403: case 404: case 409: if (json.email_invalid) { const err = new Error(json.fail_reason); err.data = { email: data.email, invalid: json.email_invalid, exists: json.account_exists, hasPassword: json.has_password, reason: json.fail_reason, }; throw err; } else { return { email: data.email, invalid: json.email_invalid, exists: json.account_exists, hasPassword: json.has_password, reason: json.fail_reason, }; } case 500: { const err = new Error('Server error while checking email'); err.data = { email: data.email, }; throw err; } } return undefined; }); } };
'use strict'; const AccountManager = require('../account-manager'); const {handleResponseData} = require('../utils'); module.exports = class CheckEmail { constructor({name, retryStep} = {}) { this.name = name; this.retryStep = retryStep; } start(data) { return AccountManager.checkEmail(data) .then(resp => Promise.all([ Promise.resolve(resp.statusCode), handleResponseData(resp), ])) .then(([status, raw]) => { const json = status === 200 ? {} : JSON.parse(raw); switch (status) { case 200: return { email: data.email, invalid: false, exists: false, hasPassword: false, reason: null, }; case 403: case 404: case 409: if (json.email_invalid) { const err = new Error(json.fail_reason); err.data = { email: data.email, invalid: json.email_invalid, exists: json.account_exists, hasPassword: json.has_password, reason: json.fail_reason, }; throw err; } else { return { email: data.email, invalid: json.email_invalid, exists: json.account_exists, hasPassword: json.has_password, reason: json.fail_reason, }; } case 500: throw new Error('Server error while checking email'); } return undefined; }); } };
Revert "Assign quality values when checking MIME types" This reverts commit b06842f3d5dea138f2962f91105926d889157773.
from __future__ import unicode_literals from flask import Request class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] @property def _known_mimetypes(self): return self._json_mimetypes + \ self._html_mimetypes + \ self._xml_mimetypes + \ self._rss_mimetypes @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
from __future__ import unicode_literals from flask import Request from itertools import repeat, chain class AcceptRequest(Request): _json_mimetypes = ['application/json',] _html_mimetypes = ['text/html', 'application/xhtml+xml'] _xml_mimetypes = ['application/xml', 'text/xml'] _rss_mimetypes = ['application/rss+xml', 'application/rdf+xml'] _known_mimetypes = list(chain( zip(_html_mimetypes, repeat(0.9)), zip(_json_mimetypes, repeat(0.8)), zip(_xml_mimetypes, repeat(0.8)), zip(_rss_mimetypes, repeat(0.7)), )) @property def is_json(self): if 'fmt' in self.values: return self.values['fmt'] == 'json' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._json_mimetypes @property def is_xml(self): if 'fmt' in self.values: return self.values['fmt'] == 'xml' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._xml_mimetypes @property def is_rss(self): if self.path.endswith('rss.xml'): return True if 'fmt' in self.values: return self.values['fmt'] == 'rss' return self.accept_mimetypes.best_match(self._known_mimetypes) in \ self._rss_mimetypes
Add published year to title
(function (env) { "use strict"; env.ddg_spice_arxiv = function(api_result){ if (!api_result) { return Spice.failed('arxiv'); } Spice.add({ id: "arxiv", name: "Reference", data: api_result, meta: { sourceName: "arxiv.org", sourceUrl: api_result.feed.entry.link[0].href }, normalize: function(item) { return { title: sprintf( "%s (%s)", item.feed.entry.title.text, item.feed.entry.published.text.replace( /^(\d{4}).*/, "$1" ) ), url: item.feed.entry.link[0].href, subtitle: item.feed.entry.author.map( function(e) { return e.name.text; } ).join(', '), description: item.feed.entry.summary.text }; }, templates: { group: 'info', options: { moreAt: true } } }); }; }(this));
(function (env) { "use strict"; env.ddg_spice_arxiv = function(api_result){ if (!api_result) { return Spice.failed('arxiv'); } Spice.add({ id: "arxiv", name: "Reference", data: api_result, meta: { sourceName: "arxiv.org", sourceUrl: api_result.feed.entry.link[0].href }, normalize: function(item) { return { title: item.feed.entry.title.text, url: item.feed.entry.link[0].href, subtitle: item.feed.entry.author.map( function(e) { return e.name.text; } ).join(', '), description: item.feed.entry.summary.text }; }, templates: { group: 'info', options: { moreAt: true } } }); }; }(this));
Update to reflect new create_app signature
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") app = annotator.create_app() annotator.create_all(app) print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with app.test_request_context(): db = app.extensions['sqlalchemy'].db print("\nCreating admin user... ", end="") u = User(username, email, password) db.session.add(u) db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id db.session.add(c) db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
from __future__ import print_function from getpass import getpass import readline import sys import annotator from annotator.model import Consumer, User if __name__ == '__main__': r = raw_input("This program will perform initial setup of the annotation \n" "store, and create the required admin accounts. Proceed? [Y/n] ") if r and r[0] in ['n', 'N']: sys.exit(1) print("\nCreating SQLite database and ElasticSearch indices... ", end="") annotator.create_app() annotator.create_all() print("done.\n") username = raw_input("Admin username [admin]: ").strip() if not username: username = 'admin' email = '' while not email: email = raw_input("Admin email: ").strip() password = '' while not password: password = getpass("Admin password: ") ckey = raw_input("Primary consumer key [annotateit]: ").strip() if not ckey: ckey = 'annotateit' with annotator.app.test_request_context(): print("\nCreating admin user... ", end="") u = User(username, email, password) annotator.db.session.add(u) annotator.db.session.commit() print("done.") print("Creating primary consumer... ", end="") c = Consumer(ckey) c.user_id = u.id annotator.db.session.add(c) annotator.db.session.commit() print("done.\n") print("Primary consumer secret: %s" % c.secret)
Change routeScript type to array (before object), and change the angular.foreach to navite javascript forEach
/** * Created by Victor Avendano on 1/10/15. * [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeScripts', ['ngRoute']); mod.directive('routeScripts', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function (scope, element) { var html = '<script ng-src="{{script}}" ng-repeat="script in routeScripts"></script>'; element.append($compile(html)(scope)); scope.routeScripts = []; $rootScope.$on('$routeChangeStart', function (e, next, current) { if(current && current.$$route && current.$$route.js){ if(!Array.isArray(current.$$route.js)){ current.$$route.js = [current.$$route.js]; } current.$$route.js.forEach(function(script, index){ scope.routeScripts.splice(index, 1); }); } if(next && next.$$route && next.$$route.js){ if(!Array.isArray(next.$$route.js)){ next.$$route.js = [next.$$route.js]; } next.$$route.js.forEach(function(script, index){ scope.routeScripts.push(script); }); } }); } }; } ]); })();
/** * Created by Victor Avendano on 1/10/15. * [email protected] */ 'use strict'; (function(){ var mod = angular.module('routeScripts', ['ngRoute']); mod.directive('routeScripts', ['$rootScope','$compile', function($rootScope, $compile){ return { restrict: 'E', link: function (scope, element) { var html = '<script ng-src="{{jsUrl}}" ng-repeat="(routeCtrl, jsUrl) in routeScripts"></script>'; element.append($compile(html)(scope)); scope.routeScripts = {}; $rootScope.$on('$routeChangeStart', function (e, next, current) { if(current && current.$$route && current.$$route.js){ if(!Array.isArray(current.$$route.js)){ current.$$route.js = [current.$$route.js]; } angular.forEach(current.$$route.js, function(script){ delete scope.routeScripts[script]; }); } if(next && next.$$route && next.$$route.js){ if(!Array.isArray(next.$$route.js)){ next.$$route.js = [next.$$route.js]; } angular.forEach(next.$$route.js, function(script){ scope.routeScripts[script] = script; }); } }); } }; } ]); })();
Set user object in session
<?php namespace Koddi\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; class AuthController { public function getLogin(Application $app) { $username = $app['request']->server->get('PHP_AUTH_USER', false); $password = $app['request']->server->get('PHP_AUTH_PW'); $user = $app['userService']->checkCredentials($username, $password); if ($user) { $app['session']->set('user', $user); return $app->redirect('/'); } $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login')); $response->setStatusCode(401, 'Please sign in.'); return $response; } public function getRegister(Application $app) { return $app['twig']->render('register.twig'); } public function postRegister(Application $app) { $username = $app['request']->request->get('username'); $password = $app['request']->request->get('password'); // Create a new user $app['userService']->addUser($username, $password); //Add response $response = new Response(); $response->setStatusCode(200, 'UserAdded'); return $response; } }
<?php namespace Koddi\Controller; use Silex\Application; use Symfony\Component\HttpFoundation\Response; class AuthController { public function getLogin(Application $app) { $username = $app['request']->server->get('PHP_AUTH_USER', false); $password = $app['request']->server->get('PHP_AUTH_PW'); $user = $app['userService']->checkCredentials($username, $password); if ($user) { $app['session']->set('user', array('userId' => $user->getId())); return $app->redirect('/'); } $response = new Response(); $response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', 'site_login')); $response->setStatusCode(401, 'Please sign in.'); return $response; } public function getRegister(Application $app) { return $app['twig']->render('register.twig'); } public function postRegister(Application $app) { $username = $app['request']->request->get('username'); $password = $app['request']->request->get('password'); // Create a new user $app['userService']->addUser($username, $password); //Add response $response = new Response(); $response->setStatusCode(200, 'UserAdded'); return $response; } }
Update package serviceprovider to support laravel 5.2
<?php namespace Benrowe\Laravel\Url; use Illuminate\Support\ServiceProvider as LaravelServiceProvider; use Blade; /** * Url Service Provider * Registers the service provider into the application IOC * * @package Benrowe\Laravel\Url */ class ServiceProvider extends LaravelServiceProvider { protected $defer; public function boot() { // blade directives Blade::directive( 'file', function ($expression) { return '<?php try { echo app(\'filesystem-url\')->url' . $expression . '; } catch (Exception $e) { } ?>'; } ); } public function register() { $this->app->singleton('filesystem-url', function ($app) { return new UrlService(config('filesystems'), $app['request']->secure()); }); $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService'); } public function provides() { return [ 'Benrowe\Laravel\Url\UrlService', 'filesystem-url' ]; } }
<?php /** * This file is part of the laravel url package. * * For the full copyright and license information, * please view the LICENSE file that was distributed with this source code. */ namespace Benrowe\Laravel\Url; use Illuminate\Support\ServiceProvider as LaravelServiceProvider; use Blade; /** * Url Service Provider * Registers the service provider into the application IOC * * @package Benrowe\Laravel\Url * @author Ben Rowe <[email protected]> * @copyright Ben Rowe <[email protected]> * @link https://github.com/benrowe/laravel-filesystem-url */ class ServiceProvider extends LaravelServiceProvider { protected $defer; public function boot() { // blade directives Blade::directive( 'file', function ($expression) { return '<?php try { echo app(\'filesystem-url\')->url' . $expression . '; } catch (Exception $e) { } ?>'; } ); } public function register() { $this->app->bindShared('filesystem-url', function ($app) { return new UrlService(config('filesystems'), $app['request']->secure()); }); $this->app->alias('filesystem-url', 'Benrowe\Laravel\Url\UrlService'); } public function provides() { return [ 'Benrowe\Laravel\Url\UrlService', 'filesystem-url' ]; } }
Fix employee form error about password hashing
from django import forms from django.contrib import admin from .models import Employee, Role class UserCreationForm(forms.ModelForm): class Meta: model = Employee fields = ('username', 'password',) def save(self, commit=True): user = super(UserCreationForm, self).save(commit=False) user.set_password(self.cleaned_data['password']) if commit: user.save() return user class RoleAdmin(admin.ModelAdmin): list_display = ("name",) class EmployeeAdmin(admin.ModelAdmin): form = UserCreationForm list_display = ("username", "first_name", "last_name", "email", 'level', 'score',) fieldsets = ( (None, {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'role', 'skype_id', 'avatar', 'categories')}), ('Personal score', {'fields': ('last_month_score', 'current_month_score', 'level', 'score')}), ('Permissions', {'fields': ('groups', 'user_permissions', 'is_superuser', 'is_staff', 'is_active',)}), ('History', {'fields': ('date_joined', 'last_login')}) ) admin.site.register(Employee, EmployeeAdmin) admin.site.register(Role, RoleAdmin)
from django.contrib import admin from .models import Employee, Role class RoleAdmin(admin.ModelAdmin): list_display = ("name",) class EmployeeAdmin(admin.ModelAdmin): list_display = ("username", "first_name", "last_name", "email", 'level', 'score',) fieldsets = ( (None, {'fields': ('username', 'email', 'password')}), ('Personal info', {'fields': ('first_name', 'last_name', 'role', 'skype_id', 'avatar', 'categories')}), ('Personal score', {'fields': ('last_month_score', 'current_month_score', 'level', 'score')}), ('Permissions', {'fields': ('groups', 'user_permissions', 'is_superuser', 'is_staff', 'is_active',)}), ('History', {'fields': ('date_joined', 'last_login')}) ) admin.site.register(Employee, EmployeeAdmin) admin.site.register(Role, RoleAdmin)
Add support for y field of a pv
''' Representation of an element @param element_type: type of the element @param length: length of the element ''' import pkg_resources from rml.exceptions import ConfigException pkg_resources.require('cothread') from cothread.catools import caget class Element(object): def __init__(self, element_type, length, **kwargs): self.element_type = element_type self.length = length self.families = set() # For storing the pv. Dictionary where keys are fields and # values are pv names self.pv = dict() def add_to_family(self, family): self.families.add(family) def get_pv(self, field, handle='readback'): """ Get pv value for the given field. Currently only supports readback handle """ if not field in self.pv: raise ConfigException("Field {0} doesn't exist.".format(field)) elif handle == 'readback': return caget(self.pv[field]) else: raise ValueError("Unknown handle {0}".format(handle)) def set_pv(self, field, pv_name): self.pv[field] = pv_name def get_type(self): return self.element_type def get_length(self): return self.length def get_families(self): return self.families
''' Representation of an element @param element_type: type of the element @param length: length of the element ''' import pkg_resources from rml.exceptions import ConfigException pkg_resources.require('cothread') from cothread.catools import caget class Element(object): def __init__(self, element_type, length, **kwargs): self.element_type = element_type self.length = length self.families = set() # Getting the pv value self.pv = kwargs.get('pv', None) self._field = {} def add_to_family(self, family): self.families.add(family) def get_pv(self, field, handle='readback'): """ Get pv value for the given field. Currently only supports readback handle """ if not field in self._field: raise ConfigException("Field {0} doesn't exist.".format(field)) elif handle == 'readback': print 'abc' return caget(self.pv) else: raise ValueError("Unknown handle {0}".format(handle)) def set_pv(self, field, pv_name): self.pv = pv_name self._field[field] = pv_name def get_type(self): return self.element_type def get_length(self): return self.length def get_families(self): return self.families
Remove window param from self-exec main function
(function ($) { 'use strict'; var partner = 'YW5kcm9pZC12M3M', build_url = function (url, params) { return url + '?' + $.param(params); }, methods = { searchMovie: function (qparam, ajaxOptions) { return this.each(function () { $(this).allocine('request', 'http://api.allocine.fr/rest/v3/search', { q: qparam, filter: 'movie', count: 5 }, ajaxOptions); }); }, getMovie: function (id, ajaxOptions) { return this.each(function () { $(this).allocine('request', 'http://api.allocine.fr/rest/v3/movie', { code: id, filter: 'movie', profile: 'large' }, ajaxOptions); }); }, request: function (url, params, ajaxOptions) { var $this = $(this), queryparams = { partner: partner, format: 'json' }; return $.ajax($.extend({ url: build_url(url, $.extend(queryparams, params)), context: $this }, ajaxOptions)); } }; $.fn.allocine = function (method) { var r; if (methods[method]) { r = methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { $.error('Method ' + method + ' does not exist on jquery.allocine'); } return r; }; }(jQuery));
(function (window, $) { 'use strict'; var partner = 'YW5kcm9pZC12M3M', build_url = function (url, params) { return url + '?' + $.param(params); }, methods = { searchMovie: function (qparam, ajaxOptions) { return this.each(function () { $(this).allocine('request', 'http://api.allocine.fr/rest/v3/search', { q: qparam, filter: 'movie', count: 5 }, ajaxOptions); }); }, getMovie: function (id, ajaxOptions) { return this.each(function () { $(this).allocine('request', 'http://api.allocine.fr/rest/v3/movie', { code: id, filter: 'movie', profile: 'large' }, ajaxOptions); }); }, request: function (url, params, ajaxOptions) { var $this = $(this), queryparams = { partner: partner, format: 'json' }; return $.ajax($.extend({ url: build_url(url, $.extend(queryparams, params)), context: $this }, ajaxOptions)); } }; $.fn.allocine = function (method) { var r; if (methods[method]) { r = methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else { $.error('Method ' + method + ' does not exist on jquery.allocine'); } return r; }; }(window, jQuery));
Move things around on the settings controller
<?hh class SettingsController extends BaseController { public static function getPath(): string { return '/settings'; } public static function getConfig(): ControllerConfig { return (new ControllerConfig()) ->setUserRoles(array(UserRole::Superuser)); } public static function get(): :xhp { $applications_open = Settings::get('applications_open'); return <div class="col-md-6 col-md-offset-3"> <form class="form" action="/settings" method="post"> <div class="panel panel-default"> <div class="panel-body"> <div class="form-group"> <div class="checkbox"> <label> <input type="checkbox" name="applications_disabled" checked={!$applications_open}/> Disable Applications </label> </div> </div> </div> </div> <button type="submit" class="btn btn-primary pull-right">Save</button> </form> </div>; } public static function post(): void { if(isset($_POST['applications_disabled'])) { Settings::set('applications_open', false); } else { Settings::set('applications_open', true); } Route::redirect('/settings'); } }
<?hh class SettingsController extends BaseController { public static function getPath(): string { return '/settings'; } public static function getConfig(): ControllerConfig { return (new ControllerConfig()) ->setUserRoles(array(UserRole::Superuser)); } public static function get(): :xhp { $applications_open = Settings::get('applications_open'); return <div class="col-md-6 col-md-offset-3"> <div class="panel panel-default"> <div class="panel-body"> <form class="form" action="/settings" method="post"> <div class="form-group"> <div class="checkbox"> <label> <input type="checkbox" name="applications_disabled" checked={!$applications_open}/> Disable Applications </label> </div> </div> <div class="form-group"> <button type="submit" class="btn btn-primary">Save</button> </div> </form> </div> </div> </div>; } public static function post(): void { if(isset($_POST['applications_disabled'])) { Settings::set('applications_open', false); } else { Settings::set('applications_open', true); } Route::redirect('/settings'); } }
Add "Table Header" (tblHeader) support for table rows (repeat row on each page, as needed).
<?php /** * This file is part of the PHP Open Doc library. * * @author Jason Morriss <[email protected]> * @since 1.0 * */ namespace PHPDOC\Document\Writer\Word2007\Formatter; use PHPDOC\Element\ElementInterface, PHPDOC\Document\Writer\Word2007\Translator, PHPDOC\Document\Writer\Exception\SaveException ; /** * Creates properties for Table <w:tbl> */ class TableRowFormatter extends Shared { /** * Property aliases */ private static $aliases = array( 'align' => 'jc', 'justify' => 'jc', 'height' => 'trHeight', 'spacing' => 'tblCellSpacing', 'skipBefore' => 'gridBefore', 'skipAfter' => 'gridAfter', 'repeat' => 'tblHeader', ); protected function initMap() { parent::initMap(self::$aliases); $this->map = array( 'cantSplit' => 'bool', 'cnfStyle' => 'decimal', // bit mask string 'gridAfter' => 'decimal', 'gridBefore' => 'decimal', 'jc' => 'align', 'tblCellSpacing' => 'tblSpacing', 'tblHeader' => 'bool', 'trHeight' => 'height', 'wAfter' => '', 'wBefore' => '', ) + $this->map; } }
<?php /** * This file is part of the PHP Open Doc library. * * @author Jason Morriss <[email protected]> * @since 1.0 * */ namespace PHPDOC\Document\Writer\Word2007\Formatter; use PHPDOC\Element\ElementInterface, PHPDOC\Document\Writer\Word2007\Translator, PHPDOC\Document\Writer\Exception\SaveException ; /** * Creates properties for Table <w:tbl> */ class TableRowFormatter extends Shared { /** * Property aliases */ private static $aliases = array( 'align' => 'jc', 'justify' => 'jc', 'height' => 'trHeight', 'spacing' => 'tblCellSpacing', 'skipBefore' => 'gridBefore', 'skipAfter' => 'gridAfter', ); protected function initMap() { parent::initMap(self::$aliases); $this->map = array( 'cantSplit' => 'bool', 'cnfStyle' => 'decimal', // bit mask string 'gridAfter' => 'decimal', 'gridBefore' => 'decimal', 'jc' => 'align', 'tblCellSpacing' => 'tblSpacing', 'tblHeader' => 'bool', 'trHeight' => 'height', 'wAfter' => '', 'wBefore' => '', ) + $this->map; } }
Add legacy slug to embedded Party on memberships
from rest_framework import serializers from parties.models import Party, PartyDescription, PartyEmblem class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PartyEmblem fields = ( "image", "description", "date_approved", "ec_emblem_id", "default", ) class PartyDescriptionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PartyDescription fields = ("description", "date_description_approved") class PartySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Party fields = ( "ec_id", "url", "name", "register", "status", "date_registered", "date_deregistered", "default_emblem", "emblems", "descriptions", "legacy_slug", ) extra_kwargs = {"url": {"lookup_field": "ec_id"}} default_emblem = PartyEmblemSerializer() emblems = PartyEmblemSerializer(many=True) descriptions = PartyDescriptionSerializer(many=True) class MinimalPartySerializer(PartySerializer): class Meta: model = Party fields = ("ec_id", "name", "legacy_slug")
from rest_framework import serializers from parties.models import Party, PartyDescription, PartyEmblem class PartyEmblemSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PartyEmblem fields = ( "image", "description", "date_approved", "ec_emblem_id", "default", ) class PartyDescriptionSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PartyDescription fields = ("description", "date_description_approved") class PartySerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Party fields = ( "ec_id", "url", "name", "register", "status", "date_registered", "date_deregistered", "default_emblem", "emblems", "descriptions", "legacy_slug", ) extra_kwargs = {"url": {"lookup_field": "ec_id"}} default_emblem = PartyEmblemSerializer() emblems = PartyEmblemSerializer(many=True) descriptions = PartyDescriptionSerializer(many=True) class MinimalPartySerializer(PartySerializer): class Meta: model = Party fields = ("ec_id", "name")
Update visitor strongCoupling unit test
<?php namespace Solidifier; use Solidifier\Analyzers\FakeAnalyzer; class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase { private $analyzer; protected function setUp() { $this->analyzer = new FakeAnalyzer(); } private function getVisitorTypes() { $types = array(); foreach($this->analyzer->getVisitors() as $traverse => $traverseVisitors) { foreach($traverseVisitors as $visitor) { $types[] = get_class($visitor); } } return $types; } private function assertHasVisitor($visitorClass) { return $this->assertContains($visitorClass, $this->getVisitorTypes()); } private function assertNotHasVisitor($visitorClass) { return $this->assertNotContains($visitorClass, $this->getVisitorTypes()); } public function testPassThru() { $handler = new ConfigurationHandler(array()); $handler->configure($this->analyzer); $this->assertHasVisitor('Solidifier\Visitors\Property\PublicAttributes'); } public function testEnable() { $values = array( 'property.public' => array('enabled' => false), 'dependency.strongCoupling' => array('enabled' => true, 'excludePatterns' => array('foo')), ); $handler = new ConfigurationHandler($values); $handler->configure($this->analyzer); $this->assertNotHasVisitor('Solidifier\Visitors\Property\PublicAttributes'); $this->assertHasVisitor('Solidifier\Visitors\DependencyInjection\StrongCoupling'); } }
<?php namespace Solidifier; use Solidifier\Analyzers\FakeAnalyzer; class ConfigurationHandlerTest extends \PHPUnit_Framework_TestCase { private $analyzer; protected function setUp() { $this->analyzer = new FakeAnalyzer(); } private function getVisitorTypes() { $types = array(); foreach($this->analyzer->getVisitors() as $traverse => $traverseVisitors) { foreach($traverseVisitors as $visitor) { $types[] = get_class($visitor); } } return $types; } private function assertHasVisitor($visitorClass) { return $this->assertContains($visitorClass, $this->getVisitorTypes()); } private function assertNotHasVisitor($visitorClass) { return $this->assertNotContains($visitorClass, $this->getVisitorTypes()); } public function testPassThru() { $handler = new ConfigurationHandler(array()); $handler->configure($this->analyzer); $this->assertHasVisitor('Solidifier\Visitors\Property\PublicAttributes'); } public function testEnable() { $values = array( 'property.public' => array('enabled' => false), 'dependency.strongCoupling' => array('enabled' => true), ); $handler = new ConfigurationHandler($values); $handler->configure($this->analyzer); $this->assertNotHasVisitor('Solidifier\Visitors\Property\PublicAttributes'); $this->assertHasVisitor('Solidifier\Visitors\DependencyInjection\StrongCoupling'); } }
Make the FetchedValue marked as for_update SQLAlchemy is currently unable to determine between a FetchedValue inside of a server_default and one inside of a server_onupdate causing the one in server_onupdate to override the func.now() in server_default. See: http://www.sqlalchemy.org/trac/ticket/2631
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from sqlalchemy.dialects import postgresql as pg from sqlalchemy.schema import FetchedValue from sqlalchemy.sql import func from sqlalchemy.sql.expression import text from warehouse import db from warehouse.database.schema import TableDDL class UUIDPrimaryKeyMixin(object): id = db.Column(pg.UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")) class TimeStampedMixin(object): __table_args__ = ( TableDDL(""" CREATE OR REPLACE FUNCTION update_modified_column() RETURNS TRIGGER AS $$ BEGIN NEW.modified = now(); RETURN NEW; END; $$ LANGUAGE 'plpgsql'; CREATE TRIGGER update_%(table)s_modtime BEFORE UPDATE ON %(table)s FOR EACH ROW EXECUTE PROCEDURE update_modified_column(); """), ) created = db.Column(db.DateTime, nullable=False, server_default=func.now()) modified = db.Column(db.DateTime, nullable=False, server_default=func.now(), server_onupdate=FetchedValue(for_update=True))
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from sqlalchemy.dialects import postgresql as pg from sqlalchemy.schema import FetchedValue from sqlalchemy.sql import func from sqlalchemy.sql.expression import text from warehouse import db from warehouse.database.schema import TableDDL class UUIDPrimaryKeyMixin(object): id = db.Column(pg.UUID(as_uuid=True), primary_key=True, server_default=text("uuid_generate_v4()")) class TimeStampedMixin(object): __table_args__ = ( TableDDL(""" CREATE OR REPLACE FUNCTION update_modified_column() RETURNS TRIGGER AS $$ BEGIN NEW.modified = now(); RETURN NEW; END; $$ LANGUAGE 'plpgsql'; CREATE TRIGGER update_%(table)s_modtime BEFORE UPDATE ON %(table)s FOR EACH ROW EXECUTE PROCEDURE update_modified_column(); """), ) created = db.Column(db.DateTime, nullable=False, server_default=func.now()) modified = db.Column(db.DateTime, nullable=False, server_default=func.now(), server_onupdate=FetchedValue())
Convert file to string before sending downstream.
'use strict'; var PluginError = require('plugin-error'), through = require('through2'), inlineCss = require('inline-css'); module.exports = function (opt) { return through.obj(function (file, enc, cb) { var self = this, _opt = JSON.parse(JSON.stringify(opt || {})); // 'url' option is required // set it automatically if not provided if (!_opt.url) { _opt.url = 'file://' + file.path; } if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new PluginError('gulp-inline-css', 'Streaming not supported')); return; } inlineCss(String(file.contents), _opt) .then(function (html) { file.contents = new Buffer(html); self.push(file); return cb(); }) .catch(function (err) { if (err) { self.emit('error', new PluginError('gulp-inline-css', err)); } }); }); };
'use strict'; var PluginError = require('plugin-error'), through = require('through2'), inlineCss = require('inline-css'); module.exports = function (opt) { return through.obj(function (file, enc, cb) { var self = this, _opt = JSON.parse(JSON.stringify(opt || {})); // 'url' option is required // set it automatically if not provided if (!_opt.url) { _opt.url = 'file://' + file.path; } if (file.isNull()) { cb(null, file); return; } if (file.isStream()) { cb(new PluginError('gulp-inline-css', 'Streaming not supported')); return; } inlineCss(file.contents, _opt) .then(function (html) { file.contents = new Buffer(String(html)); self.push(file); return cb(); }) .catch(function (err) { if (err) { self.emit('error', new PluginError('gulp-inline-css', err)); } }); }); };
[casspy] Change to console command prompt
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Cassoundra: admin-commands ~~~~~~~~~~ Module to handle special commands to control the bot once it is already running. Created by Joshua Prince, 2017 """ import discord from casspy import cassoundra async def process_input(loop): while True: command = await loop.run_in_executor(None, input) if str(command).split(" ")[0].lower() == "shutdown": return print(await handle(command)) async def handle(cmd: str) -> str: tok = cmd.split(' ') try: if tok[0].lower() == 'shutdown': return await cmd_shutdown() elif tok[0].lower() == 'say': return await cmd_say(tok[1], ' '.join(tok[2:])) else: return "Unknown command " + tok[0] + "." except IndexError: pass async def cmd_shutdown() -> str: raise KeyboardInterrupt async def cmd_say(channel: str, content: str) -> str: ch = cassoundra.client.get_channel(channel) if ch is None: return '<#{}>: I couldn\'t find that channel!'.format(channel) if ch.type == discord.ChannelType.voice: return '<#{}>: Is a voice channel.'.format(channel) await cassoundra.client.send_message(ch, content) return '<#{}>: "{}"'.format(channel, content)
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Cassoundra: admin-commands ~~~~~~~~~~ Module to handle special commands to control the bot once it is already running. Created by Joshua Prince, 2017 """ import discord from casspy import cassoundra async def process_input(loop): while True: command = await loop.run_in_executor(None, input, "> ") if str(command).split(" ")[0].lower() == "shutdown": return print(await handle(command)) async def handle(cmd: str) -> str: tok = cmd.split(' ') try: if tok[0].lower() == 'shutdown': return await cmd_shutdown() elif tok[0].lower() == 'say': return await cmd_say(tok[1], ' '.join(tok[2:])) else: return "Unknown command " + tok[0] + "." except IndexError: pass async def cmd_shutdown() -> str: raise KeyboardInterrupt async def cmd_say(channel: str, content: str) -> str: ch = cassoundra.client.get_channel(channel) if ch is None: return '<#{}>: I couldn\'t find that channel!'.format(channel) if ch.type == discord.ChannelType.voice: return '<#{}>: Is a voice channel.'.format(channel) await cassoundra.client.send_message(ch, content) return '<#{}>: "{}"'.format(channel, content)
Use tarball to match current version
import os from setuptools import setup, find_packages from wagtailmenus import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.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="wagtailmenus", version=__version__, author="Andy Babic", author_email="[email protected]", description=( "Gives you better control over the behaviour of your main menu, and " "allows you to define flat menus for output in templates."), long_description=README, packages=find_packages(), license="MIT", keywords="wagtail cms model utility", download_url="https://github.com/rkhleics/wagailmenus/tarball/1.0.0", url="https://github.com/rkhleics/wagailmenus", include_package_data=True, zip_safe=False, classifiers=[ "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", 'Topic :: Internet :: WWW/HTTP', "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], install_requires=[ "wagtail>=1.3.1", "wagtailmodeladmin>=2.5.7", ], )
import os from setuptools import setup, find_packages from wagtailmenus import __version__ with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme: README = readme.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="wagtailmenus", version=__version__, author="Andy Babic", author_email="[email protected]", description=( "Gives you better control over the behaviour of your main menu, and " "allows you to define flat menus for output in templates."), long_description=README, packages=find_packages(), license="MIT", keywords="wagtail cms model utility", download_url="https://github.com/rkhleics/wagailmenus/tarball/0.1", url="https://github.com/rkhleics/wagailmenus", include_package_data=True, zip_safe=False, classifiers=[ "Environment :: Web Environment", "Framework :: Django", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python", 'Topic :: Internet :: WWW/HTTP', "Topic :: Internet :: WWW/HTTP :: Dynamic Content", ], install_requires=[ "wagtail>=1.3.1", "wagtailmodeladmin>=2.5.7", ], )
Use `ifError` assertion instead of `equal`.
'use strict'; var grunt = require('grunt'); /** * Constructs a test case. * * @param {string} file The `package.json` file to be tested. * @param {boolean} valid Flag indicating whether the test is * expected to pass. * @param {Array} [args] Additional arguments to pass to `grunt`. * @return {function(Object)} Testing function for `nodeunit`. */ function test(file, valid, args) { return function(test) { test.expect(2); grunt.util.spawn({ grunt: true, args: [ '--gruntfile', 'test/Gruntfile.js', '--pkgFile', file ].concat(args || []).concat('npm-validate') }, function(error, result, code) { if (valid) { test.ifError(error); test.equal(code, 0); } else { test.notEqual(error, null); test.notEqual(code, 0); } test.done(); }); }; } module.exports = { empty: test('fixtures/empty.json', false), force: test('fixtures/empty.json', true, ['--force', true]), minimal: test('fixtures/minimal.json', true), package: test('../package.json', true), strict: test('fixtures/minimal.json', false, ['--strict', true]) };
'use strict'; var grunt = require('grunt'); /** * Constructs a test case. * * @param {string} file The `package.json` file to be tested. * @param {boolean} valid Flag indicating whether the test is * expected to pass. * @param {Array} [args] Additional arguments to pass to `grunt`. * @return {function(Object)} Testing function for `nodeunit`. */ function test(file, valid, args) { return function(test) { test.expect(2); grunt.util.spawn({ grunt: true, args: [ '--gruntfile', 'test/Gruntfile.js', '--pkgFile', file ].concat(args || []).concat('npm-validate') }, function(error, result, code) { if (valid) { test.equal(error, null); test.equal(code, 0); } else { test.notEqual(error, null); test.notEqual(code, 0); } test.done(); }); }; } module.exports = { empty: test('fixtures/empty.json', false), force: test('fixtures/empty.json', true, ['--force', true]), minimal: test('fixtures/minimal.json', true), package: test('../package.json', true), strict: test('fixtures/minimal.json', false, ['--strict', true]) };
Change to nameId for the userlogin test
<?php namespace AppBundle\Tests\Connections; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; /** * @file * Project: orcid * File: RepositoryTest.php */ class UserTest extends KernelTestCase { /** * @var \AppBundle\Security\User */ private $user; private $container; public function setUp() { self::bootKernel(); $this->container = self::$kernel->getContainer(); /* @var \AppBundle\Security\User $user */ $user = $this->container->get('app.user'); $user->set('eduPPN', 'phpunit'); $user->set('nameId', 'phpunit'); $user->set('displayName', 'phpunit'); $this->user = $user; } public function testLogin() { $this->user->set('nameId', null); $this->assertFalse($this->user->isLoggedIn()); $this->user->set('nameId', 'phpunit'); $this->assertTrue($this->user->isLoggedIn()); } public function testUid() { $this->assertEquals( hash('sha512', 'phpunit'), $this->user->getUid() ); } public function testDisplayName() { $this->assertEquals('phpunit', $this->user->getDisplayName()); } public function testUsername() { $this->assertEquals('phpunit', $this->user->getUsername()); } }
<?php namespace AppBundle\Tests\Connections; use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase; /** * @file * Project: orcid * File: RepositoryTest.php */ class UserTest extends KernelTestCase { /** * @var \AppBundle\Security\User */ private $user; private $container; public function setUp() { self::bootKernel(); $this->container = self::$kernel->getContainer(); /* @var \AppBundle\Security\User $user */ $user = $this->container->get('app.user'); $user->set('eduPPN', 'phpunit'); $user->set('nameId', 'phpunit'); $user->set('displayName', 'phpunit'); $this->user = $user; } public function testLogin() { $this->user->set('eduPPN', null); $this->assertFalse($this->user->isLoggedIn()); $this->user->set('eduPPN', 'phpunit'); $this->assertTrue($this->user->isLoggedIn()); $this->assertEquals('phpunit', $this->user->getDisplayName()); } public function testUid() { $this->assertEquals( hash('sha512', 'phpunit'), $this->user->getUid() ); } public function testDisplayName() { $this->assertEquals('phpunit', $this->user->getDisplayName()); } public function testUsername() { $this->assertEquals('phpunit', $this->user->getUsername()); } }
Use more precise RegExp for mixin scan
<?php namespace Jade\Lexer; /** * Class Jade\Lexer\MixinScanner. */ abstract class MixinScanner extends CaseScanner { /** * @return object */ protected function scanCall() { if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) { $this->consume($matches[0]); $token = $this->token('call', $matches[1]); // check for arguments if (preg_match('/^ *' . Scanner::PARENTHESES . '/', $this->input, $matchesArguments)) { $this->consume($matchesArguments[0]); $token->arguments = trim(substr($matchesArguments[1], 1, -1)); } return $token; } } /** * @return object */ protected function scanMixin() { if (preg_match('/^mixin +(\w[-\w]*)(?: *\((.*)\))?/', $this->input, $matches)) { $this->consume($matches[0]); $token = $this->token('mixin', $matches[1]); $token->arguments = isset($matches[2]) ? $matches[2] : null; return $token; } } }
<?php namespace Jade\Lexer; /** * Class Jade\Lexer\MixinScanner. */ abstract class MixinScanner extends CaseScanner { /** * @return object */ protected function scanCall() { if (preg_match('/^\+(\w[-\w]*)/', $this->input, $matches)) { $this->consume($matches[0]); $token = $this->token('call', $matches[1]); // check for arguments if (preg_match('/^ *\((.*?)\)/', $this->input, $matchesArguments)) { $this->consume($matchesArguments[0]); $token->arguments = $matchesArguments[1]; } return $token; } } /** * @return object */ protected function scanMixin() { if (preg_match('/^mixin +(\w[-\w]*)(?: *\((.*)\))?/', $this->input, $matches)) { $this->consume($matches[0]); $token = $this->token('mixin', $matches[1]); $token->arguments = isset($matches[2]) ? $matches[2] : null; return $token; } } }
Make UnionFind.unite return whether the operation was successful
class UnionFind(object): """A collection of distjoint sets.""" def __init__(self, n = 0): """Creates a collection of n disjoint unit sets.""" self.p = [-1]*n self.leaders = set( i for i in range(n) ) def find(self, x): """Return the identifier of a representative element for the set containing the element with identifier x.""" if self.p[x] < 0: return x self.p[x] = self.find(self.p[x]) return self.p[x] def size(self, x): """Return the number of elements in the set containing the element with identifier x.""" return -self.p[self.find(x)] def unite(self, x, y): """Unite the two sets containing the elements with identifiers x and y, respectively.""" x = self.find(x) y = self.find(y) if x == y: return False if self.size(x) > self.size(y): x,y = y,x self.p[y] += self.p[x] self.p[x] = y self.leaders.remove(x) return True def add(self): """Add a unit set containing a new element to the collection, and return the identifier of the new element.""" nid = len(self.p) self.p.append(nid) return nid
class UnionFind(object): """A collection of distjoint sets.""" def __init__(self, n = 0): """Creates a collection of n disjoint unit sets.""" self.p = [-1]*n self.leaders = set( i for i in range(n) ) def find(self, x): """Return the identifier of a representative element for the set containing the element with identifier x.""" if self.p[x] < 0: return x self.p[x] = self.find(self.p[x]) return self.p[x] def size(self, x): """Return the number of elements in the set containing the element with identifier x.""" return -self.p[self.find(x)] def unite(self, x, y): """Unite the two sets containing the elements with identifiers x and y, respectively.""" x = self.find(x) y = self.find(y) if x == y: return if self.size(x) > self.size(y): x,y = y,x self.p[y] += self.p[x] self.p[x] = y self.leaders.remove(x) def add(self): """Add a unit set containing a new element to the collection, and return the identifier of the new element.""" nid = len(self.p) self.p.append(nid) return nid
Fix email not being sent
<?php namespace App\Mail; use App\User; use App\Contact; use App\Reminder; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class UserReminded extends Mailable { use Queueable, SerializesModels; protected $reminder; protected $user; /** * Create a new message instance. * * @return void */ public function __construct(Reminder $reminder, User $user) { $this->reminder = $reminder; $this->user = $user; } /** * Build the message. * * @return $this */ public function build() { $contact = Contact::findOrFail($this->reminder->contact_id); \App::setLocale($this->user->locale); return $this->text('emails.reminder.reminder') ->subject(trans('mail.subject_line', ['contact' => $contact->getCompleteName($this->user->name_order)])) ->with([ 'contact' => $contact, 'reminder' => $this->reminder, 'user' => $this->user, ]); } }
<?php namespace App\Mail; use App\User; use App\Contact; use App\Reminder; use Illuminate\Bus\Queueable; use Illuminate\Mail\Mailable; use Illuminate\Queue\SerializesModels; use Illuminate\Contracts\Queue\ShouldQueue; class UserReminded extends Mailable { use Queueable, SerializesModels; protected $reminder; protected $user; /** * Create a new message instance. * * @return void */ public function __construct(Reminder $reminder, User $user) { $this->reminder = $reminder; $this->user = $user; } /** * Build the message. * * @return $this */ public function build() { $contact = Contact::findOrFail($this->reminder->contact_id); \App::setLocale($this->user->locale); return $this->text('emails.reminder.reminder') ->subject(trans('mail.subject_line', ['contact' => $contact->getCompleteName($this->user()->name_order)])) ->with([ 'contact' => $contact, 'reminder' => $this->reminder, 'user' => $this->user, ]); } }
Fix windows compiler not finding common.hpp
#!/usr/bin/env python import os import sys import io try: import setuptools except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, Extension from setuptools import find_packages extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"] extra_link_args = [] if os.name == 'nt' else ["-g"] platform_src = ["src/windows.cpp"] if os.name == 'nt' else [] mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms', include_dirs = ["src"], sources=['src/thinning.cpp', 'src/distance.cpp', 'src/grassfire.cpp', 'src/popcount.cpp', 'src/neighbours.cpp'] + platform_src, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args) setup( name='cv_algorithms', license='Apache license 2.0', packages=find_packages(exclude=['tests*']), install_requires=['cffi>=0.7'], ext_modules=[mod_cv_algorithms], test_suite='nose.collector', tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'], setup_requires=['nose>=1.0'], platforms="any", zip_safe=False, version='1.0.1', description='Optimized OpenCV extra algorithms for Python', url="https://github.com/ulikoehler/cv_algorithms" )
#!/usr/bin/env python import os import sys import io try: import setuptools except ImportError: from distribute_setup import use_setuptools use_setuptools() from setuptools import setup, Extension from setuptools import find_packages extra_compile_args = [] if os.name == 'nt' else ["-g", "-O2", "-march=native"] extra_link_args = [] if os.name == 'nt' else ["-g"] platform_src = ["src/windows.cpp"] if os.name == 'nt' else [] mod_cv_algorithms = Extension('cv_algorithms._cv_algorithms', sources=['src/thinning.cpp', 'src/distance.cpp', 'src/grassfire.cpp', 'src/popcount.cpp', 'src/neighbours.cpp'] + platform_src, extra_compile_args=extra_compile_args, extra_link_args=extra_link_args) setup( name='cv_algorithms', license='Apache license 2.0', packages=find_packages(exclude=['tests*']), install_requires=['cffi>=0.7'], ext_modules=[mod_cv_algorithms], test_suite='nose.collector', tests_require=['nose', 'coverage', 'mock', 'rednose', 'nose-parameterized'], setup_requires=['nose>=1.0'], platforms="any", zip_safe=False, version='1.0.0', description='Optimized OpenCV extra algorithms for Python', url="https://github.com/ulikoehler/cv_algorithms" )
Return error if user is not logged in
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array('projects' => array()); $ids = $querydata['ids']; $placeholders = implode(',', array_fill(0, count($ids), '?')); if (!isset($_SESSION)) { session_start(); } if (!isset($_SESSION['user'])) { $result['error'] = \fennecweb\ajax\listing\Projects::ERROR_NOT_LOGGED_IN; } else { $query_get_project_details = <<<EOF SELECT webuser_data_id, project FROM full_webuser_data WHERE provider = ? AND oauth_id = ? AND webuser_data_id IN ($placeholders) EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->execute( array_merge(array($_SESSION['user']['provider'], $_SESSION['user']['id']), $ids) ); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result['projects'][$row['webuser_data_id']] = $row['project']; } } return $result; } }
<?php namespace fennecweb\ajax\details; use \PDO as PDO; /** * Web Service. * Returns a project according to the project ID. */ class Projects extends \fennecweb\WebService { /** * @param $querydata[] * @returns Array $result * <code> * array('project_id': {biomfile}); * </code> */ public function execute($querydata) { $db = $this->openDbConnection($querydata); $result = array('projects' => array()); $ids = $querydata['ids']; $placeholders = implode(',', array_fill(0, count($ids), '?')); if (!isset($_SESSION)) { session_start(); } $query_get_project_details = <<<EOF SELECT webuser_data_id, project FROM full_webuser_data WHERE provider = ? AND oauth_id = ? AND webuser_data_id IN ($placeholders) EOF; $stm_get_project_details = $db->prepare($query_get_project_details); $stm_get_project_details->execute( array_merge(array($_SESSION['user']['provider'], $_SESSION['user']['id']), $ids) ); while ($row = $stm_get_project_details->fetch(PDO::FETCH_ASSOC)) { $result['projects'][$row['webuser_data_id']] = $row['project']; } return $result; } }
Improve performance (set minimongo debug to false)
import minimongo from 'minimongo-cache'; process.nextTick = setImmediate; const db = new minimongo(); db.debug = false; export default { _endpoint: null, _options: null, ddp: null, subscriptions: {}, db: db, calls: [], hasBeenConnected: false, getUrl() { return this._endpoint.substring(0, this._endpoint.indexOf('/websocket')); }, waitDdpReady(cb) { if(this.ddp) { cb(); } else { setTimeout(()=>{ this.waitDdpReady(cb); }, 10); } }, _cbs: [], onChange(cb) { this.db.on('change', cb); this.ddp.on('connected', cb); this.ddp.on('disconnected', cb); this.on('loggingIn', cb); }, offChange(cb) { this.db.off('change', cb); this.ddp.off('connected', cb); this.ddp.off('disconnected', cb); this.off('loggingIn', cb); }, on(eventName, cb) { this._cbs.push({ eventName: eventName, callback: cb }); }, off(eventName, cb) { this._cbs.splice(this._cbs.findIndex(_cb=>_cb.callback == cb && _cb.eventName == eventName), 1); }, _notifyLoggingIn() { this._cbs.map(cb=>{ if(cb.eventName=='loggingIn' && typeof cb.callback=='function') { cb.callback(); } }); } }
import minimongo from 'minimongo-cache'; process.nextTick = setImmediate; export default { _endpoint: null, _options: null, ddp: null, subscriptions: {}, db: new minimongo(), calls: [], hasBeenConnected: false, getUrl() { return this._endpoint.substring(0, this._endpoint.indexOf('/websocket')); }, waitDdpReady(cb) { if(this.ddp) { cb(); } else { setTimeout(()=>{ this.waitDdpReady(cb); }, 10); } }, _cbs: [], onChange(cb) { this.db.on('change', cb); this.ddp.on('connected', cb); this.ddp.on('disconnected', cb); this.on('loggingIn', cb); }, offChange(cb) { this.db.off('change', cb); this.ddp.off('connected', cb); this.ddp.off('disconnected', cb); this.off('loggingIn', cb); }, on(eventName, cb) { this._cbs.push({ eventName: eventName, callback: cb }); }, off(eventName, cb) { this._cbs.splice(this._cbs.findIndex(_cb=>_cb.callback == cb && _cb.eventName == eventName), 1); }, _notifyLoggingIn() { this._cbs.map(cb=>{ if(cb.eventName=='loggingIn' && typeof cb.callback=='function') { cb.callback(); } }); } }
Fix map partner SQL request
package org.lagonette.app.room.statement; public abstract class MapPartnerStatement extends Statement { // TODO Why only 87 partners returned ?? public static final String SQL = "SELECT partner.id, " + "partner.latitude, " + "partner.longitude, " + "partner.is_exchange_office, " + "partner.main_category_id, " + "main_category.icon " + "FROM partner " + "JOIN partner_metadata " + "ON partner.id = partner_metadata.partner_id " + "JOIN category AS main_category " + "ON partner.main_category_id = main_category.id " + "JOIN category_metadata AS main_category_metadata " + "ON main_category.id = main_category_metadata.category_id " + "LEFT JOIN partner_side_category " + "ON partner.id = partner_side_category.partner_id " + "LEFT JOIN category AS side_category " + "ON partner_side_category.category_id = side_category.id " + "LEFT JOIN category_metadata AS side_category_metadata " + "ON side_category.id = side_category_metadata.category_id " + "WHERE partner.name LIKE :search " + "AND partner.is_localizable <> 0 " + "GROUP BY partner.id " + "HAVING partner_metadata.is_visible + TOTAL (side_category_metadata.is_visible) > 0"; }
package org.lagonette.app.room.statement; public abstract class MapPartnerStatement extends Statement { // TODO Why only 87 partners returned ?? public static final String SQL = "SELECT partner.id, " + "partner.latitude, " + "partner.longitude, " + "partner.is_exchange_office, " + "partner.main_category_id, " + "main_category.icon " + "FROM partner " + "JOIN partner_metadata " + "ON partner.id = partner_metadata.partner_id " + "JOIN category AS main_category " + "ON partner.main_category_id = main_category.id " + "JOIN category_metadata AS main_category_metadata " + "ON main_category.id = main_category_metadata.category_id " + "LEFT JOIN partner_side_category " + "ON partner.id = partner_side_category.partner_id " + "LEFT JOIN category AS side_category " + "ON partner_side_category.category_id = side_category.id " + "LEFT JOIN category_metadata AS side_category_metadata " + "ON side_category.id = side_category_metadata.category_id " + "WHERE partner.name LIKE :search " + "AND partner.is_localizable <> 0 " + "GROUP BY partner.id " + "HAVING partner_metadata.is_visible > 0 " + "AND SUM (side_category_metadata.is_visible) > 0"; }
Add public visibility to constructors
<?php namespace Kunstmaan\DashboardBundle\Widget; use Doctrine\Common\Annotations\AnnotationReader; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\DependencyInjection\ContainerInterface; class DashboardWidget { /** * @var ContainerAwareCommand $collector */ private $command; /** * @var string $controller */ private $controller; /** * @param string $command * @param string $controller * @param \Symfony\Component\DependencyInjection\ContainerInterface $container */ public function __construct($command, $controller, ContainerInterface $container) { $this->command = new $command(); $this->command->setContainer($container); $this->controller = $controller; } /** * @return ContainerAwareCommand */ public function getCommand() { return $this->command; } public function resolvedController() { $annotationReader = new AnnotationReader(); $reflectionMethod = new \ReflectionMethod($this->controller, 'widgetAction'); $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Route) { if (empty($annotation)) { throw new \Exception("The name is not configured in the annotation"); } /** @var \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route $annotation */ return $annotation->getName(); } } throw new \Exception("There is no route annotation"); } }
<?php namespace Kunstmaan\DashboardBundle\Widget; use Doctrine\Common\Annotations\AnnotationReader; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\DependencyInjection\ContainerInterface; class DashboardWidget { /** * @var ContainerAwareCommand $collector */ private $command; /** * @var string $controller */ private $controller; /** * @param string $command * @param string $controller * @param \Symfony\Component\DependencyInjection\ContainerInterface $container */ function __construct($command, $controller, ContainerInterface $container) { $this->command = new $command(); $this->command->setContainer($container); $this->controller = $controller; } /** * @return ContainerAwareCommand */ public function getCommand() { return $this->command; } public function resolvedController() { $annotationReader = new AnnotationReader(); $reflectionMethod = new \ReflectionMethod($this->controller, 'widgetAction'); $methodAnnotations = $annotationReader->getMethodAnnotations($reflectionMethod); foreach ($methodAnnotations as $annotation) { if ($annotation instanceof Route) { if (empty($annotation)) { throw new \Exception("The name is not configured in the annotation"); } /** @var \Sensio\Bundle\FrameworkExtraBundle\Configuration\Route $annotation */ return $annotation->getName(); } } throw new \Exception("There is no route annotation"); } }
Fix text wrapping on Attendee report descriptive text
package org.kumoricon.site.report.attendees; import com.vaadin.navigator.View; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; import com.vaadin.ui.Label; import org.kumoricon.site.report.ReportView; import org.kumoricon.site.BaseView; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; @ViewScope @SpringView(name = AttendeeReportView.VIEW_NAME) public class AttendeeReportView extends BaseView implements View, ReportView { public static final String VIEW_NAME = "attendeeReport"; public static final String REQUIRED_RIGHT = "view_attendance_report"; @Autowired private AttendeeReportPresenter handler; private Button refresh = new Button("Refresh"); private Label data = new Label(); @PostConstruct public void init() { addComponent(refresh); refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this)); addComponent(data); data.setContentMode(ContentMode.HTML); handler.fetchReportData(this); setExpandRatio(data, 1f); data.setSizeFull(); data.setWidth("100%"); } @Override public void afterSuccessfulFetch(String data) { this.data.setValue(data); } public String getRequiredRight() { return REQUIRED_RIGHT; } }
package org.kumoricon.site.report.attendees; import com.vaadin.navigator.View; import com.vaadin.shared.ui.label.ContentMode; import com.vaadin.spring.annotation.SpringView; import com.vaadin.spring.annotation.ViewScope; import com.vaadin.ui.Button; import com.vaadin.ui.Label; import org.kumoricon.site.report.ReportView; import org.kumoricon.site.BaseView; import org.springframework.beans.factory.annotation.Autowired; import javax.annotation.PostConstruct; @ViewScope @SpringView(name = AttendeeReportView.VIEW_NAME) public class AttendeeReportView extends BaseView implements View, ReportView { public static final String VIEW_NAME = "attendeeReport"; public static final String REQUIRED_RIGHT = "view_attendance_report"; @Autowired private AttendeeReportPresenter handler; private Button refresh = new Button("Refresh"); private Label data = new Label(); @PostConstruct public void init() { addComponent(refresh); refresh.addClickListener((Button.ClickListener) clickEvent -> handler.fetchReportData(this)); addComponent(data); data.setContentMode(ContentMode.HTML); handler.fetchReportData(this); setExpandRatio(data, 1f); data.setSizeFull(); data.setWidthUndefined(); } @Override public void afterSuccessfulFetch(String data) { this.data.setValue(data); } public String getRequiredRight() { return REQUIRED_RIGHT; } }
Use preserved games for opening move selection
import random import pdb from defines import * class OpeningsMover(object): def __init__(self, o_mgr, game): self.o_mgr = o_mgr self.game = game def get_a_good_move(self): wins = 0 losses = 0 totals = [] colour = self.game.to_move_colour() max_rating_factor = 1 move_games = self.o_mgr.get_move_games(self.game) for mg in move_games: move, games = mg for pg in games: win_colour = pg.won_by if win_colour == colour: wins += 1 elif win_colour == opposite_colour(colour): losses += 1 # else ignore draws and unfinished games (latter shouldn't get here) move_rating = pg.get_rating(colour) # TODO: More smarts here max_rating_factor = \ max(max_rating_factor, move_rating) totals.append((move, wins, losses, max_rating_factor)) total_score = 1 # For fall through to inner filter move_scores = [] for move, wins, losses, mrf in totals: score = (mrf * (wins))/(losses or .2) move_scores.append((move, score)) total_score += score rand_val = random.random() * total_score for move, score in move_scores: if score > rand_val: return move rand_val -= score # Fall through to inner filter return None
import random import pdb from defines import * class OpeningsMover(object): def __init__(self, o_mgr, game): self.o_mgr = o_mgr self.game = game def get_a_good_move(self): wins = 0 losses = 0 totals = [] colour = self.game.to_move_colour() max_rating_factor = 1 move_games = self.o_mgr.get_move_games(self.game) for mg in move_games: move, games = mg for g in games: win_colour = g.get_won_by() if win_colour == colour: wins += 1 else: assert(win_colour == opposite_colour(colour)) losses += 1 # Calc & save the maximum rating of the players # who made this move move_player = g.get_player(colour) if move_player: max_rating_factor = \ max(max_rating_factor, move_player.rating_factor()) totals.append((move, wins, losses, max_rating_factor)) total_score = 1 # For fall through to inner filter move_scores = [] for move, wins, losses, mrf in totals: score = (mrf * (wins))/(losses or .2) move_scores.append((move, score)) total_score += score rand_val = random.random() * total_score for move, score in move_scores: if score > rand_val: return move rand_val -= score # Fall through to inner filter return None
Remove logging code from Error Controller.
<?php class ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; break; } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; } }
<?php class ErrorController extends Zend_Controller_Action { public function errorAction() { $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: // 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Page not found'; break; default: // application error $this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; break; } // Log exception, if logger available if ($log = $this->getLog()) { $log->crit($this->view->message, $errors->exception); } // conditionally display exceptions if ($this->getInvokeArg('displayExceptions') == true) { $this->view->exception = $errors->exception; } $this->view->request = $errors->request; } public function getLog() { $bootstrap = $this->getInvokeArg('bootstrap'); if (!$bootstrap->hasPluginResource('Log')) { return false; } $log = $bootstrap->getResource('Log'); return $log; } }
Optimize Performance for long lines (use mb_strcut() instead of pred_split())
<?php /* * This file is part of the eluceo/iCal package. * * (c) Markus Poerschke <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Eluceo\iCal\Util; class ComponentUtil { /** * Folds a single line. * * According to RFC 5545, all lines longer than 75 characters should be folded * * @see https://tools.ietf.org/html/rfc5545#section-5 * @see https://tools.ietf.org/html/rfc5545#section-3.1 * * @param $string * * @return array */ public static function fold($string) { $lines = []; while (strlen($string) > 0) { if (strlen($string) > 75) { $lines[] = mb_strcut($string, 0, 75, 'utf-8') . "\r\n"; $string = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8'); } else { $lines[] = $string; $string = ''; break; } } return $lines; } }
<?php /* * This file is part of the eluceo/iCal package. * * (c) Markus Poerschke <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the file LICENSE. */ namespace Eluceo\iCal\Util; class ComponentUtil { /** * Folds a single line. * * According to RFC 5545, all lines longer than 75 characters should be folded * * @see https://tools.ietf.org/html/rfc5545#section-5 * @see https://tools.ietf.org/html/rfc5545#section-3.1 * * @param $string * * @return array */ public static function fold($string) { $lines = []; while (strlen($string) > 0) { if (strlen($string) > 75) { $lines[] = mb_strcut($string, 0, 75, 'utf-8') . "\r\n"; $str = ' ' . mb_strcut($string, 75, strlen($string), 'utf-8'); } else { $lines[] = $string; $str = ''; break; } } return $lines; } }
Add processData and contentType properties to ajax call
// For testing if (typeof module !== 'undefined') { $ = require('jquery'); gebo = require('../config').gebo; FormData = require('./__mocks__/FormData'); } /** * Send a request to the gebo. The message can be sent * as FormData or JSON. * * @param object * @param FormData - optional * @param function */ var perform = function(message, form, done) { var data = {}; if (typeof form === 'object') { data = new FormData(form); } else { done = form; } Object.keys(message).forEach(function(key) { var value = message[key]; if (typeof message[key] === 'object') { value = JSON.stringify(value); } if (typeof form === 'object') { data.append(key, value); } else { data[key] = value; } }); return $.ajax({ url: gebo + '/perform', type: 'POST', data: data, processData: false, contentType: false, success: function(data) { done(); }, error: function(xhr, status, err) { done(err); }, }); }; if (typeof module !== 'undefined') { module.exports = perform; }
// For testing if (typeof module !== 'undefined') { $ = require('jquery'); gebo = require('../config').gebo; FormData = require('./__mocks__/FormData'); } /** * Send a request to the gebo. The message can be sent * as FormData or JSON. * * @param object * @param FormData - optional * @param function */ var perform = function(message, form, done) { var data = {}; if (typeof form === 'object') { data = new FormData(form); } else { done = form; } Object.keys(message).forEach(function(key) { var value = message[key]; if (typeof message[key] === 'object') { value = JSON.stringify(value); } if (typeof form === 'object') { data.append(key, value); } else { data[key] = value; } }); return $.ajax({ url: gebo + '/perform', type: 'POST', data: data, success: function(data) { done(); }, error: function(xhr, status, err) { done(err); }, }); }; if (typeof module !== 'undefined') { module.exports = perform; }
Fix more CSRF issues on login after 401s
(function() { 'use strict'; angular .module('sentryApp') .factory('authExpiredInterceptor', authExpiredInterceptor); authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector']; function authExpiredInterceptor($rootScope, $q, $injector) { var service = { responseError: responseError }; return service; function responseError(response) { // If we have an unauthorized request we redirect to the login page // Don't do this check on the account API to avoid infinite loop if (response.status === 401 && angular.isDefined(response.data.path) && response.data.path.indexOf('/api/account') === -1) { var Auth = $injector.get('Auth'); var to = $rootScope.toState; var params = $rootScope.toStateParams; Auth.logout(); if (to.name !== 'accessdenied') { Auth.storePreviousState(to.name, params); } // Fix more bad CSRF issues // var LoginService = $injector.get('LoginService'); // LoginService.open(); } return $q.reject(response); } } })();
(function() { 'use strict'; angular .module('sentryApp') .factory('authExpiredInterceptor', authExpiredInterceptor); authExpiredInterceptor.$inject = ['$rootScope', '$q', '$injector']; function authExpiredInterceptor($rootScope, $q, $injector) { var service = { responseError: responseError }; return service; function responseError(response) { // If we have an unauthorized request we redirect to the login page // Don't do this check on the account API to avoid infinite loop if (response.status === 401 && angular.isDefined(response.data.path) && response.data.path.indexOf('/api/account') === -1) { var Auth = $injector.get('Auth'); var to = $rootScope.toState; var params = $rootScope.toStateParams; Auth.logout(); if (to.name !== 'accessdenied') { Auth.storePreviousState(to.name, params); } var LoginService = $injector.get('LoginService'); LoginService.open(); } return $q.reject(response); } } })();
Use componentController to load controller
import <%= upCaseName %>Module from './<%= name %>' import <%= upCaseName %>Controller from './<%= name %>.controller'; import <%= upCaseName %>Component from './<%= name %>.component'; import <%= upCaseName %>Template from './<%= name %>.html'; const { module } = angular.mock; describe('<%= upCaseName %>', () => { beforeEach(module(<%= upCaseName %>Module)); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Controller', () => { let $componentController; beforeEach(inject((_$componentController_) => { $componentController = _$componentController_; })); it("should exist", () => { let ctrl = $componentController('<%= name %>', {}); expect(ctrl).to.exist; }); }); describe('Template', () => { // template specs // tip: use regex to ensure correct bindings are used e.g., {{ }} it('has name in template [REMOVE]', () => { expect(<%= upCaseName %>Template).to.match(/{{\s?\$ctrl\.name\s?}}/g); }); }); describe('Component', () => { // component/directive specs let component = <%= upCaseName %>Component; it('includes the intended template',() => { expect(component.template).to.equal(<%= upCaseName %>Template); }); it('invokes the right controller', () => { expect(component.controller).to.equal(<%= upCaseName %>Controller); }); }); });
import <%= upCaseName %>Module from './<%= name %>' import <%= upCaseName %>Controller from './<%= name %>.controller'; import <%= upCaseName %>Component from './<%= name %>.component'; import <%= upCaseName %>Template from './<%= name %>.html'; const { module } = angular.mock; describe('<%= upCaseName %>', () => { let $rootScope, makeController; beforeEach(module(<%= upCaseName %>Module)); beforeEach(inject((_$rootScope_) => { $rootScope = _$rootScope_; makeController = () => { return new <%= upCaseName %>Controller(); }; })); describe('Module', () => { // top-level specs: i.e., routes, injection, naming }); describe('Controller', () => { // controller specs it('has a name property [REMOVE]', () => { // erase if removing this.name from the controller let controller = makeController(); expect(controller).to.have.property('name'); }); }); describe('Template', () => { // template specs // tip: use regex to ensure correct bindings are used e.g., {{ }} it('has name in template [REMOVE]', () => { expect(<%= upCaseName %>Template).to.match(/{{\s?\$ctrl\.name\s?}}/g); }); }); describe('Component', () => { // component/directive specs let component = <%= upCaseName %>Component; it('includes the intended template',() => { expect(component.template).to.equal(<%= upCaseName %>Template); }); it('invokes the right controller', () => { expect(component.controller).to.equal(<%= upCaseName %>Controller); }); }); });
Set sensitivity of e-mail backend to 2, so notifications with 1 aren't mailed.
from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): sensitivity = 2 slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
from django.conf import settings from django.core.mail import EmailMessage from notification.backends.base import NotificationBackend class EmailBackend(NotificationBackend): slug = u'email' display_name = u'E-mail' formats = ['short.txt', 'full.txt'] def email_for_user(self, recipient): return recipient.email def should_send(self, sender, recipient, notice_type, *args, **kwargs): send = super(EmailBackend, self).should_send(sender, recipient, notice_type) return send and self.email_for_user(recipient) != '' def render_subject(self, label, context): # Strip newlines from subject return ''.join(self.render_message(label, 'notification/email_subject.txt', 'short.txt', context ).splitlines()) def send(self, sender, recipient, notice_type, context, *args, **kwargs): if not self.should_send(sender, recipient, notice_type): return False headers = kwargs.get('headers', {}) headers.setdefault('Reply-To', settings.DEFAULT_FROM_EMAIL) EmailMessage(self.render_subject(notice_type.label, context), self.render_message(notice_type.label, 'notification/email_body.txt', 'full.txt', context), kwargs.get('from_email') or settings.DEFAULT_FROM_EMAIL, [self.email_for_user(recipient)], headers=headers).send() return True
Support for RPC to work from chrome ext itself. Normally our RPC was just for the web site to the bg context but I found a need to use it in the boot stage.
/* global chrome, sauce */ (function() { 'use strict'; const hooks = {}; function addHook(system, op, callback) { const sysTable = hooks[system] || (hooks[system] = {}); sysTable[op] = callback; } addHook('storage', 'set', sauce.storage.set); addHook('storage', 'get', sauce.storage.get); addHook('ga', 'apply', async function({args, meta}) { let tracker = await sauce.ga.getTracker(this.tab.id); const url = new URL(this.url); if (!tracker) { tracker = await sauce.ga.createTracker(this.tab.id); tracker.set('hostname', url.hostname); } tracker.set('referrer', meta.referrer); tracker.set('location', url.href.split('#')[0]); tracker.set('viewportSize', `${this.tab.width}x${this.tab.height}`); const method = args.shift(); tracker[method].apply(tracker, args); }); addHook('app', 'getDetails', () => chrome.app.getDetails()); async function onMessage(msg, sender, setResponse) { try { const hook = hooks[msg.system][msg.op]; const data = await hook.call(sender, msg.data); setResponse({success: true, data}); } catch(e) { console.error('RPC Listener:', e); setResponse({ success: false, error: e.message }); } } chrome.runtime.onMessageExternal.addListener(onMessage); chrome.runtime.onMessage.addListener(onMessage); })();
/* global chrome, sauce */ (function() { 'use strict'; const hooks = {}; function addHook(system, op, callback) { const sysTable = hooks[system] || (hooks[system] = {}); sysTable[op] = callback; } addHook('storage', 'set', sauce.storage.set); addHook('storage', 'get', sauce.storage.get); addHook('ga', 'apply', async function({args, meta}) { let tracker = await sauce.ga.getTracker(this.tab.id); const url = new URL(this.url); if (!tracker) { tracker = await sauce.ga.createTracker(this.tab.id); tracker.set('hostname', url.hostname); } tracker.set('referrer', meta.referrer); tracker.set('location', url.href.split('#')[0]); tracker.set('viewportSize', `${this.tab.width}x${this.tab.height}`); const method = args.shift(); tracker[method].apply(tracker, args); }); chrome.runtime.onMessageExternal.addListener(async (msg, sender, setResponse) => { try { const hook = hooks[msg.system][msg.op]; const data = await hook.call(sender, msg.data); setResponse({success: true, data}); } catch(e) { console.error('RPC Listener:', e); setResponse({ success: false, error: e.message }); } }); })();
Use notification ID in syncWithoutDetaching
<?php namespace App\Http\Controllers\Mship; use Auth; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Session; use Redirect; class Notification extends \App\Http\Controllers\BaseController { protected $redirectTo = 'mship/notification/list'; public function postAcknowledge($notification) { $this->account->readNotifications()->syncWithoutDetaching([$notification->id]); // If this is an interrupt AND we're got no more important notifications, then let's go back! if (Session::has('force_notification_read_return_url')) { if (!Auth::user()->has_unread_important_notifications and !Auth::user()->get_unread_must_read_notifications) { return Redirect::to(Session::pull('force_notification_read_return_url')); } } return redirect($this->redirectPath()); } public function getList() { // Get all unread notifications. $unreadNotifications = $this->account->unreadNotifications; $readNotifications = $this->account->readNotifications; return $this->viewMake('mship.notification.list') ->with('unreadNotifications', $unreadNotifications) ->with('readNotifications', $readNotifications) ->with('allowedToLeave', (!Session::has('force_notification_read_return_url') or (!Auth::user()->has_unread_important_notifications and !Auth::user()->get_unread_must_read_notifications))); } }
<?php namespace App\Http\Controllers\Mship; use Auth; use Illuminate\Database\Eloquent\Relations\BelongsToMany; use Session; use Redirect; class Notification extends \App\Http\Controllers\BaseController { protected $redirectTo = 'mship/notification/list'; public function postAcknowledge($notification) { $this->account->readNotifications()->syncWithoutDetaching([$notification]); // If this is an interrupt AND we're got no more important notifications, then let's go back! if (Session::has('force_notification_read_return_url')) { if (!Auth::user()->has_unread_important_notifications and !Auth::user()->get_unread_must_read_notifications) { return Redirect::to(Session::pull('force_notification_read_return_url')); } } return redirect($this->redirectPath()); } public function getList() { // Get all unread notifications. $unreadNotifications = $this->account->unreadNotifications; $readNotifications = $this->account->readNotifications; return $this->viewMake('mship.notification.list') ->with('unreadNotifications', $unreadNotifications) ->with('readNotifications', $readNotifications) ->with('allowedToLeave', (!Session::has('force_notification_read_return_url') or (!Auth::user()->has_unread_important_notifications and !Auth::user()->get_unread_must_read_notifications))); } }
Remove config handling from threadmanager (was unused)
import Queue import signal import threading import time class ThreadManager(): """Knows how to manage dem threads""" quit = False quitting = False threads = [] def __init__(self, threads=[]): """Program entry point""" self.threads = threads self.register_signal_handlers() def register_signal_handlers(self): # Register signal handler signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) def run(self): # Main loop self.start_threads() while not self.quit: time.sleep(1) def start_threads(self): for t in self.threads: t.start() def signal_handler(self, signal, frame): """ Handle signals """ print("Caught CTRL+C / SIGKILL") if not self.quitting: self.quitting = True self.stop_threads() self.quit = True else: print("BE PATIENT!@#~!#!@#$~!`1111") def stop_threads(self): """Stops all threads and waits for them to quit""" print("Stopping threads") for thread in self.threads: thread.stop() while threading.activeCount() > 1: print("Waiting for %s threads" % threading.activeCount()) time.sleep(1) print("All threads stopped")
import Queue import signal import threading import time class ThreadManager(): """Knows how to manage dem threads""" quit = False quitting = False threads = [] def __init__(self, queue=Queue.Queue(), threads=[], config={}): """Program entry point""" # Set up queue self.queue = Queue.Queue() self.config = config self.threads = threads self.register_signal_handlers() def register_signal_handlers(self): # Register signal handler signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) def run(self): # Main loop self.start_threads() while not self.quit: time.sleep(1) def start_threads(self): for t in self.threads: t.start() def signal_handler(self, signal, frame): """ Handle signals """ print("Caught CTRL+C / SIGKILL") if not self.quitting: self.quitting = True self.stop_threads() self.quit = True else: print("BE PATIENT!@#~!#!@#$~!`1111") def stop_threads(self): """Stops all threads and waits for them to quit""" print("Stopping threads") for thread in self.threads: thread.stop() while threading.activeCount() > 1: print("Waiting for %s threads" % threading.activeCount()) time.sleep(1) print("All threads stopped")
Add failing tests for type equality
from unittest import TestCase, skip from polygraph.exceptions import PolygraphValueError from polygraph.types.basic_type import Union from polygraph.types.scalar import Float, Int, String # @skip # FIXME class UnionTypeTest(TestCase): def test_commutativity(self): self.assertEqual(Union(String, Int), Union(Int, String)) self.assertEqual(Union(String, Int, Float), Union(Float, String, Int, String)) @skip def test_associativity(self): self.assertEqual( Union(Union(String, Int), Float), Union(String, Int, Float), ) def test_pipe_operator(self): self.assertEqual( String | Int, Union(String, Int), ) @skip def test_pipe_operator_with_more_than_two_types(self): self.assertEqual( String | Int | Float, Union(String, Int, Float), ) class UnionValueTest(TestCase): def test_valid_type(self): union = String | Int self.assertEqual(union(Int(32)), Int(32)) self.assertEqual(union(String("Test")), String("Test")) def test_value_must_be_typed(self): union = String | Int with self.assertRaises(PolygraphValueError): union(32) with self.assertRaises(PolygraphValueError): union("Test") def test_value_must_have_right_type(self): union = String | Int with self.assertRaises(PolygraphValueError): union(Float(32))
from unittest import TestCase, skip from polygraph.exceptions import PolygraphValueError from polygraph.types.basic_type import Union from polygraph.types.scalar import Float, Int, String @skip # FIXME class UnionTypeTest(TestCase): def test_commutativity(self): self.assertEqual(Union(String, Int), Union(Int, String)) def test_associativity(self): self.assertEqual( Union(Union(String, Int), Float), Union(String, Int, Float), ) def test_pipe_operator(self): self.assertEqual( String | Int, Union(String, Int), ) def test_pipe_operator_with_more_than_two_types(self): self.assertEqual( String | Int | Float, Union(String, Int, Float), ) class UnionValueTest(TestCase): def test_valid_type(self): union = String | Int self.assertEqual(union(Int(32)), Int(32)) self.assertEqual(union(String("Test")), String("Test")) def test_value_must_be_typed(self): union = String | Int with self.assertRaises(PolygraphValueError): union(32) with self.assertRaises(PolygraphValueError): union("Test") def test_value_must_have_right_type(self): union = String | Int with self.assertRaises(PolygraphValueError): union(Float(32))
Make all modals buttons default to dismiss the modal
/** * Adds a marionette region to a bootstrap modal * * Copyright 2015 Ethan Smith */ var Backbone = require('backbone'), Marionette = require('backbone.marionette'), RegionModalLayout = require('./RegionModalLayout.js'), ModalButtonView = require('./ModalButtonView.js'), _ = require('underscore'); var RegionModal = Marionette.Region.extend({ el: "#modal", onShow: function(view){ this.$el.modal('show'); }, present: function(title, view, buttonSpecs) { var layout = new RegionModalLayout(), buttons = new ModalButtonView(), baseButtonSpec; baseButtonSpec = { label: 'Button', classes: 'btn-default', data: { dismiss: 'modal' }, handler: function() {} }; // Setup the layour and present `view` as the content region layout.model = new Backbone.Model({ 'title': title }); this.show(layout); layout.getRegion('content').show(view); // Setup and show buttons _.each(buttonSpecs, function(spec) { var fullSpec = _.defaults(spec, baseButtonSpec); buttons.addButton( fullSpec.label, fullSpec.classes, fullSpec.data, fullSpec.handler ); }); layout.getRegion('buttons').show(buttons); } }); module.exports = RegionModal;
/** * Adds a marionette region to a bootstrap modal * * Copyright 2015 Ethan Smith */ var Backbone = require('backbone'), Marionette = require('backbone.marionette'), RegionModalLayout = require('./RegionModalLayout.js'), ModalButtonView = require('./ModalButtonView.js'), _ = require('underscore'); var RegionModal = Marionette.Region.extend({ el: "#modal", onShow: function(view){ this.$el.modal('show'); }, present: function(title, view, buttonSpecs) { var layout = new RegionModalLayout(), buttons = new ModalButtonView(), baseButtonSpec; baseButtonSpec = { label: 'Button', classes: 'btn-default', data: {}, handler: function() {} }; // Setup the layour and present `view` as the content region layout.model = new Backbone.Model({ 'title': title }); this.show(layout); layout.getRegion('content').show(view); // Setup and show buttons _.each(buttonSpecs, function(spec) { var fullSpec = _.defaults(spec, baseButtonSpec); buttons.addButton( fullSpec.label, fullSpec.classes, fullSpec.data, fullSpec.handler ); }); layout.getRegion('buttons').show(buttons); } }); module.exports = RegionModal;
Make it possible to display no error message by setting attr errorMsg to false
angular.module('mwUI.Form') .config(function (mwValidationMessagesProvider) { mwValidationMessagesProvider.registerValidator( 'customValidation', 'mwErrorMessages.invalidInput' ); }) .directive('mwCustomErrorValidator', function (mwValidationMessages, i18n) { return { require: 'ngModel', scope: { isValid: '=mwIsValid', errorMsg: '@mwCustomErrorValidator' }, link: function (scope, elm, attr, ngModel) { ngModel.$validators.customValidation = function () { var isValid = false; if (_.isUndefined(scope.isValid)) { isValid = true; } else { isValid = scope.isValid; } return isValid; }; scope.$watch('isValid', function () { mwValidationMessages.updateMessage( 'customValidation', function () { if (scope.errorMsg && angular.isString(scope.errorMsg) && scope.errorMsg !== 'false') { return scope.errorMsg; } else if (angular.isUndefined(scope.errorMsg)) { return i18n.get('mwErrorMessages.invalidInput'); } else { return ''; } } ); ngModel.$validate(); }); } }; });
angular.module('mwUI.Form') .config(function(mwValidationMessagesProvider){ mwValidationMessagesProvider.registerValidator( 'customValidation', 'mwErrorMessages.invalidInput' ); }) .directive('mwCustomErrorValidator', function (mwValidationMessages, i18n) { return { require: 'ngModel', scope: { isValid: '=mwIsValid', errorMsg: '@mwCustomErrorValidator' }, link: function (scope, elm, attr, ngModel) { ngModel.$validators.customValidation = function () { var isValid = false; if(_.isUndefined(scope.isValid)){ isValid = true; } else { isValid = scope.isValid; } return isValid; }; scope.$watch('isValid', function(){ mwValidationMessages.updateMessage( 'customValidation', function(){ if(scope.errorMsg && angular.isString(scope.errorMsg)){ return scope.errorMsg; } else { return i18n.get('mwErrorMessages.invalidInput'); } } ); ngModel.$validate(); }); } }; });
Fix the bug where a mob can't be put back to 0
import Ember from 'ember'; import _ from 'lodash/lodash'; import steps from '../ressources/ocre-quest'; export default Ember.Component.extend({ progress: '', stepIndex: 0, target: 0, onChange: () => {}, actions: { update(item, delta) { let progress = this.get('progress'); progress = progress.split(''); progress[item.index] = item.value + delta; progress = progress.join(''); this.get('onChange')(progress, this.get('stepIndex')); } }, progressBars: Ember.computed('parsedItems', 'target', function() { const parsedItems = this.get('parsedItems'); return _.times(this.get('target'), (index) => { return _.filter(parsedItems, parsedItem => parsedItem.value > index).length / parsedItems.length; }); }), minimum: Ember.computed('progress', function() { const progress = this.get('progress'); return Math.min(..._.map(progress.split(''), number => parseInt(number, 10))); }), parsedItems: Ember.computed('progress', function() { const progress = this.get('progress'); const items = steps[this.get('stepIndex') - 1]; return _.map(items, (item, index) => { const value = parseInt(progress[index], 10); return { name: item[0], note: item[1], index: index, cantAdd: value >= 9, cantRemove: value <= 0, value: value }; }); }) });
import Ember from 'ember'; import _ from 'lodash/lodash'; import steps from '../ressources/ocre-quest'; export default Ember.Component.extend({ progress: '', stepIndex: 0, target: 0, onChange: () => {}, actions: { update(item, delta) { let progress = this.get('progress'); progress = progress.split(''); progress[item.index] = item.value + delta; progress = progress.join(''); this.get('onChange')(progress, this.get('stepIndex')); } }, progressBars: Ember.computed('parsedItems', 'target', function() { const parsedItems = this.get('parsedItems'); return _.times(this.get('target'), (index) => { return _.filter(parsedItems, parsedItem => parsedItem.value > index).length / parsedItems.length; }); }), minimum: Ember.computed('progress', function() { const progress = this.get('progress'); return Math.min(..._.map(progress.split(''), number => parseInt(number, 10))); }), parsedItems: Ember.computed('progress', function() { const progress = this.get('progress'); const items = steps[this.get('stepIndex') - 1]; return _.map(items, (item, index) => { const value = parseInt(progress[index], 10); return { name: item[0], note: item[1], index: index, cantAdd: value >= 9, cantRemove: value <= 1, value: value }; }); }) });
Use correct m2m join table name in LatestCommentsFeed git-svn-id: http://code.djangoproject.com/svn/django/trunk@9089 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --HG-- extra : convert_revision : 9ea8b1f1f4ccc068b460e76127f288742d25088e
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_user_groups WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
from django.conf import settings from django.contrib.syndication.feeds import Feed from django.contrib.sites.models import Site from django.contrib import comments class LatestCommentFeed(Feed): """Feed of latest comments on the current site.""" def title(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"%s comments" % self._site.name def link(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return "http://%s/" % (self._site.domain) def description(self): if not hasattr(self, '_site'): self._site = Site.objects.get_current() return u"Latest comments on %s" % self._site.name def items(self): qs = comments.get_model().objects.filter( site__pk = settings.SITE_ID, is_public = True, is_removed = False, ) if getattr(settings, 'COMMENTS_BANNED_USERS_GROUP', None): where = ['user_id NOT IN (SELECT user_id FROM auth_users_group WHERE group_id = %s)'] params = [settings.COMMENTS_BANNED_USERS_GROUP] qs = qs.extra(where=where, params=params) return qs.order_by('-submit_date')[:40] def item_pubdate(self, item): return item.submit_date
Use the latest openstax-accounts (0.10.0)
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = ( 'cnx-archive', 'cnx-epub', 'jinja2', 'openstax-accounts>=0.10.0', 'psycopg2', 'pyramid>=1.5', 'pyramid_multiauth', ) tests_require = [ 'webtest', ] extras_require = { 'test': tests_require, } description = """\ Application for accepting publication requests to the Connexions Archive.""" if not IS_PY3: tests_require.append('mock') setup( name='cnx-publishing', version='0.1', author='Connexions team', author_email='[email protected]', url="https://github.com/connexions/cnx-publishing", license='LGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, test_suite='cnxpublishing.tests', packages=find_packages(), include_package_data=True, package_data={ 'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'], }, entry_points="""\ [paste.app_factory] main = cnxpublishing.main:main [console_scripts] cnx-publishing-initdb = cnxpublishing.scripts.initdb:main """, )
# -*- coding: utf-8 -*- import sys from setuptools import setup, find_packages IS_PY3 = sys.version_info > (3,) install_requires = ( 'cnx-archive', 'cnx-epub', 'jinja2', 'openstax-accounts>=0.8', 'psycopg2', 'pyramid>=1.5', 'pyramid_multiauth', ) tests_require = [ 'webtest', ] extras_require = { 'test': tests_require, } description = """\ Application for accepting publication requests to the Connexions Archive.""" if not IS_PY3: tests_require.append('mock') setup( name='cnx-publishing', version='0.1', author='Connexions team', author_email='[email protected]', url="https://github.com/connexions/cnx-publishing", license='LGPL, See also LICENSE.txt', description=description, install_requires=install_requires, tests_require=tests_require, extras_require=extras_require, test_suite='cnxpublishing.tests', packages=find_packages(), include_package_data=True, package_data={ 'cnxpublishing': ['sql/*.sql', 'sql/*/*.sql'], }, entry_points="""\ [paste.app_factory] main = cnxpublishing.main:main [console_scripts] cnx-publishing-initdb = cnxpublishing.scripts.initdb:main """, )