text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Support CDATA with leading spaces
<?php declare(strict_types=1); /** * Created by PhpStorm. * User: alex * Date: 26/10/14 * Time: 00:26 */ namespace FeedIo\Rule; use FeedIo\Feed\NodeInterface; use FeedIo\RuleAbstract; class Description extends RuleAbstract { const NODE_NAME = 'description'; /** * @param NodeInterface $node * @param \DOMElement $element */ public function setProperty(NodeInterface $node, \DOMElement $element) : void { $string = ''; foreach ($element->childNodes as $childNode) { if ($childNode->nodeType == XML_CDATA_SECTION_NODE) { $string .= $childNode->textContent; } else { $string .= $element->ownerDocument->saveXML($childNode); } } $node->setDescription(htmlspecialchars_decode($string)); } /** * @inheritDoc */ protected function hasValue(NodeInterface $node) : bool { return !! $node->getDescription(); } /** * @inheritDoc */ protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void { $description = htmlspecialchars($node->getDescription()); $element = $document->createElement($this->getNodeName(), $description); if ($description !== $node->getDescription() && $this->getNodeName() != 'description') { $element->setAttribute('type', 'html'); } $rootElement->appendChild($element); } }
<?php declare(strict_types=1); /** * Created by PhpStorm. * User: alex * Date: 26/10/14 * Time: 00:26 */ namespace FeedIo\Rule; use FeedIo\Feed\NodeInterface; use FeedIo\RuleAbstract; class Description extends RuleAbstract { const NODE_NAME = 'description'; /** * @param NodeInterface $node * @param \DOMElement $element */ public function setProperty(NodeInterface $node, \DOMElement $element) : void { $string = ''; if ($element->firstChild && $element->firstChild->nodeType == XML_CDATA_SECTION_NODE) { $string = $element->firstChild->textContent; } else { foreach ($element->childNodes as $childNode) { $string .= $element->ownerDocument->saveXML($childNode); } } $node->setDescription(htmlspecialchars_decode($string)); } /** * @inheritDoc */ protected function hasValue(NodeInterface $node) : bool { return !! $node->getDescription(); } /** * @inheritDoc */ protected function addElement(\DomDocument $document, \DOMElement $rootElement, NodeInterface $node) : void { $description = htmlspecialchars($node->getDescription()); $element = $document->createElement($this->getNodeName(), $description); if ($description !== $node->getDescription() && $this->getNodeName() != 'description') { $element->setAttribute('type', 'html'); } $rootElement->appendChild($element); } }
Add a redirect message when logging out.
<?php namespace FluxBB\Web\Controllers; use FluxBB\Server\Exception\Exception; use FluxBB\Server\Exception\ValidationFailed; use FluxBB\Web\Controller; class AuthController extends Controller { public function registerForm() { return $this->view('register'); } public function register() { try { $this->execute('handle_registration', [ 'ip' => $this->request->getClientIp(), ]); return $this->redirectTo('index') ->withMessage(trans('fluxbb::register.reg_complete')); } catch (ValidationFailed $e) { return $this->redirectTo('register') ->withInput() ->withErrors($e); } } public function loginForm() { return $this->view('login'); } public function login() { try { $this->execute('handle_login'); return $this->redirectTo('index') ->withMessage(trans('fluxbb::login.message_login')); } catch (Exception $e) { return $this->redirectTo('login') ->withInput(); // TODO: With errors! } } public function logout() { $this->execute('logout'); return $this->redirectTo('index') ->withMessage('Successfully logged out.'); } public function resetForm() { // } public function reset() { // } }
<?php namespace FluxBB\Web\Controllers; use FluxBB\Server\Exception\Exception; use FluxBB\Server\Exception\ValidationFailed; use FluxBB\Web\Controller; class AuthController extends Controller { public function registerForm() { return $this->view('register'); } public function register() { try { $this->execute('handle_registration', [ 'ip' => $this->request->getClientIp(), ]); return $this->redirectTo('index') ->withMessage(trans('fluxbb::register.reg_complete')); } catch (ValidationFailed $e) { return $this->redirectTo('register') ->withInput() ->withErrors($e); } } public function loginForm() { return $this->view('login'); } public function login() { try { $this->execute('handle_login'); return $this->redirectTo('index') ->withMessage(trans('fluxbb::login.message_login')); } catch (Exception $e) { return $this->redirectTo('login') ->withInput(); // TODO: With errors! } } public function logout() { $this->execute('logout'); return $this->redirectTo('index'); } public function resetForm() { // } public function reset() { // } }
Fix SHARE capitalization, use self-referential query
from __future__ import unicode_literals import logging from django.core.management.base import BaseCommand from django.db.models import F from scripts import utils as script_utils from osf.models import PreprintService from website.preprints.tasks import on_preprint_updated logger = logging.getLogger(__name__) def update_share_preprint_modified_dates(dry_run=False): for preprint in PreprintService.objects.filter(date_modified__lt=F('node__date_modified')): if dry_run: logger.info('Would have sent ' + preprint._id + ' data to SHARE') else: on_preprint_updated(preprint._id) logger.info(preprint._id + ' data sent to SHARE') class Command(BaseCommand): """ Send more accurate preprint modified dates to SHARE (sends updates if preprint.date_modified < node.date_modified) """ def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--dry', action='store_true', dest='dry_run', help='Say how many preprint updates would be sent to SHARE', ) def handle(self, *args, **options): dry_run = options.get('dry_run', False) if not dry_run: script_utils.add_file_logger(logger, __file__) update_share_preprint_modified_dates(dry_run)
from __future__ import unicode_literals import logging from django.core.management.base import BaseCommand from scripts import utils as script_utils from osf.models import PreprintService from website.preprints.tasks import on_preprint_updated logger = logging.getLogger(__name__) def update_share_preprint_modified_dates(dry_run=False): dates_updated = 0 for preprint in PreprintService.objects.filter(): if preprint.node.date_modified > preprint.date_modified: if not dry_run: on_preprint_updated(preprint._id) dates_updated += 1 return dates_updated class Command(BaseCommand): """ Send more accurate preprint modified dates to Share (max of node.date_modified and preprint.date_modified) """ def add_arguments(self, parser): super(Command, self).add_arguments(parser) parser.add_argument( '--dry', action='store_true', dest='dry_run', help='Say how many preprint updates would be sent to share', ) def handle(self, *args, **options): dry_run = options.get('dry_run', False) if not dry_run: script_utils.add_file_logger(logger, __file__) dates_updated = update_share_preprint_modified_dates() logger.info('Sent %d new preprint modified dates to Share' % dates_updated) else: dates_updated = update_share_preprint_modified_dates(dry_run=True) logger.info('Would have sent %d new preprint modified dates to Share' % dates_updated)
Fix to Select View Template for rendering Models selected from dropdown
<dl class="dl-horizontal"> <dt> {{ $attributeTitle }} </dt> <dd> @if ($value) @if (is_scalar($value)) @if (array_key_exists($value, $options['options'])) {{ $options['options'][$value] }} @else {{ $value }} @endif @elseif (is_array($value)) @foreach ($value as $key => $value) @if (!is_scalar($value) && array_key_exists($value->{$value->getKeyName()}, $options['options'])) {{ $options['options'][$value->{$value->getKeyName()}] }} <br> @else @if (array_key_exists($value, $options['options'])) {{ $options['options'][$value] }} <br> @else {{ $value }} <br> @endif @endif @endforeach @elseif ($value instanceof \Illuminate\Database\Eloquent\Model && $optionValue = $value->getKey()) {{ $options['options'][$optionValue] }} @endif @endif </dd> </dl>
<dl class="dl-horizontal"> <dt> {{ $attributeTitle }} </dt> <dd> @if ($value) @if (is_scalar($value)) @if (array_key_exists($value, $options['options'])) {{ $options['options'][$value] }} @else {{ $value }} @endif @else @foreach ($value as $key => $value) @if (!is_scalar($value) && array_key_exists($value->{$value->getKeyName()}, $options['options'])) {{ $options['options'][$value->{$value->getKeyName()}] }} <br> @else @if (array_key_exists($value, $options['options'])) {{ $options['options'][$value] }} <br> @else {{ $value }} <br> @endif @endif @endforeach @endif @endif </dd> </dl>
Allow to use single quotes in import
'use strict'; var path = require('path'); var fs = require('fs'); var through = require('through2'); var glob = require('glob'); module.exports = function() { var process = function(filename) { var replaceString = ''; if (fs.statSync(filename).isDirectory()) { // Ignore directories start with _ if (path.basename(filename).substring(0, 1) == '_') return ''; fs.readdirSync(filename).forEach(function (file) { replaceString += process(filename + path.sep + file); }); return replaceString; } else { if (filename.substr(-4).match(/sass|scss/i)) { return '@import "' + filename + '";\n' } else { return ''; } } } var transform = function(file, env, cb) { // find all instances matching var contents = file.contents.toString('utf-8'); var reg = /@import\s+[\"']([^\"']*\*[^\"']*)[\"']/; var result; while((result = reg.exec(contents)) !== null) { var index = result.index; var sub = result[0]; var globName = result[1]; var files = glob.sync(file.base + globName); var replaceString = ''; files.forEach(function(filename){ replaceString += process(filename); }); contents = contents.replace(sub, replaceString); } file.contents = new Buffer(contents); cb(null, file); }; return through.obj(transform); };
'use strict'; var path = require('path'); var fs = require('fs'); var through = require('through2'); var glob = require('glob'); module.exports = function() { var process = function(filename) { var replaceString = ''; if (fs.statSync(filename).isDirectory()) { // Ignore directories start with _ if (path.basename(filename).substring(0, 1) == '_') return ''; fs.readdirSync(filename).forEach(function (file) { replaceString += process(filename + path.sep + file); }); return replaceString; } else { if (filename.substr(-4).match(/sass|scss/i)) { return '@import "' + filename + '";\n' } else { return ''; } } } var transform = function(file, env, cb) { // find all instances matching var contents = file.contents.toString('utf-8'); var reg = /@import\s+\"([^\"]*\*[^\"]*)\"/; var result; while((result = reg.exec(contents)) !== null) { var index = result.index; var sub = result[0]; var globName = result[1]; var files = glob.sync(file.base + globName); var replaceString = ''; files.forEach(function(filename){ replaceString += process(filename); }); contents = contents.replace(sub, replaceString); } file.contents = new Buffer(contents); cb(null, file); }; return through.obj(transform); };
Use ifPresent() to avoid calling get()
package com.suse.salt.netapi.calls.modules; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * salt.modules.state */ public class State { private State() { } public static LocalCall<Map<String, Object>> apply(List<String> mods) { return apply(mods, Optional.empty(), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(String... mods) { return apply(Arrays.asList(mods), Optional.empty(), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(List<String> mods, Optional<Map<String, Object>> pillar, Optional<Boolean> queue) { Map<String, Object> kwargs = new LinkedHashMap<>(); kwargs.put("mods", mods); pillar.ifPresent(p -> kwargs.put("pillar", p)); queue.ifPresent(q -> kwargs.put("queue", q)); return new LocalCall<>("state.apply", Optional.empty(), Optional.of(kwargs), new TypeToken<Map<String, Object>>() { }); } public static LocalCall<Object> showHighstate() { return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(), new TypeToken<Object>() { }); } }
package com.suse.salt.netapi.calls.modules; import com.suse.salt.netapi.calls.LocalCall; import com.google.gson.reflect.TypeToken; import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** * salt.modules.state */ public class State { private State() { } public static LocalCall<Map<String, Object>> apply(List<String> mods) { return apply(mods, Optional.empty(), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(String... mods) { return apply(Arrays.asList(mods), Optional.empty(), Optional.empty()); } public static LocalCall<Map<String, Object>> apply(List<String> mods, Optional<Map<String, Object>> pillar, Optional<Boolean> queue) { Map<String, Object> kwargs = new LinkedHashMap<>(); kwargs.put("mods", mods); if (pillar.isPresent()) { kwargs.put("pillar", pillar.get()); } if (queue.isPresent()) { kwargs.put("queue", queue.get()); } return new LocalCall<>("state.apply", Optional.empty(), Optional.of(kwargs), new TypeToken<Map<String, Object>>() { }); } public static LocalCall<Object> showHighstate() { return new LocalCall<>("state.show_highstate", Optional.empty(), Optional.empty(), new TypeToken<Object>() { }); } }
Fix missing service of type "IReCaptchaValidatorFactory" fixes #7 Please consider updating 1.5.x with php <5.6 syntax `->setImplement('Minetro\Forms\reCAPTCHA\IReCaptchaValidatorFactory')`
<?php namespace Minetro\Forms\reCAPTCHA; use Nette\DI\CompilerExtension; use Nette\PhpGenerator\ClassType; /** * @author Milan Felix Sulc <[email protected]> */ final class ReCaptchaExtension extends CompilerExtension { /** @var array */ private $defaults = [ 'secretKey' => NULL, 'siteKey' => NULL, ]; /** * @param mixed $secretKey */ public function __construct($secretKey = NULL) { $this->defaults['secretKey'] = $secretKey; } /** * Register services * * @return void */ public function loadConfiguration() { $config = $this->validateConfig($this->defaults); $builder = $this->getContainerBuilder(); $builder->addDefinition($this->prefix('validator')) ->setClass(ReCaptchaValidator::class, [$config['secretKey']]); $builder->addDefinition($this->prefix('validatorFactory')) ->setImplement(IReCaptchaValidatorFactory::class) ->setFactory($builder->getDefinition($this->prefix('validator'))); } /** * Decorate initialize method * * @param ClassType $class * @return void */ public function afterCompile(ClassType $class) { $config = $this->validateConfig($this->defaults); if ($config['siteKey'] != NULL) { $method = $class->getMethod('initialize'); $method->addBody(sprintf('%s::bind(?);', ReCaptchaBinding::class), [$config['siteKey']]); $method->addBody(sprintf('%s::factory(?);', ReCaptchaHolder::class), [$config['siteKey']]); } } }
<?php namespace Minetro\Forms\reCAPTCHA; use Nette\DI\CompilerExtension; use Nette\PhpGenerator\ClassType; /** * @author Milan Felix Sulc <[email protected]> */ final class ReCaptchaExtension extends CompilerExtension { /** @var array */ private $defaults = [ 'secretKey' => NULL, 'siteKey' => NULL, ]; /** * @param mixed $secretKey */ public function __construct($secretKey = NULL) { $this->defaults['secretKey'] = $secretKey; } /** * Register services * * @return void */ public function loadConfiguration() { $config = $this->validateConfig($this->defaults); $builder = $this->getContainerBuilder(); $builder->addDefinition($this->prefix('validator')) ->setClass(ReCaptchaValidator::class, [$config['secretKey']]); } /** * Decorate initialize method * * @param ClassType $class * @return void */ public function afterCompile(ClassType $class) { $config = $this->validateConfig($this->defaults); if ($config['siteKey'] != NULL) { $method = $class->getMethod('initialize'); $method->addBody(sprintf('%s::bind(?);', ReCaptchaBinding::class), [$config['siteKey']]); $method->addBody(sprintf('%s::factory(?);', ReCaptchaHolder::class), [$config['siteKey']]); } } }
Add support for beta versions to update notifier
import Npm from 'silent-npm-registry-client'; import boxen from 'boxen'; import chalk from 'chalk'; import pkg from '../package.json'; export default function() { return new Promise(function(resolve) { const params = { timeout: 1000, package: pkg.name, auth: {} }; const npm = new Npm(); const uri = 'https://registry.npmjs.org/npm'; npm.distTags.fetch(uri, params, function(err, res) { if (err) { resolve(); return; } const npmVersion = '1.2.7' || res.latest; const local = pkg.version.split('.').slice(0, 3).map(n => Number(n.split('-')[0])); const remote = npmVersion.split('.').map(n => Number(n.split('-')[0])); const beta = pkg.version.split('.')[2].split('-').length > 1; let available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (beta && !available) { available = remote[0] === local[0] && remote[1] === local[1] && remote[2] === local[2]; } if (available) { let text = `update available ${pkg.version} => ${npmVersion}`; text += `\nTo update, run ${chalk.green('npm i -g mup')}`; console.log( boxen(text, { padding: 1, margin: 1, align: 'center', borderColor: 'yellow' }) ); } resolve(); }); }); }
import Npm from 'silent-npm-registry-client'; import boxen from 'boxen'; import chalk from 'chalk'; import pkg from '../package.json'; export default function() { return new Promise(function(resolve) { const params = { timeout: 1000, package: pkg.name, auth: {} }; const npm = new Npm(); const uri = 'https://registry.npmjs.org/npm'; npm.distTags.fetch(uri, params, function(err, res) { if (err) { resolve(); return; } const npmVersion = res.latest; const local = pkg.version.split('.').map(n => Number(n)); const remote = npmVersion.split('.').map(n => Number(n)); const available = remote[0] > local[0] || remote[0] === local[0] && remote[1] > local[1] || remote[1] === local[1] && remote[2] > local[2]; if (available) { let text = `update available ${pkg.version} => ${npmVersion}`; text += `\nTo update, run ${chalk.green('npm i -g mup')}`; console.log( boxen(text, { padding: 1, margin: 1, align: 'center', borderColor: 'yellow' }) ); } resolve(); }); }); }
Increase Karma's browserNoActivityTimeout to fight timeouts in CI
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'sinon-chai', '@angular/cli'], plugins: [ require('karma-mocha'), require('karma-sinon-chai'), require('karma-mocha-clean-reporter'), require('karma-chrome-launcher'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], browserDisconnectTimeout: 30000, browserNoActivityTimeout: 30000, client: { clearContext: false }, files: [ { pattern: 'node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css', instrument: false }, ], coverageIstanbulReporter: { reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['mocha-clean'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
// Karma configuration file, see link for more information // https://karma-runner.github.io/0.13/config/configuration-file.html module.exports = function (config) { config.set({ basePath: '', frameworks: ['mocha', 'sinon-chai', '@angular/cli'], plugins: [ require('karma-mocha'), require('karma-sinon-chai'), require('karma-mocha-clean-reporter'), require('karma-chrome-launcher'), require('karma-coverage-istanbul-reporter'), require('@angular/cli/plugins/karma') ], browserDisconnectTimeout: 30000, client: { clearContext: false }, files: [ { pattern: 'node_modules/@angular/material/prebuilt-themes/deeppurple-amber.css', instrument: false }, ], coverageIstanbulReporter: { reports: ['html', 'lcovonly'], fixWebpackSourcePaths: true }, angularCli: { environment: 'dev' }, reporters: ['mocha-clean'], port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, browsers: ['Chrome'], singleRun: false }); };
Fix deoplete variable naming and conditional logic * Module-level variables should be CAPITALIZED. * if len(my_list) != 0 can be more-safely changed to "if my_list" * An empty list if falsey, a non-empty list is truthy. We're also safe from unexpected "None" values now. * Cleans up unnecessary comments that somehow made their way into the VCS at the bottom
from .base import Base COMPLETE_OUTPUTS = "g:LanguageClient_omniCompleteResults" class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.min_pattern_length = 1 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.input_pattern = r'(\.|::|->)\w*$' def gather_candidates(self, context): if context["is_async"]: outputs = self.vim.eval(COMPLETE_OUTPUTS) if outputs: context["is_async"] = False # TODO: error handling. candidates = outputs[0].get("result", []) # log(str(candidates)) return candidates else: context["is_async"] = True self.vim.command("let {} = []".format(COMPLETE_OUTPUTS)) character = (context["complete_position"] + len(context["complete_str"])) self.vim.funcs.LanguageClient_omniComplete({ "character": character, "complete_position": context["complete_position"], }) return []
from .base import Base CompleteOutputs = "g:LanguageClient_omniCompleteResults" class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = "LanguageClient" self.mark = "[LC]" self.rank = 1000 self.min_pattern_length = 1 self.filetypes = vim.eval( "get(g:, 'LanguageClient_serverCommands', {})").keys() self.input_pattern = r'(\.|::|->)\w*$' def gather_candidates(self, context): if context["is_async"]: outputs = self.vim.eval(CompleteOutputs) if len(outputs) != 0: context["is_async"] = False # TODO: error handling. candidates = outputs[0].get("result", []) # log(str(candidates)) return candidates else: context["is_async"] = True self.vim.command("let {} = []".format(CompleteOutputs)) character = (context["complete_position"] + len(context["complete_str"])) self.vim.funcs.LanguageClient_omniComplete({ "character": character, "complete_position": context["complete_position"], }) return [] # f = open("/tmp/deoplete.log", "w") # def log(message): # f.writelines([message]) # f.flush()
Fix issue where title was incorrectly used - it's name
<?php namespace Anomaly\UsersModule\Role\Table; use Anomaly\Streams\Platform\Ui\Table\TableBuilder; /** * Class RoleTableBuilder * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\UsersModule\RoleInterface\Table */ class RoleTableBuilder extends TableBuilder { /** * The table filters. * * @var array */ protected $filters = [ 'search' => [ 'fields' => [ 'name', 'slug', 'description' ] ] ]; /** * The table columns. * * @var array */ protected $columns = [ 'name', 'description' ]; /** * The table buttons. * * @var array */ protected $buttons = [ 'edit', 'permissions' => [ 'button' => 'info', 'icon' => 'lock', 'href' => 'admin/users/roles/permissions/{entry.id}' ] ]; /** * The table actions. * * @var array */ protected $actions = [ 'delete' ]; }
<?php namespace Anomaly\UsersModule\Role\Table; use Anomaly\Streams\Platform\Ui\Table\TableBuilder; /** * Class RoleTableBuilder * * @link http://pyrocms.com/ * @author PyroCMS, Inc. <[email protected]> * @author Ryan Thompson <[email protected]> * @package Anomaly\UsersModule\RoleInterface\Table */ class RoleTableBuilder extends TableBuilder { /** * The table filters. * * @var array */ protected $filters = [ 'search' => [ 'fields' => [ 'title', 'slug', 'description' ] ] ]; /** * The table columns. * * @var array */ protected $columns = [ 'name', 'description' ]; /** * The table buttons. * * @var array */ protected $buttons = [ 'edit', 'permissions' => [ 'button' => 'info', 'icon' => 'lock', 'href' => 'admin/users/roles/permissions/{entry.id}' ] ]; /** * The table actions. * * @var array */ protected $actions = [ 'delete' ]; }
Remove support for 2.4 & 2.8
/* eslint-env node */ module.exports = { scenarios: [ { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-canary', bower: { dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-default', npm: { devDependencies: {} } }, { name: 'fastboot', command: 'ember fastboot:test', npm: { devDependencies: { 'ember-source': null } } } ] };
/* eslint-env node */ module.exports = { scenarios: [ { name: 'ember-lts-2.4', bower: { dependencies: { 'ember': 'components/ember#lts-2-4' }, resolutions: { 'ember': 'lts-2-4' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-lts-2.8', bower: { dependencies: { 'ember': 'components/ember#lts-2-8' }, resolutions: { 'ember': 'lts-2-8' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-release', bower: { dependencies: { 'ember': 'components/ember#release' }, resolutions: { 'ember': 'release' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-beta', bower: { dependencies: { 'ember': 'components/ember#beta' }, resolutions: { 'ember': 'beta' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-canary', bower: { dependencies: { 'ember': 'components/ember#canary' }, resolutions: { 'ember': 'canary' } }, npm: { devDependencies: { 'ember-source': null } } }, { name: 'ember-default', npm: { devDependencies: {} } }, { name: 'fastboot', command: 'ember fastboot:test', npm: { devDependencies: { 'ember-source': null } } } ] };
Add extension_modueles to the default configuration
''' Parse CLI options ''' # Import python libs import os import copy import argparse # Import pkgcmp libs import pkgcmp.scan # Import third party libs import yaml DEFAULTS = {'cachedir': '/var/cache/pkgcmp', 'extension_modules': ''} def parse(): ''' Parse!! ''' parser = argparse.ArgumentParser(description='The pkgcmp map generator') parser.add_argument( '--cachedir', dest='cachedir', default=None, help='The location to store all the files while working') parser.add_argument( '--config', dest='config', default='/etc/pkgcmp/pkgcmp', help='The location of the pkgcmp config file') opts = parser.parse_args().__dict__ conf = config(opts['config']) for key in opts: if opts[key] is not None: conf[key] = opts[key] return conf def config(cfn): ''' Read in the config file ''' ret = copy.copy(DEFAULTS) if os.path.isfile(cfn): with open(cfn, 'r') as cfp: conf = yaml.safe_load(cfp) if isinstance(conf, dict): ret.update(conf) return ret class PkgCmp: ''' Build and run the application ''' def __init__(self): self.opts = parse() self.scan = pkgcmp.scan.Scanner(self.opts) def run(self): self.scan.run()
''' Parse CLI options ''' # Import python libs import os import copy import argparse # Import pkgcmp libs import pkgcmp.scan # Import third party libs import yaml DEFAULTS = {'cachedir': '/var/cache/pkgcmp'} def parse(): ''' Parse!! ''' parser = argparse.ArgumentParser(description='The pkgcmp map generator') parser.add_argument( '--cachedir', dest='cachedir', default=None, help='The location to store all the files while working') parser.add_argument( '--config', dest='config', default='/etc/pkgcmp/pkgcmp', help='The location of the pkgcmp config file') opts = parser.parse_args().__dict__ conf = config(opts['config']) for key in opts: if opts[key] is not None: conf[key] = opts[key] return conf def config(cfn): ''' Read in the config file ''' ret = copy.copy(DEFAULTS) if os.path.isfile(cfn): with open(cfn, 'r') as cfp: conf = yaml.safe_load(cfp) if isinstance(conf, dict): ret.update(conf) return ret class PkgCmp: ''' Build and run the application ''' def __init__(self): self.opts = parse() self.scan = pkgcmp.scan.Scanner(self.opts) def run(self): self.scan.run()
Add unit support for spacers
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * from styles import adjustUnits def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height """ elements = [] lines = data.splitlines() for line in lines: lexer = shlex.shlex(line) lexer.whitespace += ',' tokens = list(lexer) command = tokens[0] if command == 'PageBreak': if len(tokens) == 1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(adjustUnits(tokens[1]), adjustUnits(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now: # def depth(node): # if node.parent == None: # return 0 # else: # return 1 + depth(node.parent)
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (can add others on request): * PageBreak * Spacer width, height """ elements = [] lines = data.splitlines() for line in lines: lexer = shlex.shlex(line) lexer.whitespace += ',' tokens = list(lexer) command = tokens[0] if command == 'PageBreak': if len(tokens) == 1: elements.append(MyPageBreak()) else: elements.append(MyPageBreak(tokens[1])) if command == 'Spacer': elements.append(Spacer(int(tokens[1]), int(tokens[2]))) if command == 'Transition': elements.append(Transition(*tokens[1:])) return elements # Looks like this is not used anywhere now: # def depth(node): # if node.parent == None: # return 0 # else: # return 1 + depth(node.parent)
Remove url commented in google sevice.
"use strict"; (function () { angular .module("conpa") .factory("googleService", googleService); googleService.$inject = ["$http"]; function googleService($http) { var service = { quoteLookup: quoteLookup }; return service; function quoteLookup(query) { var url = "http://www.google.com/finance/match?" + "matchtype=matchall"; return $http.get(url, { params: { q: query } }).then(function (res) { return res.data.matches.map(function (quote) { return { symbol: quote.t, name: quote.n, exchDisp: quote.e, type: quote.id }; }); }); } } }());
"use strict"; // http://www.google.com/finance/match?matchtype=matchall&q=msft // http://www.google.com/finance/match?&q=?matchtype=matchall&q=msft (function () { angular .module("conpa") .factory("googleService", googleService); googleService.$inject = ["$http"]; function googleService($http) { var service = { quoteLookup: quoteLookup }; return service; function quoteLookup(query) { var url = "http://www.google.com/finance/match?" + "matchtype=matchall"; return $http.get(url, { params: { q: query } }).then(function (res) { return res.data.matches.map(function (quote) { return { symbol: quote.t, name: quote.n, exchDisp: quote.e, type: quote.id }; }); }); } } }());
Add new topic button to index page
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-12"> @if (! Auth::guest()) <div class="text-right"> <a href="{{ action('TopicController@create') }}"> <button type="button" class="btn btn-primary"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> New Topic </button> </a> </div> <br /> @endif <div class="panel panel-default"> <div class="panel-heading"> Home </div> <div class="panel-body"> <table class="table table-striped table-linkable table-hover"> <thead> <tr> <th class="text-center">Topic</th> <th class="text-center">Posted By</th> <th class="text-center">Posted At</th> </tr> </thead> <tbody> @foreach($topics as $topic) <tr onclick="document.location.href = '{{ action('TopicController@show', $topic->id) }}'"> <td>{{ $topic->title }}</td> <td class="text-center">{{ $topic->user->name }}</td> <td class="text-center">{{ $topic->created_at }}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> @endsection
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">Home</div> <div class="panel-body"> <table class="table table-striped table-linkable table-hover"> <thead> <tr> <th class="text-center">Topic</th> <th class="text-center">Posted By</th> <th class="text-center">Posted At</th> </tr> </thead> <tbody> @foreach($topics as $topic) <tr onclick="document.location.href = '{{ action('TopicController@show', $topic->id) }}'"> <td>{{ $topic->title }}</td> <td class="text-center">{{ $topic->user->name }}</td> <td class="text-center">{{ $topic->created_at }}</td> </tr> @endforeach </tbody> </table> </div> </div> </div> </div> </div> @endsection
Add Laravel 5.5 Package Command
<?php namespace meesoverdevest\wp_on_laravel; use Illuminate\Support\ServiceProvider; use meesoverdevest\wp_on_laravel\Commands\InstallWordPress; class WPServiceProvider extends ServiceProvider { protected $commands = [ 'meesoverdevest\wp_on_laravel\Commands\InstallWordPress' ]; /** * Bootstrap the application services. * * @return void */ public function boot() { // // https://laravel.io/forum/09-13-2014-create-new-database-and-tables-on-the-fly // http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/ // https://laravel.com/docs/5.4/packages $this->loadMigrationsFrom(__DIR__.'/migrations'); if ($this->app->runningInConsole()) { $this->commands([ InstallWordPress::class, ]); } } /** * Register the application services. * * @return void */ public function register() { include __DIR__.'/routes.php'; // $this->commands($this->commands); $this->app->make('meesoverdevest\wp_on_laravel\controllers\WPSyncController'); } }
<?php namespace meesoverdevest\wp_on_laravel; use Illuminate\Support\ServiceProvider; use meesoverdevest\wp_on_laravel\Commands\InstallWordPress; class WPServiceProvider extends ServiceProvider { protected $commands = [ 'meesoverdevest\wp_on_laravel\Commands\InstallWordPress' ]; /** * Bootstrap the application services. * * @return void */ public function boot() { // // https://laravel.io/forum/09-13-2014-create-new-database-and-tables-on-the-fly // http://laraveldaily.com/how-to-create-a-laravel-5-package-in-10-easy-steps/ // https://laravel.com/docs/5.4/packages $this->loadMigrationsFrom(__DIR__.'/migrations'); if ($this->app->runningInConsole()) { $this->commands([ InstallWordPress::class, ]); } } /** * Register the application services. * * @return void */ public function register() { include __DIR__.'/routes.php'; $this->commands($this->commands); $this->app->make('meesoverdevest\wp_on_laravel\controllers\WPSyncController'); } }
Fix the Waypoint Details for nodes without links.
import React from 'react'; class WaypointLinks extends React.Component { constructor(props) { super(props); this.state = { link: null }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { var value = undefined; if (event.target.value) value = parseInt(event.target.value); this.setState({link: value}); } render() { const { links, value, onChange, input } = this.props; const linksTo = (input.value||[]).map(pid => { const p = links.find(ln => ln.id === pid); return <div>{p.floor} - {p.roomName}</div>}); var linkOptions = links.map(p => <option value={p.id} key={p.id}>{p.floor} - {p.roomName}</option>); return ( <div class="form-group"> <label htmlFor="linkTo">Link to other Floorplan</label> <select name="linkTo" component="select" class="form-control" onChange={this.handleChange}> <option value="">---</option> {linkOptions} </select> {this.state.link && <button type="button" class="btn btn-default" onClick={() => input.onChange([...input.value, this.state.link])}>add link</button>} {linksTo} </div> ); } } export default WaypointLinks;
import React from 'react'; class WaypointLinks extends React.Component { constructor(props) { super(props); this.state = { link: null }; this.handleChange = this.handleChange.bind(this); } handleChange(event) { var value = undefined; if (event.target.value) value = parseInt(event.target.value); this.setState({link: value}); } render() { const { links, value, onChange, input } = this.props; const linksTo = input.value.map(pid => { const p = links.find(ln => ln.id === pid); return <div>{p.floor} - {p.roomName}</div>}); var linkOptions = links.map(p => <option value={p.id} key={p.id}>{p.floor} - {p.roomName}</option>); return ( <div class="form-group"> <label htmlFor="linkTo">Link to</label> <select name="linkTo" component="select" class="form-control" onChange={this.handleChange}> <option value="">---</option> {linkOptions} </select> {this.state.link && <button type="button" class="btn btn-default" onClick={() => input.onChange([...input.value, this.state.link])}>add link</button>} {linksTo} </div> ); } } export default WaypointLinks;
Fix stop video on modal close
import React from 'react'; import PropTypes from 'prop-types'; import YTPlayer from 'youtube-player'; import styles from './Modal.scss'; const Modal = ({ title, isGallery, trailerId, children, id }) => { window.onclick = ({ target }) => { if (target.id === id) closeModal(); }; const closeModal = () => { const modal = document.getElementById(id); if (trailerId) stopVideo(); modal.style.display = 'none'; }; let player; const stopVideo = () => { if (!player) player = YTPlayer(trailerId); player.stopVideo(); }; const renderHeader = () => ( <div className={styles.Header}> <button className={styles.ButtonClose} onClick={closeModal}> <i className="fa fa-times" /> </button> <p className={styles.Title}>{title}</p> </div> ); return ( <div id={id} className={styles.Modal}> <div className={styles.Content} style={isGallery ? { padding: '30px', borderRadius: '4px' } : {}}> {title ? renderHeader() : null} {children} </div> </div> ); }; Modal.propTypes = { children: PropTypes.node.isRequired, id: PropTypes.string.isRequired, title: PropTypes.string, isGallery: PropTypes.bool, trailerId: PropTypes.string, }; Modal.defaultProps = { title: '', isGallery: false, trailerId: '' }; export default Modal;
import React from 'react'; import PropTypes from 'prop-types'; import YTPlayer from 'youtube-player'; import styles from './Modal.scss'; let player; const Modal = ({ title, isGallery, trailerId, children, id }) => { window.onclick = ({ target }) => { if (target.id === id) closeModal(); }; const closeModal = () => { const modal = document.getElementById(id); if (trailerId) stopVideo(); modal.style.display = 'none'; }; const stopVideo = () => { if (!player) player = YTPlayer(trailerId); player.stopVideo(); }; const renderHeader = () => ( <div className={styles.Header}> <button className={styles.ButtonClose} onClick={closeModal}> <i className="fa fa-times" /> </button> <p className={styles.Title}>{title}</p> </div> ); return ( <div id={id} className={styles.Modal}> <div className={styles.Content} style={isGallery ? { padding: '30px', borderRadius: '4px' } : {}}> {title ? renderHeader() : null} {children} </div> </div> ); }; Modal.propTypes = { children: PropTypes.node.isRequired, id: PropTypes.string.isRequired, title: PropTypes.string, isGallery: PropTypes.bool, trailerId: PropTypes.string, }; Modal.defaultProps = { title: '', isGallery: false, trailerId: '' }; export default Modal;
Make raw_params an optional argument in Submessage
from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params=None, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params=None): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
from . import Message class Submessage(object): need_lock_object = True def __init__(self, obj, message_id, sender, raw_params, need_lock_object=True): self.obj = obj self.sender = sender self.message_id = message_id self.raw_params = raw_params self.need_lock_object = need_lock_object super(Submessage, self).__init__() def as_message(self, parent): return Message(self.sender, self.message_id, self.raw_params, parent_message_id=parent.unique_id, message_group=parent.message_group, ) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( self.obj, message=message, defer_side_effect=True, need_lock_object=self.need_lock_object) class RecursiveSubmessage(Submessage): def __init__(self, message_id, sender, raw_params): super(RecursiveSubmessage, self).__init__( obj=None, sender=sender, message_id=message_id, raw_params=raw_params) def dispatch(self, parent_obj, parent_message): from yawf.dispatch import dispatch_message message = self.as_message(parent_message) return dispatch_message( parent_obj, message=message, defer_side_effect=True, need_lock_object=False)
Remove unused conditon which cant hold anyway
package name.abuchen.portfolio.util; public class Isin { private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$ public static final String PATTERN = "[A-Z]{2}[A-Z0-9]{9}\\d"; //$NON-NLS-1$ private Isin() { } public static final boolean isValid(String isin) // NOSONAR { if (isin == null || isin.length() != 12) return false; int sum = 0; boolean even = false; for (int ii = 11; ii >= 0; ii--) { int v = CHARACTERS.indexOf(isin.charAt(ii)); if (v < 0) return false; int digit = v % 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; if (v >= 10) { digit = v / 10 * (even ? 2 : 1); sum += digit; even = !even; } } return sum % 10 == 0; } }
package name.abuchen.portfolio.util; public class Isin { private static final String CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; //$NON-NLS-1$ public static final String PATTERN = "[A-Z]{2}[A-Z0-9]{9}\\d"; //$NON-NLS-1$ private Isin() { } public static final boolean isValid(String isin) // NOSONAR { if (isin == null || isin.length() != 12) return false; int sum = 0; boolean even = false; for (int ii = 11; ii >= 0; ii--) { int v = CHARACTERS.indexOf(isin.charAt(ii)); if (v < 0) return false; int digit = v % 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; if (v >= 10) { digit = v / 10 * (even ? 2 : 1); sum += digit > 9 ? digit - 9 : digit; even = !even; } } return sum % 10 == 0; } }
Fix bug where additional properties in objection models were not be omitted
'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const jsonSchema = this.constructor.jsonSchema; const pick = jsonSchema && jsonSchema.properties; let omit; if (!pick) { omit = this.constructor.getRelations(); } else { if (this.constructor.camelCase) { pick.createdAt = pick.updatedAt = { type: 'string', format: 'date-time' }; } else { pick.created_at = pick.updated_at = { type: 'string', format: 'date-time' }; } } return this.$$toJson(true, omit, pick); } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; };
'use strict'; // Exports export default (BaseModel) => { class Model extends BaseModel { $toDatabaseJson() { const omit = this.constructor.getRelations(); return this.$$toJson(true, omit, null); } $beforeValidate(jsonSchema, json, opt) { const schema = super.$beforeValidate(jsonSchema, json, opt); if (this.constructor.timestamps && schema && schema.properties) { if (this.constructor.camelCase) { jsonSchema.properties.createdAt = jsonSchema.properties.updatedAt = { type: 'string', format: 'date-time' }; } else { jsonSchema.properties.created_at = jsonSchema.properties.updated_at = { type: 'string', format: 'date-time' }; } } return schema; } $beforeInsert(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) { this.createdAt = datetime; this.updatedAt = datetime; } else { this.created_at = datetime; this.updated_at = datetime; } } return super.$beforeInsert(...args); } $beforeUpdate(...args) { if (this.constructor.timestamps) { const datetime = new Date().toISOString(); if (this.constructor.camelCase) this.updatedAt = datetime; else this.updated_at = datetime; } return super.$beforeUpdate(...args); } } return Model; };
Fix an issue with repeated messages in json execution output provider. git-svn-id: 555d7295f8287ebc42f8316c6775e40d702c4756@1726 3942dd89-8c5d-46d7-aeed-044bccf3e60c
import logging from flask import render_template, request, Response, redirect, flash from flask import Module, escape from flexget.webui import register_plugin, manager, BufferQueue from Queue import Empty from flask.helpers import jsonify execute = Module(__name__, url_prefix='/execute') log = logging.getLogger('ui.execute') bufferqueue = BufferQueue() @execute.route('/', methods=['POST', 'GET']) def index(): context = {'help': manager.parser.get_help()} if request.method == 'POST': options = manager.parser.parse_args(request.form.get('options', ''))[0] if manager.parser.error_msg: flash(escape(manager.parser.error_msg), 'error') context['options'] = request.form['options'] else: flash('Manual execution started.', 'success') from flexget.webui import executor executor.execute(options=options, output=bufferqueue) return render_template('execute.html', **context) @execute.route('/progress.json') def progress(): ''' Gives takes messages from the queue and exports them to JSON. ''' result = {'items': []} try: while 1: item = bufferqueue.get_nowait() if item != '\n': result['items'].append(item) bufferqueue.task_done() except Empty: pass return jsonify(result) register_plugin(execute, menu='Execute')
import logging from flask import render_template, request, Response, redirect, flash from flask import Module, escape from flexget.webui import register_plugin, manager, BufferQueue from Queue import Empty from flask.helpers import jsonify execute = Module(__name__, url_prefix='/execute') log = logging.getLogger('ui.execute') bufferqueue = BufferQueue() @execute.route('/', methods=['POST', 'GET']) def index(): context = {'help': manager.parser.get_help()} if request.method == 'POST': options = manager.parser.parse_args(request.form.get('options', ''))[0] if manager.parser.error_msg: flash(escape(manager.parser.error_msg), 'error') context['options'] = request.form['options'] else: flash('Manual execution started.', 'success') from flexget.webui import executor executor.execute(options=options, output=bufferqueue) return render_template('execute.html', **context) @execute.route('/progress.json') def progress(): ''' Gives takes messages from the queue and exports them to JSON. ''' result = {'items': []} try: while 1: item = bufferqueue.get_nowait() if item != '\n': result['items'].append(item) except Empty: pass return jsonify(result) register_plugin(execute, menu='Execute')
Store relative paths when creating a backup in a .zip file. svn path=/trunk/eXist/; revision=6315
package org.exist.backup; import java.io.*; import java.util.zip.ZipOutputStream; import java.util.zip.ZipEntry; /** * Implementation of BackupWriter that writes to a zip file. */ public class ZipWriter implements BackupWriter { private String currentPath; private ZipOutputStream out; private StringWriter contents; public ZipWriter(String zipFile, String collection) throws IOException { File file = new File(zipFile); out = new ZipOutputStream(new FileOutputStream(file)); currentPath = collection; } public Writer newContents() throws IOException { contents = new StringWriter(); return contents; } public void closeContents() throws IOException { ZipEntry entry = new ZipEntry(mkRelative(currentPath) + "/__contents__.xml"); out.putNextEntry(entry); out.write(contents.toString().getBytes("UTF-8")); out.closeEntry(); } public OutputStream newEntry(String name) throws IOException { ZipEntry entry = new ZipEntry(mkRelative(currentPath) + '/' + name); out.putNextEntry(entry); return out; } public void closeEntry() throws IOException { out.closeEntry(); } public void newCollection(String name) { currentPath = currentPath + '/' + name; } public void closeCollection() { int p = currentPath.lastIndexOf('/'); if (p > 0) currentPath = currentPath.substring(0, p); } public void close() throws IOException { out.close(); } private String mkRelative(String path) { if (path.length() > 0 && path.charAt(0) == '/') return path.substring(1); return path; } }
package org.exist.backup; import java.io.*; import java.util.zip.ZipOutputStream; import java.util.zip.ZipEntry; /** * Implementation of BackupWriter that writes to a zip file. */ public class ZipWriter implements BackupWriter { private String currentPath; private ZipOutputStream out; private StringWriter contents; public ZipWriter(String zipFile, String collection) throws IOException { File file = new File(zipFile); out = new ZipOutputStream(new FileOutputStream(file)); currentPath = collection; } public Writer newContents() throws IOException { contents = new StringWriter(); return contents; } public void closeContents() throws IOException { ZipEntry entry = new ZipEntry(currentPath + "/__contents__.xml"); out.putNextEntry(entry); out.write(contents.toString().getBytes("UTF-8")); out.closeEntry(); } public OutputStream newEntry(String name) throws IOException { ZipEntry entry = new ZipEntry(currentPath + '/' + name); out.putNextEntry(entry); return out; } public void closeEntry() throws IOException { out.closeEntry(); } public void newCollection(String name) { currentPath = currentPath + '/' + name; } public void closeCollection() { int p = currentPath.lastIndexOf('/'); if (p > 0) currentPath = currentPath.substring(0, p); } public void close() throws IOException { out.close(); } }
Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
Index the Atlas data by version and provider
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vagrant box name """ json_url = ("https://atlas.hashicorp.com/{0}/boxes/{1}/" .format(publisher, name)) request = urllib2.Request(json_url, None, {'Accept': 'application/json'}) json_file = urllib2.urlopen(request) self._data = json.loads(json_file.read()) # We need to preserve the order of the versions self._versions = tuple(v['version'] for v in self._data['versions']) # Prepare a data structure for quick lookups self._boxes = {} for v in self._data['versions']: _version = v['version'] self._boxes[_version] = {} for p in v['providers']: _provider = p['name'] self._boxes[_version][_provider] = {} self._boxes[_version][_provider]['url'] = p['url'] def versions(self): """Return a tuple with all available box versions.""" return self._versions def providers(self, version): """Return a list of providers for a specific box version.""" return self._boxes[version].keys() def url(self, version, provider): """Return the download URL for a specific box version and provider.""" return self._boxes[version][provider]['url']
from __future__ import unicode_literals, print_function import json import urllib2 class Box(object): """Downloads and parses metainformation about a Vagrant box""" def __init__(self, publisher, name): """Extract metainformation for a Vagrant box. publisher -- Atlas owner name -- Vagrant box name """ json_url = ("https://atlas.hashicorp.com/{0}/boxes/{1}/" .format(publisher, name)) request = urllib2.Request(json_url, None, {'Accept': 'application/json'}) json_file = urllib2.urlopen(request) self._data = json.loads(json_file.read()) def versions(self): """Return a tuple with all available box versions.""" return tuple(v['version'] for v in self._data['versions'] if v['status'] == 'active') def providers(self, version): """Return a list of providers for a specific box version.""" _ver = ([v for v in self._data['versions'] if v['version'] == version])[0] return [p['name'] for p in _ver['providers']] def url(self, version, provider): """Return the download URL for a specific box version and provider.""" _ver = ([v for v in self._data['versions'] if v['version'] == version])[0] return ([p for p in _ver['providers'] if p['name'] == provider])[0]['url']
Make the sprint layout a bit easier to look at
''' Create a visual representation of the various DAGs defined ''' import sys import requests import networkx as nx import matplotlib.pyplot as plt if __name__ == '__main__': g = nx.DiGraph() labels = { 'edges': {}, 'nodes': {}, } for routeKey, routeMap in requests.get(sys.argv[1]).json().iteritems(): for i, node in enumerate(routeMap['Path']): g.add_node(node['Name']) labels['nodes'][node['Name']] = node['Name'] if i - 1 >= 0: g.add_edge(routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name']) labels['edges'][(routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name'])] = (routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name']) pos = nx.drawing.spring_layout( g, scale=10.0, ) nx.draw_networkx( g, pos=pos, with_labels=True, font_size=8, ) # write out the graph plt.savefig( 'topology.png', dpi=400.0, ) plt.show() # in case people have the required libraries to make it happen
''' Create a visual representation of the various DAGs defined ''' import sys import requests import networkx as nx import matplotlib.pyplot as plt if __name__ == '__main__': g = nx.DiGraph() labels = { 'edges': {}, 'nodes': {}, } nodes = {} for routeKey, routeMap in requests.get(sys.argv[1]).json().iteritems(): for i, node in enumerate(routeMap['Path']): g.add_node(node['Name']) labels['nodes'][node['Name']] = node['Name'] if i - 1 >= 0: g.add_edge(routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name']) labels['edges'][(routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name'])] = (routeMap['Path'][i-1]['Name'], routeMap['Path'][i]['Name']) nx.draw_networkx(g, with_labels=True) # add labels #nx.draw_networkx_labels(g, pos, labels['nodes']) #nx.draw_networkx_edge_labels(g, pos, labels['edges']) # write out the graph plt.savefig( 'topology.png', dpi=400.0, ) plt.show() # in case people have the required libraries to make it happen
Add parenthesis to print statement
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils ## # Test out the cor() functionality # If NAs in the frame, they are skipped in calculation unless na.rm = F # If any categorical columns, throw an error ## import numpy as np def cor_test(): iris_h2o = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) iris_np = np.genfromtxt(pyunit_utils.locate("smalldata/iris/iris.csv"), delimiter=',', skip_header=1, usecols=(0, 1, 2, 3)) cor_np = h2o.H2OFrame(np.corrcoef(iris_np,rowvar=0)) cor_h2o = iris_h2o[0:4].cor() cor_diff = abs(cor_h2o - cor_np) print("Correlation matrix with H2O: ") print(cor_h2o) print("Correlation matrix with Numpy: ") print(cor_np) print("Correlation differences between H2O and Numpy: ") print(cor_diff) print("Max difference in correlation calculation between H2O and Numpy: ") print(cor_diff.max()) max = cor_diff.max() assert max < .006, "expected equal correlations" if __name__ == "__main__": pyunit_utils.standalone_test(cor_test) else: cor_test()
from builtins import range import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils ## # Test out the cor() functionality # If NAs in the frame, they are skipped in calculation unless na.rm = F # If any categorical columns, throw an error ## import numpy as np def cor_test(): iris_h2o = h2o.import_file(path=pyunit_utils.locate("smalldata/iris/iris.csv")) iris_np = np.genfromtxt(pyunit_utils.locate("smalldata/iris/iris.csv"), delimiter=',', skip_header=1, usecols=(0, 1, 2, 3)) cor_np = h2o.H2OFrame(np.corrcoef(iris_np,rowvar=0)) cor_h2o = iris_h2o[0:4].cor() cor_diff = abs(cor_h2o - cor_np) print("Correlation matrix with H2O: ") print cor_h2o print("Correlation matrix with Numpy: ") print cor_np print("Correlation differences between H2O and Numpy: ") print cor_diff print("Max difference in correlation calculation between H2O and Numpy: ") print cor_diff.max() max = cor_diff.max() assert max < .006, "expected equal correlations" if __name__ == "__main__": pyunit_utils.standalone_test(cor_test) else: cor_test()
Add a count to support non sequential dialog closes
import React, { Component, PureComponent } from 'react'; import PropTypes from 'prop-types'; import { getNodeFromSelector } from './util'; /** Provides an HOC component for ensuring container is non-scrollable during component lifecycle. **/ export default function withNonScrollable(Portal) { let portalVisibleCount = 0; let originalOverflow; return class NonScrollableWrapper extends (PureComponent || Component) { static propTypes = { selector: PropTypes.string }; static defaultProps = { selector: 'body' }; restoreStyle() { portalVisibleCount--; if (portalVisibleCount <= 0) { const node = getNodeFromSelector(this.props.selector); node.style.overflow = originalOverflow; } } saveStyle() { portalVisibleCount++; if (portalVisibleCount === 1) { const node = getNodeFromSelector(this.props.selector); const { style } = node; originalOverflow = style.overflow; style.overflow = 'hidden'; } } componentDidMount() { if (this.props.visible) { this.saveStyle(); } } componentWillUnmount() { if (this.props.visible) { this.restoreStyle(); } } componentWillReceiveProps(nextProps) { if (this.props.visible !== nextProps.visible) { if (nextProps.visible === false) { this.restoreStyle(); } else { this.saveStyle(); } } } render() { return <Portal {...this.props} />; } }; }
import React, { Component, PureComponent } from 'react'; import PropTypes from 'prop-types'; import { getNodeFromSelector } from './util'; /** Provides an HOC component for ensuring container is non-scrollable during component lifecycle. **/ export default function withNonScrollable(Portal) { return class NonScrollableWrapper extends (PureComponent || Component) { static propTypes = { selector: PropTypes.string }; static defaultProps = { selector: 'body' }; restoreStyle() { const node = getNodeFromSelector(this.props.selector); node.style.overflow = this.originalOverflow; } saveStyle() { const node = getNodeFromSelector(this.props.selector); const { style } = node; this.originalOverflow = style.overflow; style.overflow = 'hidden'; } componentDidMount() { if (this.props.visible) { this.saveStyle(); } } componentWillUnmount() { if (this.props.visible) { this.restoreStyle(); } } componentWillReceiveProps(nextProps) { if (this.props.visible !== nextProps.visible) { if (nextProps.visible === false) { this.restoreStyle(); } else { this.saveStyle(); } } } render() { return <Portal {...this.props} />; } }; }
Remove random bit of code I have no idea what that is doing there. It is not called from what I can tell, and the tests work without it. And it makes no sense whatsoever, create a message each time you retrieve the conversation info??!?!?!
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise PermissionDenied(_('You are not in this conversation')) return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers from rest_framework.exceptions import PermissionDenied from foodsaving.conversations.models import Conversation, ConversationMessage class ConversationSerializer(serializers.ModelSerializer): class Meta: model = Conversation fields = [ 'id', 'participants', 'created_at' ] def retrieve(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data) class ConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation', 'created_at' ] class CreateConversationMessageSerializer(serializers.ModelSerializer): class Meta: model = ConversationMessage fields = [ 'id', 'author', 'content', 'conversation' ] extra_kwargs = { 'author': { 'read_only': True } } def validate_conversation(self, conversation): if self.context['request'].user not in conversation.participants.all(): raise PermissionDenied(_('You are not in this conversation')) return conversation def create(self, validated_data): user = self.context['request'].user return ConversationMessage.objects.create(author=user, **validated_data)
Check query.id before fetching data from youtube-api
var _ = require('underscore'); var moment = require('moment'); var Promise = require('promise'); var fetch = require('./../fetch'); var cache = require('../cache'); var VideoModel = require('../../db/videos/models/Video'); var saveVideo = require('../../db/videos/saveVideo'); var getVideos = require('../../db/videos/getVideos'); module.exports = function (req, res) { var query = req.query; var videoIds = query.id.split(','); getVideos(videoIds) .then(videoResult => { var itemsFromDB = videoResult.itemsFromDB; var itemsNotFound = videoResult.itemsNotFound; var config = new fetch.Config({ endpoint: 'videos', query: query }); // Update query query.id = itemsNotFound.join(','); if(!query.id) { fetch.end(res, itemsFromDB); return; } fetch(config).then(result => { var fromCache = result.fromCache; var items = result.data.items.concat(itemsFromDB); if (!fromCache) { // Save/Update videos in mongoDB _.each(result.data.items, function (videoItem) { videoItem._id = videoItem.id; videoItem.expires = moment().add(7, 'days').toDate(); saveVideo(videoItem); }); } }); }); };
var _ = require('underscore'); var moment = require('moment'); var Promise = require('promise'); var fetch = require('./../fetch'); var cache = require('../cache'); var VideoModel = require('../../db/videos/models/Video'); var saveVideo = require('../../db/videos/saveVideo'); var getVideos = require('../../db/videos/getVideos'); module.exports = function (req, res) { var query = req.query; var videoIds = query.id.split(','); getVideos(videoIds) .then(videoResult => { var itemsFromDB = videoResult.itemsFromDB; var itemsNotFound = videoResult.itemsNotFound; var config = new fetch.Config({ endpoint: 'videos', query: query }); // Update query query.id = itemsNotFound.join(','); fetch(config).then(result => { var fromCache = result.fromCache; var items = result.data.items.concat(itemsFromDB); fetch.end(res, items); if (!fromCache) { // Save/Update videos in mongoDB _.each(result.data.items, function (videoItem) { videoItem._id = videoItem.id; videoItem.expires = moment().add(7, 'days').toDate(); saveVideo(videoItem); }); } }); }); };
Make it work by default
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { var options = _.defaults(grunt.config('behat') || {}, defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; grunt.registerTask('behat', 'Parallel behat', function () { var done = this.async(); glob(options.src, function (err, files) { options.files = files; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); }); } module.exports = GruntTask;
'use strict'; var glob = require('glob'), _ = require('underscore'), ParallelExec = require('./lib/ParallelExec'), BehatTask = require('./lib/BehatTask'), defaults = { src: './**/*.feature', bin: './bin/behat', cwd: './', config: './behat.yml', flags: '', maxProcesses: 10000, baseDir: './', debug: false, numRetries: 0, timeout: 600000 }; /** * Grunt task for executing behat feature files in parallel * * @param {Grunt} grunt */ function GruntTask (grunt) { var options = _.defaults(grunt.config('behat'), defaults), executor = new ParallelExec(options.maxProcesses, {cwd: options.cwd, timeout: options.timeout}), behat; grunt.registerTask('behat', 'Parallel behat', function () { var done = this.async(); glob(options.src, function (err, files) { options.files = files; options.done = done; options.executor = executor; options.log = grunt.log.writeln; behat = new BehatTask(options); behat.run(); }); }); } module.exports = GruntTask;
system: Remove constructor/destructor from static L10nFactory
<?php /** * Factory class for providing Localization implementations * @author M2Mobi, Heinz Wiesinger */ class L10nFactory { /** * Instance of the L10nProvider * @var array */ private static $lprovider; /** * This method returns an object with the appropriate localization * implementation provider * @param String $provider The localization implementation requested * @param String $language POSIX locale definition * @return L10nProvider $return Instance of the localization provider requested */ public static function get_localization($provider, $language) { require_once("class.l10nprovider.inc.php"); switch($provider) { case "php": if (!isset(self::$lprovider[$provider])) { require_once("class.l10nproviderphp.inc.php"); self::$lprovider[$provider] = new L10nProviderPHP($language); } return self::$lprovider[$provider]; break; case "gettext": default: if (!isset(self::$lprovider[$provider])) { require_once("class.l10nprovidergettext.inc.php"); self::$lprovider[$provider] = new L10nProviderGettext($language); } return self::$lprovider[$provider]; break; } } } ?>
<?php /** * Factory class for providing Localization implementations * @author M2Mobi, Heinz Wiesinger */ class L10nFactory { /** * Instance of the L10nProvider * @var array */ private static $lprovider; /** * Constructor */ public function __construct() { } /** * Destructor */ public function __destruct() { } /** * This method returns an object with the appropriate localization * implementation provider * @param String $provider The localization implementation requested * @param String $language POSIX locale definition * @return L10nProvider $return Instance of the localization provider requested */ public static function get_localization($provider, $language) { require_once("class.l10nprovider.inc.php"); switch($provider) { case "php": if (!isset(self::$lprovider[$provider])) { require_once("class.l10nproviderphp.inc.php"); self::$lprovider[$provider] = new L10nProviderPHP($language); } return self::$lprovider[$provider]; break; case "gettext": default: if (!isset(self::$lprovider[$provider])) { require_once("class.l10nprovidergettext.inc.php"); self::$lprovider[$provider] = new L10nProviderGettext($language); } return self::$lprovider[$provider]; break; } } } ?>
Set `pydev_message` only if `additional_info` exists.
# -*- coding: utf-8 -*- import threading def pytest_exception_interact(node, call, report): """ Drop into PyCharm debugger, if available, on uncaught exceptions. """ try: import pydevd from pydevd import pydevd_tracing except ImportError: pass else: exctype, value, traceback = call.excinfo._excinfo frames = [] while traceback: frames.append(traceback.tb_frame) traceback = traceback.tb_next thread = threading.current_thread() frames_by_id = dict([(id(frame), frame) for frame in frames]) frame = frames[-1] exception = (exctype, value, traceback) if hasattr(thread, "additional_info"): thread.additional_info.pydev_message = "test fail" try: debugger = pydevd.debugger except AttributeError: debugger = pydevd.get_global_debugger() pydevd_tracing.SetTrace(None) # no tracing from here try: debugger.stop_on_unhandled_exception(thread, frame, frames_by_id, exception) except AttributeError: # fallback to pre PyCharm 2019.2 API debugger.handle_post_mortem_stop(thread, frame, frames_by_id, exception) return report
# -*- coding: utf-8 -*- import threading def pytest_exception_interact(node, call, report): """ Drop into PyCharm debugger, if available, on uncaught exceptions. """ try: import pydevd from pydevd import pydevd_tracing except ImportError: pass else: exctype, value, traceback = call.excinfo._excinfo frames = [] while traceback: frames.append(traceback.tb_frame) traceback = traceback.tb_next thread = threading.current_thread() frames_by_id = dict([(id(frame), frame) for frame in frames]) frame = frames[-1] exception = (exctype, value, traceback) thread.additional_info.pydev_message = 'test fail' try: debugger = pydevd.debugger except AttributeError: debugger = pydevd.get_global_debugger() pydevd_tracing.SetTrace(None) # no tracing from here try: debugger.stop_on_unhandled_exception(thread, frame, frames_by_id, exception) except AttributeError: # fallback to pre PyCharm 2019.2 API debugger.handle_post_mortem_stop(thread, frame, frames_by_id, exception) return report
Update tests for molecule 3 compatibility
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/molecule3/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True)
import pytest import os import shutil from subprocess import call from cookiecutter.main import cookiecutter playbook_setup_commands = ['pip install -r https://raw.githubusercontent.com/nephelaiio/ansible-role-requirements/master/requirements.txt'] playbook_setup_success = 0 playbook_test_command = "molecule test" playbook_test_success = 0 @pytest.mark.parametrize('role_name', ['tree']) def test_role_name(role_name): last_dir = os.path.curdir project_name = "ansible-role-{0}".format(role_name) test_dir = project_name try: shutil.rmtree(test_dir, ignore_errors=True) cookiecutter( '.', no_input=True, overwrite_if_exists=True, extra_context={ 'role_name': role_name, 'project_name': project_name} ) for command in playbook_setup_commands: assert call(command.split()) == playbook_setup_success os.chdir(test_dir) assert call(playbook_test_command.split()) == playbook_test_success finally: os.chdir(last_dir) shutil.rmtree(test_dir, ignore_errors=True)
Use last_build_result instead of last_build_status
define( [ 'jquery', 'backbone', 'underscore', 'moment' ], function ($, Backbone, _, moment) { "use strict"; return Backbone.Model.extend({ url : function() { var base = $('body').data('api-url') + '/repos'; return this.isNew() ? base : base + '/' + this.id; }, presenter: function () { return _.extend(this.toJSON(), { status: this.getStatus(), travisUrl: this.getTravisUrl(), githubUrl: this.getGithubUrl(), lastBuildFinishedAt: this.getLastBuildFinishedAt(), humanizedLastBuildFinishedAt: this.getHumanizedBuildFinishedAt() }); }, getStatus: function () { var lastBuildStatus = this.get('last_build_result'); if (0 === lastBuildStatus) { return 'passing'; } else if (1 === lastBuildStatus) { return 'failing'; } return 'unknown'; }, getTravisUrl: function () { return 'https://travis-ci.org/' + this.get('slug') + '/builds/' + this.get('last_build_id'); }, getGithubUrl: function () { return 'https://github.com/' + this.get('slug'); }, getLastBuildFinishedAt: function () { return this.get('last_build_finished_at'); }, getHumanizedBuildFinishedAt: function () { if (this.getLastBuildFinishedAt()) { return moment(this.getLastBuildFinishedAt()).fromNow(); } return ''; } }); } );
define( [ 'jquery', 'backbone', 'underscore', 'moment' ], function ($, Backbone, _, moment) { "use strict"; return Backbone.Model.extend({ url : function() { var base = $('body').data('api-url') + '/repos'; return this.isNew() ? base : base + '/' + this.id; }, presenter: function () { return _.extend(this.toJSON(), { status: this.getStatus(), travisUrl: this.getTravisUrl(), githubUrl: this.getGithubUrl(), lastBuildFinishedAt: this.getLastBuildFinishedAt(), humanizedLastBuildFinishedAt: this.getHumanizedBuildFinishedAt() }); }, getStatus: function () { var lastBuildStatus = this.get('last_build_status'); if (0 === lastBuildStatus) { return 'passing'; } else if (1 === lastBuildStatus) { return 'failing'; } return 'unknown'; }, getTravisUrl: function () { return 'https://travis-ci.org/' + this.get('slug') + '/builds/' + this.get('last_build_id'); }, getGithubUrl: function () { return 'https://github.com/' + this.get('slug'); }, getLastBuildFinishedAt: function () { return this.get('last_build_finished_at'); }, getHumanizedBuildFinishedAt: function () { if (this.getLastBuildFinishedAt()) { return moment(this.getLastBuildFinishedAt()).fromNow(); } return ''; } }); } );
Create index on Question.when for faster ordered queries.
from django.db import models from django.contrib.auth.models import User from quizzardous.utils import slugify class Question(models.Model): """Represents a question asked by a user.""" class Meta: ordering = ['-when'] question = models.TextField() # A slug is actually required, but if it's empty, then it'll automatically # be converted from question (see above) slug = models.SlugField(default='', blank=True) author = models.ForeignKey('auth.User', related_name='questions') when = models.DateTimeField(auto_now=True, db_index=True) hearters = models.ManyToManyField('auth.User', related_name='hearted_questions') correct_answers = models.TextField() # TODO: Tags - custom implementation or django-tagging? def clean(self): if not self.slug: self.slug = slugify(self.question) def save(self): self.full_clean() super(self.__class__, self).save(self) @models.permalink def get_absolute_url(self): return ('question', (self.pk, self.slug)) @property def hearts(self): try: return self.hearters.count() except ValueError: return 0 def __unicode__(self): return unicode(self.question) class Answer(models.Model): """Represents an answer to a question (submitted by a user)""" question = models.ForeignKey('Question', related_name='answers') answer = models.TextField() author = models.ForeignKey('auth.User', related_name='answers')
from django.db import models from django.contrib.auth.models import User from quizzardous.utils import slugify class Question(models.Model): """Represents a question asked by a user.""" class Meta: ordering = ['-when'] question = models.TextField() # A slug is actually required, but if it's empty, then it'll automatically # be converted from question (see above) slug = models.SlugField(default='', blank=True) author = models.ForeignKey('auth.User', related_name='questions') when = models.DateTimeField(auto_now=True) hearters = models.ManyToManyField('auth.User', related_name='hearted_questions') correct_answers = models.TextField() # TODO: Tags - custom implementation or django-tagging? def clean(self): if not self.slug: self.slug = slugify(self.question) def save(self): self.full_clean() super(self.__class__, self).save(self) @models.permalink def get_absolute_url(self): return ('question', (self.pk, self.slug)) @property def hearts(self): try: return self.hearters.count() except ValueError: return 0 def __unicode__(self): return unicode(self.question) class Answer(models.Model): """Represents an answer to a question (submitted by a user)""" question = models.ForeignKey('Question', related_name='answers') answer = models.TextField() author = models.ForeignKey('auth.User', related_name='answers')
Set the default cartoCSS version when generating the MapConfig
var _ = require('underscore'); var LayerGroupConfig = {}; var DEFAULT_CARTOCSS_VERSION = '2.1.0'; LayerGroupConfig.generate = function (options) { var layers = options.layers; var dataviews = options.dataviews; var config = { layers: [] }; _.each(layers, function (layer) { if (layer.isVisible()) { var layerConfig = { type: layer.get('type').toLowerCase(), options: { sql: layer.get('sql'), cartocss: layer.get('cartocss'), cartocss_version: layer.get('cartocss_version') || DEFAULT_CARTOCSS_VERSION, interactivity: layer.getInteractiveColumnNames(), // TODO widgets should be renamed to dataviews, requires Windshaft to be changed first though widgets: {} } }; if (dataviews) { layerConfig.options.widgets = dataviews.reduce(function (memo, m) { if (layer.get('id') === m.layer.get('id')) { memo[m.get('id')] = m.toJSON(); } return memo; }, {}); } if (layer.getInfowindowFieldNames().length) { layerConfig.options.attributes = { id: 'cartodb_id', columns: layer.getInfowindowFieldNames() }; } config.layers.push(layerConfig); } }); return config; }; module.exports = LayerGroupConfig;
var _ = require('underscore'); var LayerGroupConfig = {}; LayerGroupConfig.generate = function (options) { var layers = options.layers; var dataviews = options.dataviews; var config = { layers: [] }; _.each(layers, function (layer) { if (layer.isVisible()) { var layerConfig = { type: layer.get('type').toLowerCase(), options: { sql: layer.get('sql'), cartocss: layer.get('cartocss'), cartocss_version: layer.get('cartocss_version'), interactivity: layer.getInteractiveColumnNames(), // TODO widgets should be renamed to dataviews, requires Windshaft to be changed first though widgets: {} } }; if (dataviews) { layerConfig.options.widgets = dataviews.reduce(function (memo, m) { if (layer.get('id') === m.layer.get('id')) { memo[m.get('id')] = m.toJSON(); } return memo; }, {}); } if (layer.getInfowindowFieldNames().length) { layerConfig.options.attributes = { id: 'cartodb_id', columns: layer.getInfowindowFieldNames() }; } config.layers.push(layerConfig); } }); return config; }; module.exports = LayerGroupConfig;
feat: Improve annotating of code segements
import re class ArtifactAnnotator: excluded_types = set(['heading', 'code']) def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types: strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] not in ArtifactAnnotator.excluded_types item['text'] = strings[i] i = i + 1
import re class ArtifactAnnotator: def linkify_artifacts(marked_tree, artifacts): big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree) for artifact in artifacts: link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id'] for token in artifact['tokens']: reg = ArtifactAnnotator._token_reg(token) repl = r'[\1]%s' % link big_string = reg.sub(repl, big_string) ArtifactAnnotator._big_string_to_marked_tree(marked_tree, big_string) return marked_tree def _token_reg(token): reg = r'(\b%s)' % token return re.compile(reg, re.IGNORECASE) def _marked_tree_to_big_string(marked_tree): strings = [] for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': strings.append(item['text']) big_string = u'\u1394'.join(strings) return big_string def _big_string_to_marked_tree(marked_tree, big_string): strings = big_string.split(u'\u1394') i = 0 for item in marked_tree: if 'text' in item and item['type'] != 'heading' and item[ 'type'] != 'code': item['text'] = strings[i] i = i + 1
Use multiple run for local karma
/* global process */ module.exports = function (config) { config.set({ browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: !!process.env.CONTINUOUS_INTEGRATION, frameworks: [ 'mocha' ], files: [ 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js', 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js', './__tests__/tests.webpack.js' ], preprocessors: { './__tests__/tests.webpack.js': [ 'webpack', 'sourcemap' ] }, reporters: [ 'dots' ], webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'jsx-loader?stripTypes', 'babel?stage=0' ], exclude: /node_modules/ } ] }, externals : { 'react' : 'React', 'react-dom' : 'ReactDOM' } }, webpackServer: { noInfo: true } }); };
/* global process */ module.exports = function (config) { config.set({ browsers: [ process.env.CONTINUOUS_INTEGRATION ? 'Firefox' : 'Chrome' ], singleRun: true, frameworks: [ 'mocha' ], files: [ 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-with-addons.js', 'https://cdnjs.cloudflare.com/ajax/libs/react/0.14.0/react-dom.js', './__tests__/tests.webpack.js' ], preprocessors: { './__tests__/tests.webpack.js': [ 'webpack', 'sourcemap' ] }, reporters: [ 'dots' ], webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.jsx?$/, loaders: [ 'jsx-loader?stripTypes', 'babel?stage=0' ], exclude: /node_modules/ } ] }, externals : { 'react' : 'React', 'react-dom' : 'ReactDOM' } }, webpackServer: { noInfo: true } }); };
Add backends as explicit package
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( author="Ben Lopatin", author_email="[email protected]", name='django-organizations', version='0.2.0', description='Group accounts for Django', long_description=readme + '\n\n' + history, url='https://github.com/wellfire/django-organizations/', license='BSD License', platforms=['OS Independent'], packages=[ 'organizations', 'organizations.backends', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires=[ 'Django>=1.4.2,<1.7', 'django-extensions>=0.9', ], test_suite='tests', include_package_data=True, zip_safe=False, )
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') os.system('python setup.py bdist_wheel upload') sys.exit() readme = open('README.rst').read() history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( author="Ben Lopatin", author_email="[email protected]", name='django-organizations', version='0.2.0', description='Group accounts for Django', long_description=readme + '\n\n' + history, url='https://github.com/wellfire/django-organizations/', license='BSD License', platforms=['OS Independent'], packages=[ 'organizations', ], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires=[ 'Django>=1.4.2', 'django-extensions>=0.9', ], test_suite='tests', include_package_data=True, zip_safe=False, )
Add food to the perception handler
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta elif isinstance(entity, structure.Food): return "f%s" % delta return ""
""" Module that holds classes that represent an agent's perception handler. """ import abc import world import structure class PerceptionHandler(object): """ Abstract perception handler class. """ @abc.abstractmethod def perceive(self, agent, world): """ Generates a percept given an agent and a world. :param agent: The agent to generate the percept for. :param world: The world to generate the percept for. :return: The percept. """ raise NotImplementedError("Should be implemented by child") class EmptyPerceptionHandler(PerceptionHandler): """ A trivial perception handler that never perceives anything. """ def perceive(self, agent, world): return "" class BasicPerceptionHandler(PerceptionHandler): """ A perception handler that perceives walls and blocks up to a given distance. The perception indicates the type of structure that is seen, as well as its distance. """ def perceive(self, agent_, world_): for delta in range(0, 10): pos = world.Position(agent_.get_position()) pos.add(agent_.get_move_delta(delta)) entities = world_.get_entities_at(pos) for entity in entities: if entity == agent_: continue if isinstance(entity, structure.Wall): return "w%s" % delta elif isinstance(entity, structure.Block): return "b%s" % delta return ""
Fix migration that fails on postgres
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('studygroups', '0027_auto_20150513_2005'), ] operations = [ migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=256)), ('address', models.CharField(max_length=256)), ('contact_name', models.CharField(max_length=256)), ('contact', models.CharField(max_length=256)), ('link', models.URLField()), ], ), migrations.RemoveField( model_name='studygroup', name='location_link', ), migrations.AddField( model_name='studygroup', name='location_details', field=models.CharField(default='none', max_length=128), preserve_default=False, ), migrations.RemoveField( model_name='studygroup', name='location', ), migrations.AddField( model_name='studygroup', name='location', field=models.ForeignKey(to='studygroups.Location'), ), ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('studygroups', '0027_auto_20150513_2005'), ] operations = [ migrations.CreateModel( name='Location', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=256)), ('address', models.CharField(max_length=256)), ('contact_name', models.CharField(max_length=256)), ('contact', models.CharField(max_length=256)), ('link', models.URLField()), ], ), migrations.RemoveField( model_name='studygroup', name='location_link', ), migrations.AddField( model_name='studygroup', name='location_details', field=models.CharField(default='none', max_length=128), preserve_default=False, ), migrations.AlterField( model_name='studygroup', name='location', field=models.ForeignKey(to='studygroups.Location'), ), ]
Add modal options to sidebar
module.exports = { api: [ { type: 'category', label: 'Navigation', items: [ 'component', 'root', 'stack', 'modal', 'overlay' ] }, { type: 'category', label: 'Layouts', items: [ 'layout-layout', 'layout-component', 'layout-stack', 'layout-bottomTabs', 'layout-sideMenu', 'layout-splitView' ] }, { type: 'category', label: 'Options', items: [ 'options-api', 'options-root', 'options-bottomTabs', 'options-bottomTab', { 'type': 'category', 'label': 'Stack', 'items': [ 'options-stack', 'options-title', 'options-subtitle', 'options-background', 'options-backButton', 'options-button', 'options-iconInsets', 'options-largeTitle' ] }, 'options-statusBar', 'options-layout', 'options-modal', 'options-navigationBar', 'options-overlay', 'options-sideMenu', 'options-sideMenuSide', 'options-splitView' ] }, 'events' ] };
module.exports = { api: [ { type: 'category', label: 'Navigation', items: [ 'component', 'root', 'stack', 'modal', 'overlay' ] }, { type: 'category', label: 'Layouts', items: [ 'layout-layout', 'layout-component', 'layout-stack', 'layout-bottomTabs', 'layout-sideMenu', 'layout-splitView' ] }, { type: 'category', label: 'Options', items: [ 'options-api', 'options-root', 'options-bottomTabs', 'options-bottomTab', { 'type': 'category', 'label': 'Stack', 'items': [ 'options-stack', 'options-title', 'options-subtitle', 'options-background', 'options-backButton', 'options-button', 'options-iconInsets', 'options-largeTitle' ] }, 'options-statusBar', 'options-layout', 'options-navigationBar', 'options-overlay', 'options-sideMenu', 'options-sideMenuSide', 'options-splitView' ] }, 'events' ] };
[import] Reduce batch size to 128kb
const MAX_PAYLOAD_SIZE = 1024 * 256 // 256KB function batchDocuments(docs) { let currentBatch = [] let currentBatchSize = 0 const batches = [currentBatch] docs.forEach(doc => { const docSize = JSON.stringify(doc).length const newBatchSize = currentBatchSize + docSize // If this document pushes us over the max payload size, start a new batch if (currentBatchSize > 0 && newBatchSize > MAX_PAYLOAD_SIZE) { currentBatch = [doc] currentBatchSize = docSize batches.push(currentBatch) return } // If this document *alone* is over the max payload size, try to allow it // on it's own. Server has slightly higher payload size than defined here if (docSize > MAX_PAYLOAD_SIZE) { if (currentBatchSize === 0) { // We're alone in a new batch, so push this doc into it and start a new // one for the next document in line currentBatch.push(doc) currentBatchSize = docSize currentBatch = [] batches.push(currentBatch) return } // Batch already has documents, so "close" that batch off and push this // huge document into it's own batch currentBatch = [] currentBatchSize = 0 batches.push([doc], currentBatch) } // Otherwise, we should be below the max size, so push this document into // the batch and increase the size of it to match currentBatch.push(doc) currentBatchSize += docSize }) return batches } module.exports = batchDocuments
const MAX_PAYLOAD_SIZE = 1024 * 512 // 512KB function batchDocuments(docs) { let currentBatch = [] let currentBatchSize = 0 const batches = [currentBatch] docs.forEach(doc => { const docSize = JSON.stringify(doc).length const newBatchSize = currentBatchSize + docSize // If this document pushes us over the max payload size, start a new batch if (currentBatchSize > 0 && newBatchSize > MAX_PAYLOAD_SIZE) { currentBatch = [doc] currentBatchSize = docSize batches.push(currentBatch) return } // If this document *alone* is over the max payload size, try to allow it // on it's own. Server has slightly higher payload size than defined here if (docSize > MAX_PAYLOAD_SIZE) { if (currentBatchSize === 0) { // We're alone in a new batch, so push this doc into it and start a new // one for the next document in line currentBatch.push(doc) currentBatchSize = docSize currentBatch = [] batches.push(currentBatch) return } // Batch already has documents, so "close" that batch off and push this // huge document into it's own batch currentBatch = [] currentBatchSize = 0 batches.push([doc], currentBatch) } // Otherwise, we should be below the max size, so push this document into // the batch and increase the size of it to match currentBatch.push(doc) currentBatchSize += docSize }) return batches } module.exports = batchDocuments
Update query to use nodes
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository(owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { nodes { name target { commitUrl } } } releases(last: $count) { nodes { tag { name prefix } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
import requests GITHUB_API_URL = "https://api.github.com/graphql" QUERY = """ query($repository_owner:String!, $repository_name: String!, $count: Int!) { repository( owner: $repository_owner, name: $repository_name) { refs(last: $count,refPrefix:"refs/tags/") { edges { node{ name } } } releases(last: $count) { edges { node { name } } } } } """ class Github: def __authorization_header(self): return "token " + self.token def __request_headers(self): return { 'authorization': self.__authorization_header(), } def __init__(self, token): self.token = token def getTagsAndReleases(self, repository_owner, repository_name, count): payload = {"query": QUERY, "variables": { "repository_owner": repository_owner, "repository_name": repository_name, "count": count }} print "Requesting for", repository_name response = requests.post(GITHUB_API_URL, json=payload, headers=self.__request_headers()) print "Got status code for", repository_name, response.status_code return response.json()
Remove trailing slash from realpath call realpath returns paths without trailing slashes. This change makes that clearer in the call
<?php namespace Bugsnag\BugsnagBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class BugsnagExtension extends Extension { /** * Loads a specific configuration. * * @param array $configs * @param ContainerBuilder $container * * @return void */ public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.yml'); foreach ($config as $key => $value) { $container->setParameter("bugsnag.{$key}", $value); } if ($container->hasParameter('kernel.project_dir')) { $symfonyRoot = $container->getParameter('kernel.project_dir'); } else { $symfonyRoot = realpath( $container->getParameter('kernel.root_dir').'/..' ); } $container->setParameter('bugsnag.symfony_root', $symfonyRoot); } }
<?php namespace Bugsnag\BugsnagBundle\DependencyInjection; use Symfony\Component\Config\FileLocator; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\HttpKernel\DependencyInjection\Extension; class BugsnagExtension extends Extension { /** * Loads a specific configuration. * * @param array $configs * @param ContainerBuilder $container * * @return void */ public function load(array $configs, ContainerBuilder $container) { $config = $this->processConfiguration(new Configuration(), $configs); $loader = new YamlFileLoader( $container, new FileLocator(__DIR__.'/../Resources/config') ); $loader->load('services.yml'); foreach ($config as $key => $value) { $container->setParameter("bugsnag.{$key}", $value); } if ($container->hasParameter('kernel.project_dir')) { $symfonyRoot = $container->getParameter('kernel.project_dir'); } else { $symfonyRoot = realpath( $container->getParameter('kernel.root_dir').'/../' ); } $container->setParameter('bugsnag.symfony_root', $symfonyRoot); } }
Improve the top bar for the error messages.
package com.sb.elsinore.html; import java.io.IOException; import org.rendersnake.HtmlCanvas; import org.rendersnake.Renderable; import com.sb.elsinore.LaunchControl; import static org.rendersnake.HtmlAttributesFactory.*; /** * Create a top bar for the web page. * @author Doug Edey */ public class TopBar implements Renderable { @Override public final void renderOn(HtmlCanvas htmlCanvas) throws IOException { htmlCanvas.div(id("topbar").class_("row")) .div(id("breweryTitle").class_("left col-md-2")) .h1(class_("breweryNameHeader").onClick("editBreweryName()")) .div(id("breweryName")).write("Elsinore")._div() .small() .a(href(LaunchControl.RepoURL)) .content("StrangeBrew Elsinore") ._small() ._h1() ._div() .div(class_("center-left col-md-4"))._div() .div(class_("center-right col-md-4"))._div() ._div() .div(id("messages").class_("row").style("display:none")) .div(class_("panel panel-warning")) .div(id("messages-title").class_("title panel-heading"))._div() .div(id("messages-body").class_("panel-body"))._div() ._div() ._div(); } }
package com.sb.elsinore.html; import java.io.IOException; import org.rendersnake.HtmlCanvas; import org.rendersnake.Renderable; import com.sb.elsinore.LaunchControl; import static org.rendersnake.HtmlAttributesFactory.*; /** * Create a top bar for the web page. * @author Doug Edey */ public class TopBar implements Renderable { @Override public final void renderOn(HtmlCanvas htmlCanvas) throws IOException { htmlCanvas.div(id("topbar").class_("col-md-12")) .div(id("breweryTitle").class_("left col-md-2")) .h1(class_("breweryNameHeader").onClick("editBreweryName()")) .div(id("breweryName")).write("Elsinore")._div() .small() .a(href(LaunchControl.RepoURL)) .content("StrangeBrew Elsinore") ._small() ._h1() ._div() .div(class_("center-left col-md-4"))._div() .div(class_("center-right col-md-4"))._div() ._div() .div(id("messages").style("display:none")) .div(class_("panel panel-warning")) .div(id("messages-title").class_("title panel-heading"))._div() .div(id("messages-body").class_("panel-body"))._div() ._div() ._div(); } }
Remove sensitivity to time warnings in formatter output
<?php namespace Matcher; use PhpSpec\Exception\Example\FailureException; use PhpSpec\Matcher\MatcherInterface; use Symfony\Component\Console\Tester\ApplicationTester; class ApplicationOutputMatcher implements MatcherInterface { /** * Checks if matcher supports provided subject and matcher name. * * @param string $name * @param mixed $subject * @param array $arguments * * @return Boolean */ public function supports($name, $subject, array $arguments) { return ($name == 'haveOutput' && $subject instanceof ApplicationTester); } /** * Evaluates positive match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function positiveMatch($name, $subject, array $arguments) { $expected = $this->normalise($arguments[0]); $actual = $this->normalise($subject->getDisplay()); if (strpos($actual, $expected) === false) { throw new FailureException(sprintf( "Application output did not contain expected '%s'. Actual output:\n'%s'" , $expected, $subject->getDisplay() )); } } private function normalise($string) { $string = preg_replace('/\([0-9]+ms\)/', '', $string); return $string; } /** * Evaluates negative match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function negativeMatch($name, $subject, array $arguments) { throw new FailureException('Negative application output matcher not implemented'); } /** * Returns matcher priority. * * @return integer */ public function getPriority() { return 51; } }
<?php namespace Matcher; use PhpSpec\Exception\Example\FailureException; use PhpSpec\Matcher\MatcherInterface; use Symfony\Component\Console\Tester\ApplicationTester; class ApplicationOutputMatcher implements MatcherInterface { /** * Checks if matcher supports provided subject and matcher name. * * @param string $name * @param mixed $subject * @param array $arguments * * @return Boolean */ public function supports($name, $subject, array $arguments) { return ($name == 'haveOutput' && $subject instanceof ApplicationTester); } /** * Evaluates positive match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function positiveMatch($name, $subject, array $arguments) { $expected = $arguments[0]; if (strpos($subject->getDisplay(), $expected) === false) { throw new FailureException(sprintf( "Application output did not contain expected '%s'. Actual output:\n'%s'" , $expected, $subject->getDisplay() )); } } /** * Evaluates negative match. * * @param string $name * @param mixed $subject * @param array $arguments */ public function negativeMatch($name, $subject, array $arguments) { throw new FailureException('Negative application output matcher not implemented'); } /** * Returns matcher priority. * * @return integer */ public function getPriority() { return 51; } }
Add a method to get the value objects built internally.
<?PHP /** * A common interface for all value objects. * * * @author Adamo Crespi <[email protected]> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Common; /** * Implements basic constructor for complex value objects. */ trait ComplexValueObjectTrait { /** @var array Contains the data for which a property were not found */ private $otherData = []; /** * Accepts an array containing the values to set in the object. * * @param array $values */ public function __construct(array $values) { foreach ($values as $property => $value) { $setter = 'set' . ucfirst($property); $adder = 'add' . ucfirst($property); if (true === method_exists($this, $setter)) { $this->$setter($value); unset($values[$property]); } if (true === method_exists($this, $adder)) { $this->$adder($value); unset($values[$property]); } } // Add remaining value to $otherData $this->otherData = $values; } /** * Get other data if present, null instead. * * @return array|null */ public function getOtherData() { return (true === empty($this->otherData)) ? null : $this->otherData; } /** * Returns the built value object or null if no one is present. * @return mixed */ public function getValueObject() { return $this->valueObject; } }
<?PHP /** * A common interface for all value objects. * * * @author Adamo Crespi <[email protected]> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Component\ValueObjects\Common; /** * Implements basic constructor for complex value objects. */ trait ComplexValueObjectTrait { /** @var array Contains the data for which a property were not found */ private $otherData = []; /** * Accepts an array containing the values to set in the object. * * @param array $values */ public function __construct(array $values) { foreach ($values as $property => $value) { $setter = 'set' . ucfirst($property); $adder = 'add' . ucfirst($property); if (true === method_exists($this, $setter)) { $this->$setter($value); unset($values[$property]); } if (true === method_exists($this, $adder)) { $this->$adder($value); unset($values[$property]); } } // Add remaining value to $otherData $this->otherData = $values; } /** * Get other data if present, null instead. * * @return array|null */ public function getOtherData() { return (true === empty($this->otherData)) ? null : $this->otherData; } }
CRM-4904: Refactor email body sync - Fix migrations
<?php namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery; use Oro\Bundle\MigrationBundle\Migration\QueryBag; use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery; class OroEmailBundle implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { self::oroEmailTable($schema); $this->deleteBodySyncProcess($schema, $queries); } /** * @param Schema $schema */ public static function oroEmailTable(Schema $schema) { $table = $schema->getTable('oro_email'); if (!$table->hasColumn('body_synced')) { $table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]); } } /** * Delete sync_email_body_after_email_synchronize process definition * * @param Schema $schema * @param QueryBag $queries */ protected function deleteBodySyncProcess(Schema $schema, QueryBag $queries) { if ($schema->hasTable('oro_process_definition')) { $queries->addQuery( new ParametrizedSqlMigrationQuery( 'DELETE FROM oro_process_definition WHERE name = :processName', ['processName' => 'sync_email_body_after_email_synchronize'] ) ); } } }
<?php namespace Oro\Bundle\EmailBundle\Migrations\Schema\v1_20; use Doctrine\DBAL\Schema\Schema; use Oro\Bundle\MigrationBundle\Migration\Migration; use Oro\Bundle\MigrationBundle\Migration\ParametrizedSqlMigrationQuery; use Oro\Bundle\MigrationBundle\Migration\QueryBag; use Oro\Bundle\MigrationBundle\Migration\SqlMigrationQuery; class OroEmailBundle implements Migration { /** * {@inheritdoc} */ public function up(Schema $schema, QueryBag $queries) { self::oroEmailTable($schema); $this->deleteBodySyncProcess($queries); } /** * @param Schema $schema */ public static function oroEmailTable(Schema $schema) { $table = $schema->getTable('oro_email'); if (!$table->hasColumn('body_synced')) { $table->addColumn('body_synced', 'boolean', ['notnull' => false, 'default' => false]); } } /** * Delete sync_email_body_after_email_synchronize process definition * * @param QueryBag $queries */ protected function deleteBodySyncProcess(QueryBag $queries) { $queries->addQuery( new ParametrizedSqlMigrationQuery( 'DELETE FROM oro_process_definition WHERE name = :processName', ['processName' => 'sync_email_body_after_email_synchronize'] ) ); } }
Add error info when lock exists
import logging try: import click from lockfile import LockFile, LockTimeout except ImportError: click = None logger = logging.getLogger('spoppy.main') def get_version(): return '1.2.2' if click: @click.command() @click.argument('username', required=False) @click.argument('password', required=False) def main(username, password): # Ignore error, logging set up in logging utils from . import logging_utils from .navigation import Leifur from .config import get_config, set_config, get_config_from_user lock = LockFile('/tmp/spoppy') try: # Try for 5s to acquire the lock lock.acquire(5) except LockTimeout: click.echo('Could not acquire lock, is spoppy running?') click.echo( 'If you\'re sure that spoppy is not running, ' 'try removing the lock file %s' % lock.lock_file ) else: if username and password: set_config(username, password) else: username, password = get_config() if not (username and password): username, password = get_config_from_user() try: navigator = Leifur(username, password) navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') finally: if lock.i_am_locking(): lock.release() else: def main(*args, **kwargs): print('Something went horribly wrong, missing requirements...')
import logging try: import click from lockfile import LockFile, LockTimeout except ImportError: click = None logger = logging.getLogger('spoppy.main') def get_version(): return '1.2.2' if click: @click.command() @click.argument('username', required=False) @click.argument('password', required=False) def main(username, password): # Ignore error, logging set up in logging utils from . import logging_utils from .navigation import Leifur from .config import get_config, set_config, get_config_from_user lock = LockFile('/tmp/spoppy.lock') try: # Try for 5s to acquire the lock lock.acquire(5) except LockTimeout: click.echo('Could not acquire lock, is spoppy running?') else: if username and password: set_config(username, password) else: username, password = get_config() if not (username and password): username, password = get_config_from_user() try: navigator = Leifur(username, password) navigator.start() finally: navigator.shutdown() logger.debug('Finally, bye!') finally: if lock.i_am_locking(): lock.release() else: def main(*args, **kwargs): print('Something went horribly wrong, missing requirements...')
chore(cleanup): Remove old code for copying test-module
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
var utils = require('utils') , env = utils.bootstrapEnv() , moduleLdr = env.moduleLoader , injector = require('injector') , ncp = require('ncp') , path = require('path') , async = require('async'); describe('ModuleLoader', function() { before(function(done) { var source = path.resolve(__dirname, '..', 'test-module') , dest = path.resolve(__dirname, '..', '..', '..', 'modules', 'test-module'); // Copy the test-module into the modules folder ncp(source, dest, done); }); it('should load modules', function(done) { this.timeout(20000); moduleLdr.on('modulesLoaded', function() { async.parallel( [ function ormDb(callback) { if (moduleLdr.moduleIsEnabled('clever-orm') === true) { injector .getInstance('sequelize') .sync({ force: true }) .then(function() { callback(null); }) .catch(callback); } else { callback(null); } }, function odmDb(callback) { callback(null); } ], function(err) { if (err !== undefined && err !== null) { console.dir(err); return done(err); } done(); } ); }); moduleLdr.loadModules(); }); it('should initialize all module routes', function(done) { moduleLdr.on('routesInitialized', function() { done(); }); moduleLdr.initializeRoutes(); }); });
Add index.js to the tests / complexity runner Signed-off-by: Henrique Vicente <[email protected]>
/* * grunt-cli-config * https://github.com/henvic/grunt-cli-config * * Copyright (c) 2014 Henrique Vicente * Licensed under the MIT license. */ 'use strict'; module.exports = function exports(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'index.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, nodeunit: { tests: ['test/*_test.js'] }, complexity: { generic: { src: ['Gruntfile.js', 'index.js', 'tasks/*.js'], options: { breakOnErrors: true, errorsOnly: false, cyclomatic: 3, halstead: 8, maintainability: 70, hideComplexFunctions: false } } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-complexity'); grunt.registerTask('test', ['jshint', 'nodeunit', 'complexity']); grunt.registerTask('default', ['test']); };
/* * grunt-cli-config * https://github.com/henvic/grunt-cli-config * * Copyright (c) 2014 Henrique Vicente * Licensed under the MIT license. */ 'use strict'; module.exports = function exports(grunt) { grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, nodeunit: { tests: ['test/*_test.js'] }, complexity: { generic: { src: ['Gruntfile.js', 'tasks/config_options.js'], options: { breakOnErrors: true, errorsOnly: false, cyclomatic: 3, halstead: 8, maintainability: 70, hideComplexFunctions: false } } } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-complexity'); grunt.registerTask('test', ['jshint', 'nodeunit', 'complexity']); grunt.registerTask('default', ['test']); };
Exclude inactive comics from sets editing, effectively throwing them out of the set when saved
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.filter(active=True), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
import datetime from django import forms from django.template.defaultfilters import slugify from comics.core.models import Comic from comics.sets.models import Set class NewSetForm(forms.ModelForm): class Meta: model = Set fields = ('name',) def save(self, commit=True): set = super(NewSetForm, self).save(commit=False) set.name = slugify(set.name) set.last_modified = datetime.datetime.now() set.last_loaded = datetime.datetime.now() if commit: set.save() return set class EditSetForm(forms.ModelForm): comics = forms.ModelMultipleChoiceField( Comic.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) add_new_comics = forms.BooleanField( label='Automatically add new comics to the set', required=False) hide_empty_comics = forms.BooleanField( label='Hide comics without matching releases from view', required=False) class Meta: model = Set fields = ('comics', 'add_new_comics', 'hide_empty_comics') def save(self, commit=True): comics_set = super(EditSetForm, self).save(commit=False) comics_set.last_modified = datetime.datetime.now() if commit: comics_set.save() self.save_m2m() return comics_set
Allow method chaining after serveSwagger
import {json} from "body-parser"; import {Router} from "express"; import * as validate from "./validate-middleware"; import * as convert from "./convert"; export default function convexpress (options) { const router = Router().use(json()); router.swagger = { swagger: "2.0", host: options.host, basePath: options.basePath || "/", info: options.info, consumes: ["application/json"], produces: ["application/json"], paths: {} }; router.convroute = function (route) { // Attach route to router router[route.method]( route.path, [validate.middleware(route.parameters)].concat(route.middleware || []), route.handler ); // Update the swagger document const swaggerPath = convert.path(route.path); router.swagger.paths[swaggerPath] = { ...router.swagger.paths[swaggerPath], [route.method]: { description: route.description, parameters: convert.parameters(route.parameters), responses: { ...route.responses, ...validate.responses } } }; // Allow method chaining return router; }; router.serveSwagger = function (path = "/swagger.json") { router.get(path, (req, res) => res.status(200).send(router.swagger)); return router; }; return router; }
import {json} from "body-parser"; import {Router} from "express"; import * as validate from "./validate-middleware"; import * as convert from "./convert"; export default function convexpress (options) { const router = Router().use(json()); router.swagger = { swagger: "2.0", host: options.host, basePath: options.basePath || "/", info: options.info, consumes: ["application/json"], produces: ["application/json"], paths: {} }; router.convroute = function (route) { // Attach route to router router[route.method]( route.path, [validate.middleware(route.parameters)].concat(route.middleware || []), route.handler ); // Update the swagger document const swaggerPath = convert.path(route.path); router.swagger.paths[swaggerPath] = { ...router.swagger.paths[swaggerPath], [route.method]: { description: route.description, parameters: convert.parameters(route.parameters), responses: { ...route.responses, ...validate.responses } } }; // Allow method chaining return router; }; router.serveSwagger = function (path = "/swagger.json") { router.get(path, (req, res) => res.status(200).send(router.swagger)); }; return router; }
Configure debug_toolbar to not fail.
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'schwag.views.home', name='home'), url(r'^account/login/$', 'schwag.views.login', name='login'), url(r'^account/logout/$', 'schwag.views.logout', name='logout'), url(r'^account/register/$', 'schwag.views.register', name='register'), url(r'^account/', include('django.contrib.auth.urls')), url(r'^checkout/', include('senex_shop.checkout.urls')), url(r'^cart/', include('senex_shop.cart.urls')), url(r'^shop/', include('senex_shop.urls')), url(r'^news/', include('senex_shop.news.urls')), url(r'^admin/', include(admin.site.urls)), ) # Uncomment the next line to serve media files in dev. # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: try: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), ) except ImportError: pass if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), )
from django.conf.urls import patterns, include, url from django.conf import settings # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^$', 'schwag.views.home', name='home'), url(r'^account/login/$', 'schwag.views.login', name='login'), url(r'^account/logout/$', 'schwag.views.logout', name='logout'), url(r'^account/register/$', 'schwag.views.register', name='register'), url(r'^account/', include('django.contrib.auth.urls')), url(r'^checkout/', include('senex_shop.checkout.urls')), url(r'^cart/', include('senex_shop.cart.urls')), url(r'^shop/', include('senex_shop.urls')), url(r'^news/', include('senex_shop.news.urls')), url(r'^admin/', include(admin.site.urls)), ) # Uncomment the next line to serve media files in dev. # urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) if settings.DEBUG: import debug_toolbar urlpatterns += patterns('', url(r'^__debug__/', include(debug_toolbar.urls)), ) if settings.DEBUG: urlpatterns += patterns('django.views.static', (r'media/(?P<path>.*)', 'serve', {'document_root': settings.MEDIA_ROOT}), )
Enhance bad response exception CS.
<?php /** * @author Lev Semin <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Security\OAuth\Exception; use Darvin\AdminBundle\Security\OAuth\Response\DarvinAuthResponse; /** * Bad response exception */ class BadResponseException extends \LogicException { private $needClass; private $getClass; /** * BadResponseException constructor. * * @param object $object Object * @param string $needClass Need class */ public function __construct($object, $needClass = null) { $this->needClass = $needClass; $this->getClass = is_object($object) ? get_class($object) : 'not object'; if (empty($needClass)) { $this->needClass = DarvinAuthResponse::DARVIN_AUTH_RESPONSE_CLASS; } parent::__construct(sprintf( "OAuth response must be instance of %s, %s given", $this->needClass, $this->getClass )); } /** * @return string */ public function getNeedClass() { return $this->needClass; } /** * @return string */ public function getGetClass() { return $this->getClass; } }
<?php /** * @author Lev Semin <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\AdminBundle\Security\OAuth\Exception; use Darvin\AdminBundle\Security\OAuth\Response\DarvinAuthResponse; /** * Bad response exception */ class BadResponseException extends \LogicException { private $needClass; private $getClass; /** * BadResponseException constructor. * * @param object $object Object * @param string $needClass Need class */ public function __construct($object, $needClass = null) { $this->needClass = $needClass; $this->getClass = is_object($object) ? get_class($object) : 'not object'; if ($needClass == null) { $this->needClass = DarvinAuthResponse::DARVIN_AUTH_RESPONSE_CLASS; } parent::__construct(sprintf( "OAuth response must be instance of %s, %s given", $this->needClass, $this->getClass )); } /** * @return string */ public function getNeedClass() { return $this->needClass; } /** * @return string */ public function getGetClass() { return $this->getClass; } }
Mark as compatible with Python 3 with the proper classifier.
import os from setuptools import find_packages from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() DESCR = ('This package provides a Deform autocomplete widget that ' 'stores a value that may be different from the one shown ' 'to the user.') requires = ('deform', ) setup(name='deform_ext_autocomplete', version='0.1', description=DESCR, long_description=README + '\n\n' + CHANGES, classifiers=( 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2'), author='Damien Baty', author_email='[email protected]', url='http://readthedocs.org/projects/deform_ext_autocomplete/', keywords='deform form autocomplete', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, test_suite='deform_ext_autocomplete', )
import os from setuptools import find_packages from setuptools import setup here = os.path.abspath(os.path.dirname(__file__)) README = open(os.path.join(here, 'README.rst')).read() CHANGES = open(os.path.join(here, 'CHANGES.rst')).read() DESCR = ('This package provides a Deform autocomplete widget that ' 'stores a value that may be different from the one shown ' 'to the user.') requires = ('deform', ) setup(name='deform_ext_autocomplete', version='0.1', description=DESCR, long_description=README + '\n\n' + CHANGES, classifiers=( 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.2'), author='Damien Baty', author_email='[email protected]', url='http://readthedocs.org/projects/deform_ext_autocomplete/', keywords='deform form autocomplete', packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=requires, test_suite='deform_ext_autocomplete', )
Update Entity database table name
<?php namespace WiContactAPI\V1\Rest\Contact; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection") * @ORM\Table(name="contacts") */ class ContactEntity { /** * * @var int @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * * @var string @ORM\Column(type="string", nullable=true) */ protected $name; /** * * @return the $id */ public function getId() { return $this->id; } /** * * @return the $name */ public function getName() { return $this->name; } /** * * @param string $name */ public function setName($name) { $this->name = $name; } // @todo: Add phones support // @todo: Add Gedmo Annotations support // @todo: Check if getArrayCopy() function is required }
<?php namespace WiContactAPI\V1\Rest\Contact; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity(repositoryClass="WiContactAPI\V1\Rest\Contact\ContactCollection") * @ORM\Table(name="contact") */ class ContactEntity { /** * * @var int @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * * @var string @ORM\Column(type="string", nullable=true) */ protected $name; /** * * @return the $id */ public function getId() { return $this->id; } /** * * @return the $name */ public function getName() { return $this->name; } /** * * @param string $name */ public function setName($name) { $this->name = $name; } // @todo: Add phones support // @todo: Add Gedmo Annotations support // @todo: Check if getArrayCopy() function is required }
Expatistan: Switch to using the api_result.abstract for firstline
(function(env) { env.ddg_spice_expatistan = function(api_result) { "use strict"; if(!api_result || api_result.status !== 'OK') { return Spice.failed('expatistan'); } Spice.add({ id: "expatistan", name: "Answer", data: api_result, meta: { sourceUrl: api_result.source_url, sourceName: 'Expatistan' }, normalize: function(item) { // Split abstract in order to get // two separate strings and modify the first if (!api_result.abstract) { return null; } var lines = api_result.abstract.split(/of\s[0-9]+\s/); var cost = api_result.abstract.match(/\s[0-9]+\s/); var firstLine = ''; var secondLine = ''; if (lines.length === 2 && cost.length >= 1) { firstLine = lines[0].replace(' has a', '') + ' =' + cost[0]; secondLine = lines[1]; } if(!cost) firstLine = api_result.abstract.replace(/\./, ""); return { title: DDG.strip_html(firstLine), subtitle: DDG.strip_html(secondLine) }; }, templates: { group: 'text', options: { moreAt: true } } }); } }(this));
(function(env) { env.ddg_spice_expatistan = function(api_result) { "use strict"; if(!api_result || api_result.status !== 'OK') { return Spice.failed('expatistan'); } Spice.add({ id: "expatistan", name: "Answer", data: api_result, meta: { sourceUrl: api_result.source_url, sourceName: 'Expatistan' }, normalize: function(item) { // Split abstract in order to get // two separate strings and modify the first if (!api_result.abstract) { return null; } var lines = api_result.abstract.split(/of\s[0-9]+\s/); var cost = api_result.abstract.match(/\s[0-9]+\s/); var firstLine = ''; var secondLine = ''; if (lines.length === 2 && cost.length >= 1) { firstLine = lines[0].replace(' has a', '') + ' =' + cost[0]; secondLine = lines[1]; } if(!cost) firstLine = lines[0].replace(/\./, ""); return { title: DDG.strip_html(firstLine), subtitle: DDG.strip_html(secondLine) }; }, templates: { group: 'text', options: { moreAt: true } } }); } }(this));
Make short unit extraction script idempotent
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit and not each.short_unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
import os import sys sys.path.insert(1, os.path.join(sys.path[0], '../..')) import owid_grapher.wsgi from grapher_admin.models import Variable # use this script to extract and write short forms of unit of measurement for all variables that already exit in the db common_short_units = ['$', '£', '€', '%'] all_variables = Variable.objects.filter(fk_dst_id__namespace='wdi') for each in all_variables: if each.unit: if ' per ' in each.unit: short_form = each.unit.split(' per ')[0] if any(w in short_form for w in common_short_units): for x in common_short_units: if x in short_form: each.short_unit = x each.save() break else: each.short_unit = short_form each.save() elif any(x in each.unit for x in common_short_units): for y in common_short_units: if y in each.unit: each.short_unit = y each.save() break elif len(each.unit) < 9: # this length is sort of arbitrary at this point, taken from the unit 'hectares' each.short_unit = each.unit each.save()
Change the DB VM seed
<?php use Illuminate\Database\Seeder; use REBELinBLUE\Deployer\Server; class ServerTableSeeder extends Seeder { public function run() { DB::table('servers')->delete(); Server::create([ 'name' => 'Web VM', 'ip_address' => '192.168.33.50', 'user' => 'deploy', 'path' => '/var/www', 'project_id' => 1, 'deploy_code' => true, ]); Server::create([ 'name' => 'Cron VM', 'ip_address' => '192.168.33.60', 'user' => 'deploy', 'path' => '/var/www', 'project_id' => 1, 'deploy_code' => true, ]); Server::create([ 'name' => 'Database VM', 'ip_address' => '192.168.33.70', 'user' => 'deploy', 'path' => '/home/deploy', 'project_id' => 1, 'deploy_code' => false, ]); } }
<?php use Illuminate\Database\Seeder; use REBELinBLUE\Deployer\Server; class ServerTableSeeder extends Seeder { public function run() { DB::table('servers')->delete(); Server::create([ 'name' => 'Web VM', 'ip_address' => '192.168.33.50', 'user' => 'deploy', 'path' => '/var/www', 'project_id' => 1, 'deploy_code' => true, ]); Server::create([ 'name' => 'Cron VM', 'ip_address' => '192.168.33.60', 'user' => 'deploy', 'path' => '/var/www', 'project_id' => 1, 'deploy_code' => true, ]); Server::create([ 'name' => 'DB VM', 'ip_address' => '192.168.33.70', 'user' => 'deploy', 'path' => '/var/www', 'project_id' => 1, 'deploy_code' => false, ]); } }
Support cloning in UncDirectory constructor
class UncDirectory(object): def __init__(self, path, username=None, password=None): if hasattr(path, 'path') and hasattr(path, 'username') and hasattr(path, 'password'): self.path = path.path self.username = path.username self.password = path.password else: self.path = path self.username = username self.password = password def __eq__(self, other): try: return (self.get_normalized_path() == other.get_normalized_path() and self.username == other.username and self.password == other.password) except AttributeError: return False def get_normalized_path(self): """ Returns the normalized path for this `UncDirectory`. Differing UNC paths that all point to the same network location will have the same normalized path. """ path = self.path.lower() return path[:-5] if path.endswith(r'\ipc$') else path.rstrip('\\') def __str__(self): return '{username}{password}{at}{path}'.format( username=self.username, password=':' + self.password if self.password else '', at='@' if self.username or self.password else '', path=self.path) def __repr__(self): return '<{cls}: {str}>'.format(cls=self.__class__.__name__, str=str(self))
class UncDirectory(object): def __init__(self, path, username=None, password=None): self.path = path self.username = username self.password = password def __eq__(self, other): try: return (self.get_normalized_path() == other.get_normalized_path() and self.username == other.username and self.password == other.password) except AttributeError: return False def get_normalized_path(self): """ Returns the normalized path for this `UncDirectory`. Differing UNC paths that all point to the same network location will have the same normalized path. """ path = self.path.lower() return path[:-5] if path.endswith(r'\ipc$') else path.rstrip('\\') def __str__(self): return '{username}{password}{at}{path}'.format( username=self.username, password=':' + self.password if self.password else '', at='@' if self.username or self.password else '', path=self.path) def __repr__(self): return '<{cls}: {str}>'.format(cls=self.__class__.__name__, str=str(self))
[Fluid] Add lineMarker for template to identifier to prevent flickering
package com.cedricziel.idea.fluid.codeInsight; import com.cedricziel.idea.fluid.lang.psi.FluidFile; import com.cedricziel.idea.fluid.util.FluidUtil; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.patterns.PlatformPatterns; import com.intellij.psi.PsiElement; import com.jetbrains.php.lang.lexer.PhpTokenTypes; import com.jetbrains.php.lang.psi.elements.Method; import icons.FluidIcons; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider { @Override protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) { if (!PlatformPatterns.psiElement(PhpTokenTypes.IDENTIFIER).withParent(PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action"))).accepts(element)) { return; } Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element.getParent()); if (possibleMatchedTemplates.size() > 0) { result.add( NavigationGutterIconBuilder .create(FluidIcons.TEMPLATE_LINE_MARKER) .setTargets(possibleMatchedTemplates) .setTooltipText("Navigate to template") .createLineMarkerInfo(element) ); } } }
package com.cedricziel.idea.fluid.codeInsight; import com.cedricziel.idea.fluid.lang.psi.FluidFile; import com.cedricziel.idea.fluid.util.FluidUtil; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerInfo; import com.intellij.codeInsight.daemon.RelatedItemLineMarkerProvider; import com.intellij.codeInsight.navigation.NavigationGutterIconBuilder; import com.intellij.patterns.PlatformPatterns; import com.intellij.psi.PsiElement; import com.jetbrains.php.lang.psi.elements.Method; import icons.FluidIcons; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class ControllerLineMarkerProvider extends RelatedItemLineMarkerProvider { @Override protected void collectNavigationMarkers(@NotNull PsiElement element, @NotNull Collection<? super RelatedItemLineMarkerInfo> result) { if (!PlatformPatterns.psiElement(Method.class).withName(PlatformPatterns.string().endsWith("Action")).accepts(element)) { return; } Collection<FluidFile> possibleMatchedTemplates = FluidUtil.findTemplatesForControllerAction((Method) element); if (possibleMatchedTemplates.size() > 0) { result.add( NavigationGutterIconBuilder .create(FluidIcons.TEMPLATE_LINE_MARKER) .setTargets(possibleMatchedTemplates) .setTooltipText("Navigate to template") .createLineMarkerInfo(element) ); } } }
Remove unnecessary trailing slash in host config
<?php namespace Bundle\ApcBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; class ApcExtension extends Extension { public function configLoad($config, ContainerBuilder $container) { if(isset($config['host'])) { $container->setParameter('apc.host', trim($config['host'], '/')); } else { throw new \InvalidArgumentException('You must provide the host (e.g. http/example.com)'); } if(isset($config['web_dir'])) { $container->setParameter('apc.web_dir', $config['web_dir']); } else { throw new \InvalidArgumentException('You must provide the web_dir (e.g. %kernel.root_dir%/../web)'); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'apc'; } }
<?php namespace Bundle\ApcBundle\DependencyInjection; use Symfony\Component\DependencyInjection\Extension\Extension; use Symfony\Component\DependencyInjection\Loader\XmlFileLoader; use Symfony\Component\DependencyInjection\ContainerBuilder; class ApcExtension extends Extension { public function configLoad($config, ContainerBuilder $container) { if(isset($config['host'])) { $container->setParameter('apc.host', trim($config['host'], '/').'/'); } else { throw new \InvalidArgumentException('You must provide the host (e.g. http/example.com)'); } if(isset($config['web_dir'])) { $container->setParameter('apc.web_dir', $config['web_dir']); } else { throw new \InvalidArgumentException('You must provide the web_dir (e.g. %kernel.root_dir%/../web)'); } } /** * Returns the base path for the XSD files. * * @return string The XSD base path */ public function getXsdValidationBasePath() { return null; } public function getNamespace() { return 'http://www.symfony-project.org/schema/dic/symfony'; } public function getAlias() { return 'apc'; } }
Remove unecessary ifram param in headerAction
<?php namespace Biopen\CoreBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class CoreController extends Controller { public function homeAction() { $em = $this->get('doctrine_mongodb')->getManager(); // Get Wrapper List $listWrappers = $em->getRepository('BiopenCoreBundle:Wrapper') ->findAllOrderedByPosition(); $mainCategory = $em->getRepository('BiopenGeoDirectoryBundle:Taxonomy') ->findMainCategory(); $mainOptions = $mainCategory->getOptions(); $this->get('session')->clear(); return $this->render('@BiopenCoreBundle/home.html.twig', array('listWrappers' => $listWrappers, 'mainOptions' => $mainOptions)); } public function headerAction() { $em = $this->get('doctrine_mongodb')->getManager(); // Get About List $listAbouts = $em->getRepository('BiopenCoreBundle:About') ->findAllOrderedByPosition(); return $this->render('@BiopenCoreBundle/header.html.twig', array('listAbouts' => $listAbouts)); } public function partnersAction() { $repository = $this ->get('doctrine_mongodb')->getManager() ->getRepository('BiopenCoreBundle:Partner'); $listPartners = $repository->findAllOrderedByPosition(); return $this->render('@BiopenCoreBundle/partners.html.twig', array('listPartners' => $listPartners)); } }
<?php namespace Biopen\CoreBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; class CoreController extends Controller { public function homeAction() { $em = $this->get('doctrine_mongodb')->getManager(); // Get Wrapper List $listWrappers = $em->getRepository('BiopenCoreBundle:Wrapper') ->findAllOrderedByPosition(); $mainCategory = $em->getRepository('BiopenGeoDirectoryBundle:Taxonomy') ->findMainCategory(); $mainOptions = $mainCategory->getOptions(); $this->get('session')->clear(); return $this->render('@BiopenCoreBundle/home.html.twig', array('listWrappers' => $listWrappers, 'mainOptions' => $mainOptions)); } public function headerAction($iframe) $em = $this->get('doctrine_mongodb')->getManager(); // Get About List $listAbouts = $em->getRepository('BiopenCoreBundle:About') ->findAllOrderedByPosition(); return $this->render('@BiopenCoreBundle/header.html.twig', array('listAbouts' => $listAbouts, 'iframe' => $iframe)); } public function partnersAction() { $repository = $this ->get('doctrine_mongodb')->getManager() ->getRepository('BiopenCoreBundle:Partner'); $listPartners = $repository->findAllOrderedByPosition(); return $this->render('@BiopenCoreBundle/partners.html.twig', array('listPartners' => $listPartners)); } }
Handle case of undefined document list as result of search
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if ((documents == undefined) || (documents.length == 0)) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if (documents.length == 0) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
Add back rotatation for scroll job.
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.set_rotate() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
import scrollphat from pijobs.scrollphatjob import ScrollphatJob class ScrollJob(ScrollphatJob): def default_options(self): opts = { 'brightness': 2, 'interval': 0.1, 'sleep': 1.0, } return opts def init(self): self.set_brightness() self.write_message() def write_message(self): message = self.parse_message() scrollphat.write_string(message, 11) def message(self): return self.options['message'] def parse_message(self): message = self.message() + ' ' if self.options['upper'] == True: message = message.upper() return message def run(self): length = scrollphat.buffer_len() if self.options['loop'] == True: counter = 0 while True: self.scroll() counter += 1 if counter % length == 0: time.sleep(self.options['sleep']) else: for i in range(length): self.scroll() self.sleep() def scroll(self): scrollphat.scroll() self.sleep_interval()
Fix AJAX response class constructor.
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\HttpFoundation; use Symfony\Component\HttpFoundation\JsonResponse; /** * AJAX response */ class AjaxResponse extends JsonResponse { /** * @param string $html HTML * @param bool $success Is success * @param string $message Message * @param bool $reloadPage Whether to reload page * @param array $data Additional data * @param int $status Response status code * @param array $headers Response headers */ public function __construct( $html = '', $success = true, $message = null, $reloadPage = false, array $data = array(), $status = 200, array $headers = array() ) { parent::__construct(array_merge($data, array( 'html' => $html, 'message' => $message, 'reloadPage' => $reloadPage, 'success' => $success, )), $status, $headers); } }
<?php /** * @author Igor Nikolaev <[email protected]> * @copyright Copyright (c) 2015, Darvin Studio * @link https://www.darvin-studio.ru * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Darvin\Utils\HttpFoundation; use Symfony\Component\HttpFoundation\JsonResponse; /** * AJAX response */ class AjaxResponse extends JsonResponse { /** * @param string $html HTML * @param bool $success Is success * @param string $message Message * @param bool $reloadPage Whether to reload page * @param array $data Additional data * @param int $status Response status code * @param array $headers Response headers */ public function __construct( $html = '', $success = true, $message = null, $reloadPage = false, array $data = array(), $status = 200, array $headers = array() ) { parent::__construct(array_merge($data, array( 'html' => $html, 'message' => $message, 'reloadPage' => $reloadPage, 'success' => $success, ), $status, $headers)); } }
Make StringMatch questions use new choice type
/** * Copyright 2016 James Sharkey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["app/honest/responsive_video"], function(rv) { return ["api", function(api) { return { scope: true, restrict: 'A', templateUrl: "/partials/content/StringMatchQuestion.html", controller: ["$scope", function(scope) { var ctrl = this; ctrl.selectedValue = null; scope.$watch("ctrl.selectedValue", function(v, oldV) { if (v === oldV) { return; // Init } scope.question.selectedChoice = scope.question.selectedChoice || { type: "stringChoice" }; scope.question.selectedChoice.value = v; }); if (scope.question.selectedChoice) { ctrl.selectedValue = scope.question.selectedChoice.value; } }], controllerAs: "ctrl", }; }]; });
/** * Copyright 2016 James Sharkey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["app/honest/responsive_video"], function(rv) { return ["api", function(api) { return { scope: true, restrict: 'A', templateUrl: "/partials/content/StringMatchQuestion.html", controller: ["$scope", function(scope) { var ctrl = this; ctrl.selectedValue = null; scope.$watch("ctrl.selectedValue", function(v, oldV) { if (v === oldV) { return; // Init } scope.question.selectedChoice = scope.question.selectedChoice || { type: "choice" }; scope.question.selectedChoice.value = v; }); if (scope.question.selectedChoice) { ctrl.selectedValue = scope.question.selectedChoice.value; } }], controllerAs: "ctrl", }; }]; });
Fix bug in BeanExtractor (DynaBeanItem was not recognized)
package org.tylproject.vaadin.addon.utils; import com.vaadin.addon.jpacontainer.EntityItem; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; import org.vaadin.viritin.DynaBeanItem; import org.vaadin.viritin.ListContainer; /** * Extracts bean from an Item, depending on the Container implementation */ public class DefaultBeanExtractor implements BeanExtractor { @Override public Object extract(Object itemId, Item item) throws IllegalArgumentException { final Class<?> itemClass = item.getClass(); Object bean; if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass) || DynaBeanItem.class.isAssignableFrom(itemClass)) { bean = itemId; } else if (isJPAContainer(itemClass)) { bean = ((EntityItem<?>)item).getEntity(); } else if (BeanItem.class.isAssignableFrom(item.getClass())) { bean = ((BeanItem<?>) item).getBean(); } else{ throw new UnsupportedOperationException( "Unknown item type: "+itemClass.getCanonicalName()); } return bean; } protected boolean isJPAContainer(Class<?> itemClass) { try { return EntityItem.class.isAssignableFrom(itemClass); } catch (NoClassDefFoundError ex) { return false; } } }
package org.tylproject.vaadin.addon.utils; import com.vaadin.addon.jpacontainer.EntityItem; import com.vaadin.data.Item; import com.vaadin.data.util.BeanItem; import org.vaadin.viritin.DynaBeanItem; import org.vaadin.viritin.ListContainer; /** * Extracts bean from an Item, depending on the Container implementation */ public class DefaultBeanExtractor implements BeanExtractor { @Override public Object extract(Object itemId, Item item) throws IllegalArgumentException { final Class<?> itemClass = item.getClass(); Object bean; if (ListContainer.DynaBeanItem.class.isAssignableFrom(itemClass)) { bean = itemId; } else if (isJPAContainer(itemClass)) { bean = ((EntityItem<?>)item).getEntity(); } else if (BeanItem.class.isAssignableFrom(item.getClass())) { bean = ((BeanItem<?>) item).getBean(); } else{ throw new UnsupportedOperationException( "Unknown item type: "+itemClass.getCanonicalName()); } return bean; } protected boolean isJPAContainer(Class<?> itemClass) { try { return EntityItem.class.isAssignableFrom(itemClass); } catch (NoClassDefFoundError ex) { return false; } } }
Use ->guard() instead of ->driver(). Signed-off-by: crynobone <[email protected]>
<?php namespace Orchestra\Auth; use Orchestra\Authorization\Policy; use Illuminate\Contracts\Foundation\Application; use Illuminate\Auth\AuthServiceProvider as ServiceProvider; use Orchestra\Contracts\Authorization\Factory as FactoryContract; class AuthServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { parent::register(); $this->registerPolicyAfterResolvingHandler(); } /** * Register the service provider for Auth. * * @return void */ protected function registerAuthenticator() { $this->app->singleton('auth', function (Application $app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->singleton('auth.driver', function (Application $app) { return $app->make('auth')->guard(); }); } /** * Register the Policy after resolving handler. * * @return void */ protected function registerPolicyAfterResolvingHandler() { $this->app->afterResolving(Policy::class, function (Policy $policy) { return $policy->setAuthorization($this->app->make(FactoryContract::class)); }); } }
<?php namespace Orchestra\Auth; use Orchestra\Authorization\Policy; use Illuminate\Contracts\Foundation\Application; use Illuminate\Auth\AuthServiceProvider as ServiceProvider; use Orchestra\Contracts\Authorization\Factory as FactoryContract; class AuthServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { parent::register(); $this->registerPolicyAfterResolvingHandler(); } /** * Register the service provider for Auth. * * @return void */ protected function registerAuthenticator() { $this->app->singleton('auth', function (Application $app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new AuthManager($app); }); $this->app->singleton('auth.driver', function (Application $app) { return $app->make('auth')->driver(); }); } /** * Register the Policy after resolving handler. * * @return void */ protected function registerPolicyAfterResolvingHandler() { $this->app->afterResolving(Policy::class, function (Policy $policy) { return $policy->setAuthorization($this->app->make(FactoryContract::class)); }); } }
Add a vararg constructor for the Tabbed Panel
package lt.inventi.wicket.component.bootstrap.tab; import java.util.Arrays; import java.util.List; import org.apache.wicket.extensions.markup.html.tabs.ITab; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.IModel; import org.apache.wicket.util.string.StringValue; import de.agilecoders.wicket.markup.html.bootstrap.tabs.BootstrapTabbedPanel; public class RememberingTabbedPanel<T extends ITab> extends BootstrapTabbedPanel<T> { public RememberingTabbedPanel(String id, List<T> tabs, IModel<Integer> model) { super(id, tabs, model); } public RememberingTabbedPanel(String id, List<T> tabs) { super(id, tabs); } public RememberingTabbedPanel(String id, T... tabs) { super(id, Arrays.asList(tabs)); } @Override protected void onInitialize() { super.onInitialize(); StringValue selectedTabId = getPage().getPageParameters().get(getId()); if (selectedTabId.isEmpty()) { setSelectedTab(0); } else { setSelectedTab(selectedTabId.toInt()); } } @Override protected WebMarkupContainer newLink(String linkId, final int index) { return new Link<Void>(linkId) { @Override public void onClick() { setSelectedTab(index); getPage().getPageParameters().set(RememberingTabbedPanel.this.getId(), String.valueOf(index)); } }; } }
package lt.inventi.wicket.component.bootstrap.tab; import java.util.List; import org.apache.wicket.extensions.markup.html.tabs.ITab; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.link.Link; import org.apache.wicket.model.IModel; import org.apache.wicket.util.string.StringValue; import de.agilecoders.wicket.markup.html.bootstrap.tabs.BootstrapTabbedPanel; public class RememberingTabbedPanel<T extends ITab> extends BootstrapTabbedPanel<T> { public RememberingTabbedPanel(String id, List<T> tabs, IModel<Integer> model) { super(id, tabs, model); } public RememberingTabbedPanel(String id, List<T> tabs) { super(id, tabs); } @Override protected void onInitialize() { super.onInitialize(); StringValue selectedTabId = getPage().getPageParameters().get(getId()); if (selectedTabId.isEmpty()) { setSelectedTab(0); } else { setSelectedTab(selectedTabId.toInt()); } } @Override protected WebMarkupContainer newLink(String linkId, final int index) { return new Link<Void>(linkId) { @Override public void onClick() { setSelectedTab(index); getPage().getPageParameters().set(RememberingTabbedPanel.this.getId(), String.valueOf(index)); } }; } }
Fix extra in case of fragmented sources
from collections import namedtuple Event = namedtuple('Event', ['id', 'type', 'data']) def parse(source): eid = None etype = None data = [] retry = None extra = '' dispatch = False cursor = 0 lines = source.splitlines() for line in lines: if not line: dispatch = True extra = source[cursor+1:] break if not ':' in line: field, value = line, '' else: field, value = line.split(':', 1) if value and value[0] == ' ': value = value[1:] if field == 'data': data.append(value) elif field == 'event': etype = value elif field == 'id': eid = value elif field == 'retry': retry = int(value) cursor += len(line) + 1 if not dispatch: return None, source if data: data = '\n'.join(data) if retry: if etype or data: extra = ('retry: %s\n\n' % retry) + extra else: etype, data = 'retry', retry return Event(eid, etype, data), extra
from collections import namedtuple Event = namedtuple('Event', ['id', 'type', 'data']) def parse(source): eid = None etype = None data = [] retry = None extra = '' dispatch = False lines = source.splitlines() for line in lines: if dispatch: extra += line + '\n' continue if not line: dispatch = True continue if not ':' in line: field, value = line, '' else: field, value = line.split(':', 1) if value and value[0] == ' ': value = value[1:] if field == 'data': data.append(value) elif field == 'event': etype = value elif field == 'id': eid = value elif field == 'retry': retry = int(value) if not dispatch: return None, source if data: data = '\n'.join(data) if retry: if etype or data: extra = ('retry: %s\n\n' % retry) + extra else: etype, data = 'retry', retry return Event(eid, etype, data), extra
Change the name "name" to "key" to support the backend structure of holding annotation elements
/** * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ define( function () { /** * @class AnnotationElement * @constructor * @class AnnotationElement Creates an object to hold an annotation element * @param {key} to store the property of the annotation element * @param {value} to store the property's value of the annotation element */ var AnnotationElement = function (key, value) { this.key = key; this.value = value; }; AnnotationElement.prototype.getKey = function () { return this.key; }; AnnotationElement.prototype.setKey= function (key) { this.key = key; }; AnnotationElement.prototype.getValue = function () { return this.value; }; AnnotationElement.prototype.setValue = function (value) { this.value = value; }; return AnnotationElement; });
/** * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ define( function () { /** * @class AnnotationElement * @constructor * @class AnnotationElement Creates an object to hold an annotation element * @param {key} to store the property of the annotation element * @param {value} to store the property's value of the annotation element */ var AnnotationElement = function (name, value) { this.name = name; this.value = value; }; AnnotationElement.prototype.getName = function () { return this.key; }; AnnotationElement.prototype.setName= function (name) { this.name = name; }; AnnotationElement.prototype.getValue = function () { return this.value; }; AnnotationElement.prototype.setValue = function (value) { this.value = value; }; return AnnotationElement; });
Use a private I/O thread pool for failure detector
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.failureDetector; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import org.weakref.jmx.guice.ExportBinder; import static io.airlift.configuration.ConfigurationModule.bindConfig; import static io.airlift.http.client.HttpClientBinder.httpClientBinder; public class FailureDetectorModule implements Module { @Override public void configure(Binder binder) { httpClientBinder(binder) .bindAsyncHttpClient("failure-detector", ForFailureDetector.class) .withPrivateIoThreadPool() .withTracing(); bindConfig(binder).to(FailureDetectorConfig.class); binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON); binder.bind(FailureDetector.class) .to(HeartbeatFailureDetector.class) .in(Scopes.SINGLETON); ExportBinder.newExporter(binder) .export(HeartbeatFailureDetector.class) .withGeneratedName(); } }
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.failureDetector; import com.google.inject.Binder; import com.google.inject.Module; import com.google.inject.Scopes; import org.weakref.jmx.guice.ExportBinder; import static io.airlift.configuration.ConfigurationModule.bindConfig; import static io.airlift.http.client.HttpClientBinder.httpClientBinder; public class FailureDetectorModule implements Module { @Override public void configure(Binder binder) { httpClientBinder(binder) .bindAsyncHttpClient("failure-detector", ForFailureDetector.class) .withTracing(); bindConfig(binder).to(FailureDetectorConfig.class); binder.bind(HeartbeatFailureDetector.class).in(Scopes.SINGLETON); binder.bind(FailureDetector.class) .to(HeartbeatFailureDetector.class) .in(Scopes.SINGLETON); ExportBinder.newExporter(binder) .export(HeartbeatFailureDetector.class) .withGeneratedName(); } }
Update company logos if they didn't previously have one but they do now
<?php namespace GoRemote\Model; class CompanyModel { public $id = 0; public $name; public $url = ''; public $twitter; public $logo; public function insert(\Doctrine\DBAL\Connection $db) { $duplicateId = $db->fetchAssoc( 'select companyid, url, logo from companies where name=?', [ (string) $this->name ]); if ($duplicateId) { if (empty($duplicateId['logo']) && !empty($this->logo)) { $db->createQueryBuilder() ->update('companies') ->set('logo', '?') ->where('companyid = ?') ->setParameter(0, $this->logo) ->setParameter(1, $duplicateId['companyid']) ->execute(); } $this->id = $duplicateId; return $duplicateId; } $company = [ 'name' => $this->name, 'dateadded' => date('Y-m-d H:i:s'), 'logo' => $this->logo, 'twitter' => $this->twitter, 'url' => $this->url ]; $db->insert('companies', $company); $this->id = $db->lastInsertId(); return $this->id; } }
<?php namespace GoRemote\Model; class CompanyModel { public $id = 0; public $name; public $url = ''; public $twitter; public $logo; public function insert(\Doctrine\DBAL\Connection $db) { $duplicateId = $db->fetchAssoc( 'select companyid, url, logo from companies where name=?', [ (string) $this->name ]); if ($duplicateId) { if (empty($duplicateId['logo']) && !empty($this->logo)) { $db->createQueryBuilder() ->update('companies') ->set('logo', '?') ->where('companyid = ?') ->setParameter(0, $this->logo) ->setParameter(1, $duplicateId['companyid']); } $this->id = $duplicateId; return $duplicateId; } $company = [ 'name' => $this->name, 'dateadded' => date('Y-m-d H:i:s'), 'logo' => $this->logo, 'twitter' => $this->twitter, 'url' => $this->url ]; $db->insert('companies', $company); $this->id = $db->lastInsertId(); return $this->id; } }
Make sure we always use the same filename for the fixtures translations. This way the translations do not contain accidental changes.
import json import os from django.core.management.commands.makemessages import Command as BaseCommand from bluebottle.clients.utils import get_currencies class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): with open('bluebottle/fixtures.py', 'w') as temp: for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: strings = [ fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file) ] for string in strings: temp.write('gettext("{}")\n'.format(string)) for currency in get_currencies(): temp.write('gettext("{}")\n'.format(currency['name'])) temp.flush() super(Command, self).handle(*args, **kwargs) os.unlink('bluebottle/fixtures.py')
import json import tempfile from django.core.management.commands.makemessages import Command as BaseCommand from bluebottle.clients.utils import get_currencies class Command(BaseCommand): """ Extend the makemessages to include some of the fixtures """ fixtures = [ ('bb_projects', 'project_data.json'), ('bb_tasks', 'skills.json'), ('geo', 'geo_data.json'), ] def handle(self, *args, **kwargs): with tempfile.NamedTemporaryFile(dir='bluebottle', suffix='.py') as temp: for app, file in self.fixtures: with open('bluebottle/{}/fixtures/{}'.format(app, file)) as fixture_file: strings = [ fixture['fields']['name'].encode('utf-8') for fixture in json.load(fixture_file) ] for string in strings: temp.write('gettext("{}")\n'.format(string)) for currency in get_currencies(): temp.write('gettext("{}")\n'.format(currency['name'])) temp.flush() return super(Command, self).handle(*args, **kwargs)
Rename tests to better reflect field meaning
package de.innoaccel.wamp.server.converter; import de.innoaccel.wamp.server.Websocket; import de.innoaccel.wamp.server.message.Message; import org.junit.Test; import java.io.IOException; abstract public class GeneralMessageTests<T extends Message> { protected JsonParsingConverter<T> converter; @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("message", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenThereIsNoMessageCodeField(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoNumber(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[null]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageCodeIsNoInteger(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[0.5f]", socket); } @Test(expected = InvalidMessageCodeException.class) public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[" + Message.INVALID + "]", socket); } }
package de.innoaccel.wamp.server.converter; import de.innoaccel.wamp.server.Websocket; import de.innoaccel.wamp.server.message.Message; import org.junit.Test; import java.io.IOException; abstract public class GeneralMessageTests<T extends Message> { protected JsonParsingConverter<T> converter; @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenMessageIsNoArray(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("message", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenThereIsNoFirstField(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoNumber(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[null]", socket); } @Test(expected = MessageParseException.class) public void deserializeThrowsMessageParseExceptionWhenFirstFieldIsNoInteger(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[0.5f]", socket); } @Test(expected = InvalidMessageCodeException.class) public void deserializeThrowsInvalidMessageCodeExceptionWhenWrongMessageCode(final Websocket socket) throws IOException, MessageParseException, InvalidMessageCodeException { this.converter.deserialize("[" + Message.INVALID + "]", socket); } }
Clarify arguments in tests slightly
from planterbox import ( step, hook, ) hooks_run = set() @hook('before', 'feature') def before_feature_hook(feature_suite): global hooks_run hooks_run.add(('before', 'feature')) @hook('before', 'scenario') def before_scenario_hook(test): global hooks_run hooks_run.add(('before', 'scenario')) @hook('before', 'step') def before_step_hook(step_text): global hooks_run hooks_run.add(('before', 'step')) @step(r'I verify that all before hooks have run') def verify_before_hooks(test): global hooks_run assert hooks_run == {('before', 'feature'), ('before', 'scenario'), ('before', 'step'), } @hook('after', 'feature') def after_feature_hook(feature_suite): global hooks_run hooks_run.add(('after', 'feature')) assert hooks_run == {('before', 'feature'), ('before', 'scenario'), ('before', 'step'), ('after', 'feature'), ('after', 'scenario'), ('after', 'step'), } @hook('after', 'scenario') def after_scenario_hook(test): global hooks_run hooks_run.add(('after', 'scenario')) @hook('after', 'step') def after_step_hook(step_text): global hooks_run hooks_run.add(('after', 'step'))
from planterbox import ( step, hook, ) hooks_run = set() @hook('before', 'feature') def before_feature_hook(feature_suite): global hooks_run hooks_run.add(('before', 'feature')) @hook('before', 'scenario') def before_scenario_hook(scenario_test): global hooks_run hooks_run.add(('before', 'scenario')) @hook('before', 'step') def before_step_hook(step_text): global hooks_run hooks_run.add(('before', 'step')) @step(r'I verify that all before hooks have run') def verify_before_hooks(world): global hooks_run assert hooks_run == {('before', 'feature'), ('before', 'scenario'), ('before', 'step'), } @hook('after', 'feature') def after_feature_hook(feature_suite): global hooks_run hooks_run.add(('after', 'feature')) assert hooks_run == {('before', 'feature'), ('before', 'scenario'), ('before', 'step'), ('after', 'feature'), ('after', 'scenario'), ('after', 'step'), } @hook('after', 'scenario') def after_scenario_hook(scenario_test): global hooks_run hooks_run.add(('after', 'scenario')) @hook('after', 'step') def after_step_hook(step_text): global hooks_run hooks_run.add(('after', 'step'))
Change code to be compliant with PEP 8 This change camel cased functions for underscored function names and properties.
import subprocess import os class PHPLint: def __init__(self): self.silent = False def set_silent_lint(self, is_silent): self.silent = is_silent def lint(self, path): if os.path.isfile(path): self.lint_file(path) elif os.path.isdir(path): self.lint_dir(path) def lint_file(self, path): if self.is_php_file(path): process = subprocess.Popen(['php', '-l', path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (process_stdout, process_stderr) = process.communicate(); if not self.is_silent_lint(): print process_stdout.rstrip() if process.returncode > 0: print process_stderr.rstrip() raise SystemExit(1) def lint_dir(self, path): for root_dir, dir_name, files in os.walk(path): for f in files: self.lint_file(os.path.join(root_dir, f)) def is_php_file(self, filename): return filename.endswith('.php') def is_silent_lint(self): return self.silent
import subprocess import os class PHPLint: def __init__(self): self.silent = False def setSilentLint(self, isSilent): self.silent = isSilent def lint(self, path): if os.path.isfile(path): self.lintFile(path) elif os.path.isdir(path): self.lintDir(path) def lintFile(self, path): if self.isPHPFile(path): process = subprocess.Popen(['php', '-l', path], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE) (processStdOut, processStdErr) = process.communicate(); if not self.isSilentLint(): print processStdOut.rstrip() if process.returncode > 0: print processStdErr.rstrip() raise SystemExit(1) def lintDir(self, path): for rootDir, dirName, files in os.walk(path): for f in files: self.lintFile(os.path.join(rootDir, f)) def isPHPFile(self, filename): return filename.endswith('.php') def isSilentLint(self): return self.silent
Disable native pi calculator test for the moment
package com.github.michaelkhw.playground.pi; import com.github.michaelkhw.playground.timer.NanoTimer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; /** * Created by michael on 21/3/15. */ @RunWith(Parameterized.class) public class PiCalculatorTest { private PiCalculator calculator; @Parameterized.Parameters(name = "{index}: PiCalculatorTest({0})") public static Collection<Object[]> testParameters() { return Arrays.asList( new Object[][]{ {"Akka", new AkkaPiCalculator()}, {"Simple", new SimplePiCalculator()}, //{"Native", new NativePiCalculator()} }); } public PiCalculatorTest(String name, PiCalculator calculator) { this.calculator = calculator; } @Test public void testCalculate() throws Exception { try { // Put a heavy Load to the calculator, attempting to JIT compile the method calculator.calculate(10000); // The actual work begins double actual; // This will took around 1-2 secs on my mac try (NanoTimer ignored = new NanoTimer()) { actual = calculator.calculate(100000000L); } assertEquals(3.14159, actual, 0.00001); } finally { if (calculator instanceof AutoCloseable) ((AutoCloseable) calculator).close(); } } }
package com.github.michaelkhw.playground.pi; import com.github.michaelkhw.playground.timer.NanoTimer; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; /** * Created by michael on 21/3/15. */ @RunWith(Parameterized.class) public class PiCalculatorTest { private PiCalculator calculator; @Parameterized.Parameters(name = "{index}: PiCalculatorTest({0})") public static Collection<Object[]> testParameters() { return Arrays.asList( new Object[][]{ {"Akka", new AkkaPiCalculator()}, {"Simple", new SimplePiCalculator()}, {"Native", new NativePiCalculator()} }); } public PiCalculatorTest(String name, PiCalculator calculator) { this.calculator = calculator; } @Test public void testCalculate() throws Exception { try { // Put a heavy Load to the calculator, attempting to JIT compile the method calculator.calculate(10000); // The actual work begins double actual; // This will took around 1-2 secs on my mac try (NanoTimer ignored = new NanoTimer()) { actual = calculator.calculate(100000000L); } assertEquals(3.14159, actual, 0.00001); } finally { if (calculator instanceof AutoCloseable) ((AutoCloseable) calculator).close(); } } }
Add missed traits for controller
<?php namespace GeniusTS\Preferences\Controllers; use GeniusTS\Preferences\Models\Domain; use GeniusTS\Preferences\Models\Element; use GeniusTS\Preferences\Models\Setting; use GeniusTS\Preferences\PreferencesManager; use Illuminate\Foundation\Bus\DispatchesJobs; use Symfony\Component\HttpFoundation\Response; use GeniusTS\Preferences\Requests\SettingsRequest; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; /** * Class SettingsController * * @package GeniusTS\Preferences */ abstract class SettingsController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; /** * @var PreferencesManager */ protected $preferences; /** * SettingsController constructor. */ public function __construct() { $this->preferences = resolve('preferences'); } /** * Handle update settings request * * @param \GeniusTS\Preferences\Requests\SettingsRequest $request * * @return \Symfony\Component\HttpFoundation\Response */ public function update(SettingsRequest $request) { /** @var Domain $domain */ foreach ($this->preferences->domains as $domain) { /** @var Element $element */ foreach ($domain->elements as $element) { $model = Setting::findBySlugOrNew($element->name, $domain->key); $model->value = $request->get($element->name, null); $model->save(); } } return $this->handleSuccessResponse(); } /** * @return Response */ abstract protected function handleSuccessResponse(); }
<?php namespace GeniusTS\Preferences\Controllers; use GeniusTS\Preferences\Models\Domain; use GeniusTS\Preferences\Models\Element; use GeniusTS\Preferences\Models\Setting; use GeniusTS\Preferences\PreferencesManager; use Symfony\Component\HttpFoundation\Response; use GeniusTS\Preferences\Requests\SettingsRequest; /** * Class SettingsController * * @package GeniusTS\Preferences */ abstract class SettingsController { /** * @var PreferencesManager */ protected $preferences; /** * SettingsController constructor. */ public function __construct() { $this->preferences = resolve('preferences'); } /** * Handle update settings request * * @param \GeniusTS\Preferences\Requests\SettingsRequest $request * * @return \Symfony\Component\HttpFoundation\Response */ public function update(SettingsRequest $request) { /** @var Domain $domain */ foreach ($this->preferences->domains as $domain) { /** @var Element $element */ foreach ($domain->elements as $element) { $model = Setting::findBySlugOrNew($element->name, $domain->key); $model->value = $request->get($element->name, null); $model->save(); } } return $this->handleSuccessResponse(); } /** * @return Response */ abstract protected function handleSuccessResponse(); }
Add logging filter for checking that the app is actually deployed (imported from commit 77bd7e008fdea4033e18a91d206999f9714e0f74)
import logging import traceback from hashlib import sha256 from datetime import datetime, timedelta # Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010) class _RateLimitFilter(object): last_error = datetime.min def filter(self, record): from django.conf import settings from django.core.cache import cache # Track duplicate errors duplicate = False rate = getattr(settings, '%s_LIMIT' % self.__class__.__name__.upper(), 600) # seconds if rate > 0: # Test if the cache works try: cache.set('RLF_TEST_KEY', 1, 1) use_cache = cache.get('RLF_TEST_KEY') == 1 except: use_cache = False if use_cache: key = self.__class__.__name__.upper() duplicate = cache.get(key) == 1 cache.set(key, 1, rate) else: min_date = datetime.now() - timedelta(seconds=rate) duplicate = (self.last_error >= min_date) if not duplicate: self.last_error = datetime.now() return not duplicate class HumbugLimiter(_RateLimitFilter): pass class EmailLimiter(_RateLimitFilter): pass class ReturnTrue(logging.Filter): def filter(self, record): return True class RequireReallyDeployed(logging.Filter): def filter(self, record): from django.conf import settings return settings.DEPLOYED and not settings.TESTING_DEPLOYED
import logging import traceback from hashlib import sha256 from datetime import datetime, timedelta # Adapted http://djangosnippets.org/snippets/2242/ by user s29 (October 25, 2010) class _RateLimitFilter(object): last_error = datetime.min def filter(self, record): from django.conf import settings from django.core.cache import cache # Track duplicate errors duplicate = False rate = getattr(settings, '%s_LIMIT' % self.__class__.__name__.upper(), 600) # seconds if rate > 0: # Test if the cache works try: cache.set('RLF_TEST_KEY', 1, 1) use_cache = cache.get('RLF_TEST_KEY') == 1 except: use_cache = False if use_cache: key = self.__class__.__name__.upper() duplicate = cache.get(key) == 1 cache.set(key, 1, rate) else: min_date = datetime.now() - timedelta(seconds=rate) duplicate = (self.last_error >= min_date) if not duplicate: self.last_error = datetime.now() return not duplicate class HumbugLimiter(_RateLimitFilter): pass class EmailLimiter(_RateLimitFilter): pass class ReturnTrue(logging.Filter): def filter(self, record): return True
Remove code prototype code where the settings variables were being modified, this code works in single threaded servers but might not work on multithreaded servers.
from django.conf import settings from crits.config.config import CRITsConfig def modify_configuration(forms, analyst): """ Modify the configuration with the submitted changes. :param config_form: The form data. :type config_form: dict :param analyst: The user making the modifications. :type analyst: str :returns: dict with key "message" """ config = CRITsConfig.objects().first() if not config: config = CRITsConfig() data = None for form in forms: if not data: data = form.cleaned_data else: data.update(form.cleaned_data) # data = config_form.cleaned_data allowed_hosts_list = data['allowed_hosts'].split(',') allowed_hosts = () for allowed_host in allowed_hosts_list: allowed_hosts = allowed_hosts + (allowed_host.strip(),) data['allowed_hosts'] = allowed_hosts service_dirs_list = data['service_dirs'].split(',') service_dirs = () for service_dir in service_dirs_list: service_dirs = service_dirs + (service_dir.strip(),) data['service_dirs'] = service_dirs config.merge(data, overwrite=True) try: config.save(username=analyst) return {'message': "Success!"} except Exception, e: return {'message': "Failure: %s" % e}
from django.conf import settings from crits.config.config import CRITsConfig def modify_configuration(forms, analyst): """ Modify the configuration with the submitted changes. :param config_form: The form data. :type config_form: dict :param analyst: The user making the modifications. :type analyst: str :returns: dict with key "message" """ config = CRITsConfig.objects().first() if not config: config = CRITsConfig() data = None for form in forms: if not data: data = form.cleaned_data else: data.update(form.cleaned_data) # data = config_form.cleaned_data allowed_hosts_list = data['allowed_hosts'].split(',') allowed_hosts = () for allowed_host in allowed_hosts_list: allowed_hosts = allowed_hosts + (allowed_host.strip(),) data['allowed_hosts'] = allowed_hosts service_dirs_list = data['service_dirs'].split(',') service_dirs = () for service_dir in service_dirs_list: service_dirs = service_dirs + (service_dir.strip(),) data['service_dirs'] = service_dirs config.merge(data, overwrite=True) try: config.save(username=analyst) settings.ENABLE_TOASTS = data['enable_toasts'] return {'message': "Success!"} except Exception, e: return {'message': "Failure: %s" % e}
Add fixture for the advert in the blog sidebar advert.
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'UP NEXT: LOREM IPSUM', 'body': '', 'url_text': 'GET INVOLVED', 'url': '', }, { 'slug': 'featured', 'name': 'FEATURED CONTENT', 'body': '', 'url_text': 'FEATURED', 'url': '', }, { 'slug': 'welcome-email', 'name': 'Welcome to US Ignite', 'body': '', 'url_text': '', 'url': '', }, { 'slug': 'blog-sidebar', 'name': 'Dynamic content', 'body': '', 'url_text': '', 'url': '', }, ] class Command(BaseCommand): def handle(self, *args, **options): for data in FIXTURES: try: # Ignore existing snippets: Snippet.objects.get(slug=data['slug']) continue except Snippet.DoesNotExist: pass data.update({ 'status': Snippet.PUBLISHED, }) Snippet.objects.create(**data) print u'Importing %s' % data['slug'] print "Done!"
from django.core.management.base import BaseCommand from us_ignite.snippets.models import Snippet FIXTURES = [ { 'slug': 'home-box', 'name': 'UP NEXT: LOREM IPSUM', 'body': '', 'url_text': 'GET INVOLVED', 'url': '', }, { 'slug': 'featured', 'name': 'FEATURED CONTENT', 'body': '', 'url_text': 'FEATURED', 'url': '', }, { 'slug': 'welcome-email', 'name': 'Welcome to US Ignite', 'body': '', 'url_text': '', 'url': '', }, ] class Command(BaseCommand): def handle(self, *args, **options): for data in FIXTURES: try: # Ignore existing snippets: Snippet.objects.get(slug=data['slug']) continue except Snippet.DoesNotExist: pass data.update({ 'status': Snippet.PUBLISHED, }) Snippet.objects.create(**data) print u'Importing %s' % data['slug'] print "Done!"
Exclude @ngrx modules from preloading
var path = require('path'); var webpack = require('webpack'); var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; module.exports = { devtool: 'source-map', debug: true, entry: { '@angular': [ 'rxjs', 'reflect-metadata', 'zone.js' ], 'common': ['es6-shim'], 'app': './src/app/app.component.ts' }, output: { path: __dirname + '/build/', publicPath: 'build/', filename: '[name].js', sourceMapFilename: '[name].js.map', chunkFilename: '[id].chunk.js' }, resolve: { extensions: ['','.ts','.js','.json', '.css', '.html'] }, module: { preLoaders: [ { test: /\.js$/, loader: 'source-map-loader', exclude: [ // these packages have problems with their sourcemaps helpers.root('node_modules/@ngrx/core'), helpers.root('node_modules/@ngrx/router') ] } ] loaders: [ { test: /\.tsx?$/, loader: 'ts', exclude: [ /node_modules/, /releases/ ] }, { test: /\.json$/, loader: 'json' }, { test: /\.(css|html)$/, loader: 'raw' }, { test: /\.(png|jpg)$/, loader: 'url?limit=10000' } ] }, plugins: [ new CommonsChunkPlugin({ names: ['@angular', 'common'], minChunks: Infinity }) ], target:'electron-renderer' };
var path = require('path'); var webpack = require('webpack'); var CommonsChunkPlugin = webpack.optimize.CommonsChunkPlugin; module.exports = { devtool: 'source-map', debug: true, entry: { '@angular': [ 'rxjs', 'reflect-metadata', 'zone.js' ], 'common': ['es6-shim'], 'app': './src/app/app.ts' }, output: { path: __dirname + '/build/', publicPath: 'build/', filename: '[name].js', sourceMapFilename: '[name].js.map', chunkFilename: '[id].chunk.js' }, resolve: { extensions: ['','.ts','.js','.json', '.css', '.html'] }, module: { loaders: [ { test: /\.ts$/, loader: 'ts', exclude: [ /node_modules/, /releases/ ] }, { test: /\.json$/, loader: 'json' }, { test: /\.(css|html)$/, loader: 'raw' }, { test: /\.(png|jpg)$/, loader: 'url?limit=10000' } ] }, plugins: [ new CommonsChunkPlugin({ names: ['@angular', 'common'], minChunks: Infinity }) ], target:'electron-renderer' };
Add help text for roll command
import random import re from cardinal.decorators import command, help def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$', arg): num_dice = 1 sides = match.group(1) else: return [] return [int(sides)] * int(num_dice) class RandomPlugin: @command('roll') @help("Roll dice") @help("Syntax: .roll #d# (e.g. .roll 2d6)") def roll(self, cardinal, user, channel, msg): args = msg.split(' ') args.pop(0) if not args: return dice = [] for arg in args: dice = dice + parse_roll(arg) results = [] limit = 10 for sides in dice: if sides < 2 or sides > 120: continue limit -= 1 # Don't allow more than ten dice rolled at a time if limit < 0: break results.append((sides, random.randint(1, sides))) messages = ', '.join( [f"d{sides}: {result}" for sides, result in results] ) cardinal.sendMsg(channel, messages) entrypoint = RandomPlugin
import random import re from cardinal.decorators import command def parse_roll(arg): # some people might separate with commas arg = arg.rstrip(',') if match := re.match(r'^(\d+)?d(\d+)$', arg): num_dice = match.group(1) sides = match.group(2) elif match := re.match(r'^d?(\d+)$', arg): num_dice = 1 sides = match.group(1) else: return [] return [int(sides)] * int(num_dice) class RandomPlugin: @command('roll') def roll(self, cardinal, user, channel, msg): args = msg.split(' ') args.pop(0) dice = [] for arg in args: dice = dice + parse_roll(arg) results = [] limit = 10 for sides in dice: if sides < 2 or sides > 120: continue limit -= 1 # Don't allow more than ten dice rolled at a time if limit < 0: break results.append((sides, random.randint(1, sides))) messages = ', '.join( [f"d{sides}: {result}" for sides, result in results] ) cardinal.sendMsg(channel, messages) entrypoint = RandomPlugin
Move button to top-left, need to adjust margins and padding
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; class Story extends Component{ onProfilePressed() { this.props.navigator.push({ title: 'Story', component: Profile }) } render() { return ( <View style={styles.container}> <TouchableHighlight onPress={this.onProfilePressed.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Ahmeds Profile </Text> </TouchableHighlight> <Text>Day 7</Text> <Text style={styles.title}> My neighbor Amira </Text> <Text style={styles.content}> Today I met another girl my age named Amira, her family is like mine...</Text> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, button: { height: 50, backgroundColor: '#48BBEC', alignSelf: 'flex-start', marginTop: 10, justifyContent: 'center' }, buttonText: { textAlign: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, content: { alignSelf: 'center', fontSize: 21, marginTop: 10, marginBottom: 5, }, }); module.exports = Story;
import React, { Component } from 'react'; import { StyleSheet, Text, View, TouchableHighlight, } from 'react-native'; class Story extends Component{ onProfilePressed() { this.props.navigator.push({ title: 'Story', component: Profile }) } render() { return ( <View style={styles.container}> <Text>Day 7</Text> <Text style={styles.title}> My neighbor Amira </Text> <Text style={styles.content}> Today I met another girl my age named Amira, her family is like mine...</Text> <TouchableHighlight onPress={this.onProfilePressed.bind(this)} style={styles.button}> <Text style={styles.buttonText}> Ahmeds Profile </Text> </TouchableHighlight> </View> ) } }; var styles = StyleSheet.create({ button: { height: 50, backgroundColor: '#48BBEC', alignSelf: 'stretch', marginTop: 10, justifyContent: 'center' }, buttonText: { textAlign: 'center', }, container: { flex: 1, justifyContent: 'center', alignItems: 'center', }, title: { fontSize: 20, alignSelf: 'center', margin: 40 }, content: { alignSelf: 'center', fontSize: 21, marginTop: 10, marginBottom: 5, }, }); module.exports = Story;
Adjust query selector for location of image
window.addEventListener("click", notifyExtension); function notifyExtension(e) { console.log("igcs.js: click on ${e}"); if (e.target.classList.contains("coreSpriteHeartFull")) { var parser = document.createElement('a'); parser.href = e.target.closest("article").querySelector("header a").href; var bio = document.getElementsByClassName("_bugdy"); if (bio.length > 0) { bio = bio[0].textContent; } else { bio = ''; } var pic_url = ''; var username = ''; var post = ''; var timestamp = ''; var location = ''; try { pic_url = e.target.closest("article").querySelector("img._2di5p").src; } catch (e) {} try { username = parser.pathname.replace("/","").replace("/",""); } catch (e) {} try { post = e.target.closest("article > div").querySelector("div > ul > li > span").textContent; } catch (e) {} try { timestamp = e.target.closest("article").querySelector("time").attributes["datetime"].value; } catch (e) {} try { location = e.target.closest("article").querySelector("header div._60iqg a").textContent; } catch (e) {} browser.runtime.sendMessage({ "url": pic_url, "user": username, "post": post, "bio": bio, "timestamp": timestamp, "location": location }); } }
window.addEventListener("click", notifyExtension); function notifyExtension(e) { console.log("igcs.js: click on ${e}"); if (e.target.classList.contains("coreSpriteHeartFull")) { var parser = document.createElement('a'); parser.href = e.target.closest("article").querySelector("header a").href; var bio = document.getElementsByClassName("_bugdy"); if (bio.length > 0) { bio = bio[0].textContent; } else { bio = ''; } var pic_url = ''; var username = ''; var post = ''; var timestamp = ''; var location = ''; try { pic_url = e.target.closest("article").querySelector("img._2di5p").src; } catch (e) {} try { username = parser.pathname.replace("/","").replace("/",""); } catch (e) {} try { post = e.target.closest("article > div").querySelector("div > ul > li > span").textContent; } catch (e) {} try { timestamp = e.target.closest("article").querySelector("time").attributes['datetime'].value; } catch (e) {} try { location = e.target.closest('article').querySelector('header div div a').textContent; } catch (e) {} browser.runtime.sendMessage({ "url": pic_url, "user": username, "post": post, "bio": bio, "timestamp": timestamp, "location": location }); } }
Fix case-sensitive filename in storage test
import json import os from mock import patch import pytest from inmemorystorage.storage import InMemoryStorage TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'images') @pytest.mark.django_db def test_alternate_storage(admin_client, settings): """Verify can plugin alternate storage backend""" settings.BETTY_IMAGE_ROOT = 'images' storage = InMemoryStorage() with patch('django.db.models.fields.files.default_storage._wrapped', storage): # Create Image path = os.path.join(TEST_DATA_PATH, 'Lenna.png') with open(path, "rb") as image: resp = admin_client.post('/images/api/new', {"image": image}) assert resp.status_code == 200 image_id = json.loads(resp.content.decode("utf-8"))['id'] image.seek(0) image_data = image.read() storage_data = storage.filesystem.open('images/{}/Lenna.png'.format(image_id)).read() assert image_data == storage_data assert storage.filesystem.exists('images/{}/optimized.png'.format(image_id)) # Delete Image resp = admin_client.post("/images/api/{0}".format(image_id), REQUEST_METHOD="DELETE") assert not storage.filesystem.exists('images/{}/Lenna.png'.format(image_id)) assert not storage.filesystem.exists('images/{}/optimized.png'.format(image_id))
import json import os from mock import patch import pytest from inmemorystorage.storage import InMemoryStorage TEST_DATA_PATH = os.path.join(os.path.dirname(__file__), 'images') @pytest.mark.django_db def test_alternate_storage(admin_client, settings): """Verify can plugin alternate storage backend""" settings.BETTY_IMAGE_ROOT = 'images' storage = InMemoryStorage() with patch('django.db.models.fields.files.default_storage._wrapped', storage): # Create Image path = os.path.join(TEST_DATA_PATH, 'lenna.png') with open(path, "rb") as image: resp = admin_client.post('/images/api/new', {"image": image}) assert resp.status_code == 200 image_id = json.loads(resp.content.decode("utf-8"))['id'] image.seek(0) image_data = image.read() storage_data = storage.filesystem.open('images/{}/lenna.png'.format(image_id)).read() assert image_data == storage_data assert storage.filesystem.exists('images/{}/optimized.png'.format(image_id)) # Delete Image resp = admin_client.post("/images/api/{0}".format(image_id), REQUEST_METHOD="DELETE") assert not storage.filesystem.exists('images/{}/lenna.png'.format(image_id)) assert not storage.filesystem.exists('images/{}/optimized.png'.format(image_id))
Remove temp directory creation... not worth it
import os from .exceptions import IncompleteEnv from tempfile import TemporaryDirectory import time class Environment(object): def __init__(self, *args, **kwargs): self.environ = os.environ.copy() self.config = {} self.cbchome = None if 'CBC_HOME' in kwargs: self.cbchome = kwargs['CBC_HOME'] # I want the local user environment to override what is # passed to the class. if 'CBC_HOME' in self.environ: self.cbchome = self.environ['CBC_HOME'] if self.cbchome is None: raise IncompleteEnv('Environment.cbchome is undefined') if not os.path.exists(self.cbchome): os.makedirs(self.cbchome) self.config['script'] = {} self.config['script']['meta'] = self.join('meta.yaml') self.config['script']['build_linux'] = self.join('build.sh') self.config['script']['build_windows'] = self.join('bld.bat') def join(self, path): return os.path.join(self.cbchome, path) ''' def local_temp(self): temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) return TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) '''
import os from .exceptions import IncompleteEnv from tempfile import TemporaryDirectory import time class Environment(object): def __init__(self, *args, **kwargs): self.environ = os.environ.copy() self.config = {} self.cbchome = None if 'CBC_HOME' in kwargs: self.cbchome = kwargs['CBC_HOME'] if 'CBC_HOME' in self.environ: self.cbchome = self.environ['CBC_HOME'] if self.cbchome is None: raise IncompleteEnv('Environment.cbchome is undefined') if not os.path.exists(self.cbchome): os.makedirs(self.cbchome) temp_prefix = os.path.basename(os.path.splitext(__name__)[0]) tempdir = TemporaryDirectory(prefix=temp_prefix, dir=self.cbchome) self.working_dir = tempdir.name self.config['meta'] = self.join('meta.yaml') self.config['build'] = self.join('build.sh') self.config['build_windows'] = self.join('bld.bat') print(self.working_dir) def join(self, path): return os.path.join(self.cbchome, path)
Change manage.py to require Pillow 2.0. This is to avoid PIL import errors for Mac users
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) version = '2.6.dev0' setup( name="django-photologue", version=version, description="Powerful image management for the Django web framework.", author="Justin Driscoll, Marcos Daniel Petry, Richard Barran", author_email="[email protected], [email protected]", url="https://github.com/jdriscoll/django-photologue", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum. 'South>=0.7.5', # Might work with earlier versions, but not tested. 'Pillow>=2.0', # Might work with earlier versions, but not tested. ], )
#/usr/bin/env python import os from setuptools import setup, find_packages ROOT_DIR = os.path.dirname(__file__) SOURCE_DIR = os.path.join(ROOT_DIR) version = '2.6.dev0' setup( name="django-photologue", version=version, description="Powerful image management for the Django web framework.", author="Justin Driscoll, Marcos Daniel Petry, Richard Barran", author_email="[email protected], [email protected]", url="https://github.com/jdriscoll/django-photologue", packages=find_packages(), package_data={ 'photologue': [ 'res/*.jpg', 'locale/*/LC_MESSAGES/*', 'templates/photologue/*.html', 'templates/photologue/tags/*.html', ] }, zip_safe=False, classifiers=['Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Utilities'], install_requires=['Django>=1.3', # Change to class-based views means 1.3 minimum. 'South>=0.7.5', # Might work with earlier versions, but not tested. 'Pillow>=1.7.8', # Might work with earlier versions, but not tested. ], )
Make shapes reappear when navigating back to the homepage
function setupNavigation() { if (document.getElementById("navigation") == null) { return; } var anchors = document.getElementsByTagName("a"); var sub_navigation_bars = document.getElementsByClassName("sub-navigation"); for (var i = 0; i < anchors.length; i++) { if (anchors[i].parentElement.id == "main-navigation" && anchors[i].innerHTML != "Home") { anchors[i].onmouseover = function(e) { for (var j = 0; j < sub_navigation_bars.length; j++) { if (sub_navigation_bars[j].getAttribute("parent") == this.innerHTML) { sub_navigation_bars[j].className = "sub-navigation"; } else { sub_navigation_bars[j].className = "sub-navigation hidden"; } } }; } } document.getElementById("navigation").onmouseleave = function(e) { var selected_anchors = document.getElementsByClassName("selected"); var sub_navigation_bars = document.getElementsByClassName("sub-navigation"); for (var i = 0; i < selected_anchors.length; i++) { if (selected_anchors[i].parentElement.id == "main-navigation") { for (var j = 0; j < sub_navigation_bars.length; j++) { if (sub_navigation_bars[j].getAttribute("parent") == selected_anchors[i].innerHTML) { sub_navigation_bars[j].className = "sub-navigation"; } else { sub_navigation_bars[j].className = "sub-navigation hidden"; } } break; } } }; } setupNavigation();
function setupNavigation() { var anchors = document.getElementsByTagName("a"); var sub_navigation_bars = document.getElementsByClassName("sub-navigation"); for (var i = 0; i < anchors.length; i++) { if (anchors[i].parentElement.id == "main-navigation" && anchors[i].innerHTML != "Home") { anchors[i].onmouseover = function(e) { for (var j = 0; j < sub_navigation_bars.length; j++) { if (sub_navigation_bars[j].getAttribute("parent") == this.innerHTML) { sub_navigation_bars[j].className = "sub-navigation"; } else { sub_navigation_bars[j].className = "sub-navigation hidden"; } } }; } } document.getElementById("navigation").onmouseleave = function(e) { var selected_anchors = document.getElementsByClassName("selected"); var sub_navigation_bars = document.getElementsByClassName("sub-navigation"); for (var i = 0; i < selected_anchors.length; i++) { if (selected_anchors[i].parentElement.id == "main-navigation") { for (var j = 0; j < sub_navigation_bars.length; j++) { if (sub_navigation_bars[j].getAttribute("parent") == selected_anchors[i].innerHTML) { sub_navigation_bars[j].className = "sub-navigation"; } else { sub_navigation_bars[j].className = "sub-navigation hidden"; } } break; } } }; } setupNavigation();
Fix dangling default in kwargs 'shell_cmd'
import sublime, sublime_plugin import os def wrapped_exec(self, *args, **kwargs): settings = sublime.load_settings("SublimeExterminal.sublime-settings") if settings.get('enabled') and kwargs.get('use_exterminal', True): wrapper = settings.get('exec_wrapper') try: shell_cmd = kwargs.get('shell_cmd') shell_cmd = wrapper % shell_cmd.replace('"','\\"') kwargs['shell_cmd'] = shell_cmd except KeyError: pass try: cmd = ' '.join(kwargs.get('cmd')) kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"') except KeyError: pass return self.run_cached_by_exterminal(*args, **kwargs) def plugin_loaded(): exec_cls = [cls for cls in sublime_plugin.window_command_classes \ if cls.__qualname__=='ExecCommand'][0] if hasattr(exec_cls(None), 'run_cached_by_exterminal'): exec_cls.run = exec_cls.run_cached_by_exterminal exec_cls.run_cached_by_exterminal = None exec_cls.run_cached_by_exterminal = exec_cls.run exec_cls.run = wrapped_exec class StartExterminalCommand(sublime_plugin.WindowCommand): def run(self, *args): settings = sublime.load_settings("SublimeExterminal.sublime-settings") cmd = settings.get('start_exterminal', '') os.popen(cmd)
import sublime, sublime_plugin import os def wrapped_exec(self, *args, **kwargs): settings = sublime.load_settings("SublimeExterminal.sublime-settings") if settings.get('enabled') and kwargs.get('use_exterminal', True): wrapper = settings.get('exec_wrapper') try: shell_cmd = kwargs.get('shell_cmd', '') shell_cmd = wrapper % shell_cmd.replace('"','\\"') kwargs['shell_cmd'] = shell_cmd except KeyError: pass try: cmd = ' '.join(kwargs.get('cmd')) kwargs['shell_cmd'] = wrapper % cmd.replace('"','\\"') except KeyError: pass return self.run_cached_by_exterminal(*args, **kwargs) def plugin_loaded(): exec_cls = [cls for cls in sublime_plugin.window_command_classes \ if cls.__qualname__=='ExecCommand'][0] if hasattr(exec_cls(None), 'run_cached_by_exterminal'): exec_cls.run = exec_cls.run_cached_by_exterminal exec_cls.run_cached_by_exterminal = None exec_cls.run_cached_by_exterminal = exec_cls.run exec_cls.run = wrapped_exec class StartExterminalCommand(sublime_plugin.WindowCommand): def run(self, *args): settings = sublime.load_settings("SublimeExterminal.sublime-settings") cmd = settings.get('start_exterminal', '') os.popen(cmd)
Add missing column to cache table
<?php /** * Migration: 0 * Started: 20/05/2021 * * @package Nails * @subpackage module-geo-ip * @category Database Migration * @author Nails Dev Team */ namespace Nails\GeoIp\Database\Migration; use Nails\Common\Console\Migrate\Base; /** * Class Migration0 * * @package Nails\GeoIp\Database\Migration */ class Migration0 extends Base { /** * Execute the migration */ public function execute() { $this->query(" CREATE TABLE `{{NAILS_DB_PREFIX}}geoip_cache` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `ip` varchar(255) NOT NULL DEFAULT '', `hostname` varchar(255) NOT NULL DEFAULT '', `city` varchar(255) NOT NULL DEFAULT '', `region` varchar(255) NOT NULL DEFAULT '', `country` varchar(255) NOT NULL DEFAULT '', `lat` varchar(255) NOT NULL DEFAULT '', `lng` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "); } }
<?php /** * Migration: 0 * Started: 20/05/2021 * * @package Nails * @subpackage module-geo-ip * @category Database Migration * @author Nails Dev Team */ namespace Nails\GeoIp\Database\Migration; use Nails\Common\Console\Migrate\Base; /** * Class Migration0 * * @package Nails\GeoIp\Database\Migration */ class Migration0 extends Base { /** * Execute the migration */ public function execute() { $this->query(" CREATE TABLE `{{NAILS_DB_PREFIX}}geoip_cache` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `hostname` varchar(255) NOT NULL DEFAULT '', `city` varchar(255) NOT NULL DEFAULT '', `region` varchar(255) NOT NULL DEFAULT '', `country` varchar(255) NOT NULL DEFAULT '', `lat` varchar(255) NOT NULL DEFAULT '', `lng` varchar(255) NOT NULL DEFAULT '', `created` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; "); } }
Introduce scope_types in server password policy oslo.policy introduced the scope_type feature which can control the access level at system-level and project-level. - https://docs.openstack.org/oslo.policy/latest/user/usage.html#setting-scope - http://specs.openstack.org/openstack/keystone-specs/specs/keystone/queens/system-scope.html Appropriate scope_type for nova case: - https://specs.openstack.org/openstack/nova-specs/specs/ussuri/approved/policy-defaults-refresh.html#scope This commit introduce scope_type for server password API policies as ['system', 'project']. Also adds the test case with scope_type enabled and verify we pass and fail the policy check with expected context. Partial implement blueprint policy-defaults-refresh Change-Id: I8f5e66810c68a871e57a5362a931545bccded608
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-server-password' server_password_policies = [ policy.DocumentedRuleDefault( name=BASE_POLICY_NAME, check_str=base.RULE_ADMIN_OR_OWNER, description="Show and clear the encrypted administrative " "password of a server", operations=[ { 'method': 'GET', 'path': '/servers/{server_id}/os-server-password' }, { 'method': 'DELETE', 'path': '/servers/{server_id}/os-server-password' } ], scope_types=['system', 'project']), ] def list_rules(): return server_password_policies
# Copyright 2016 Cloudbase Solutions Srl # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo_policy import policy from nova.policies import base BASE_POLICY_NAME = 'os_compute_api:os-server-password' server_password_policies = [ policy.DocumentedRuleDefault( BASE_POLICY_NAME, base.RULE_ADMIN_OR_OWNER, "Show and clear the encrypted administrative password of a server", [ { 'method': 'GET', 'path': '/servers/{server_id}/os-server-password' }, { 'method': 'DELETE', 'path': '/servers/{server_id}/os-server-password' } ]), ] def list_rules(): return server_password_policies
Update Tags name length to 320 characters; per https://github.com/UseMuffin/Slug/pull/25#issuecomment-225242866;
<?php namespace Muffin\Slug\Test\Fixture; use Cake\TestSuite\Fixture\TestFixture; class TagsFixture extends TestFixture { public $table = 'slug_tags'; public $fields = [ 'id' => ['type' => 'integer'], 'namespace' => ['type' => 'string', 'length' => 255, 'null' => true], 'slug' => ['type' => 'string', 'length' => 255], 'name' => ['type' => 'string', 'length' => 320], 'counter' => ['type' => 'integer', 'unsigned' => true, 'default' => 0, 'null' => true], 'created' => ['type' => 'datetime', 'null' => true], 'modified' => ['type' => 'datetime', 'null' => true], '_constraints' => [ 'primary' => ['type' => 'primary', 'columns' => ['id']], ], ]; public $records = [ [ 'namespace' => null, 'slug' => 'color', 'name' => 'Color', 'counter' => 2, ], [ 'namespace' => null, 'slug' => 'dark-color', 'name' => 'Dark Color', 'counter' => 1, ], ]; public function init() { $created = $modified = date('Y-m-d H:i:s'); array_walk($this->records, function (&$record) use ($created, $modified) { $record += compact('created', 'modified'); }); parent::init(); } }
<?php namespace Muffin\Slug\Test\Fixture; use Cake\TestSuite\Fixture\TestFixture; class TagsFixture extends TestFixture { public $table = 'slug_tags'; public $fields = [ 'id' => ['type' => 'integer'], 'namespace' => ['type' => 'string', 'length' => 255, 'null' => true], 'slug' => ['type' => 'string', 'length' => 255], 'name' => ['type' => 'string', 'length' => 255], 'counter' => ['type' => 'integer', 'unsigned' => true, 'default' => 0, 'null' => true], 'created' => ['type' => 'datetime', 'null' => true], 'modified' => ['type' => 'datetime', 'null' => true], '_constraints' => [ 'primary' => ['type' => 'primary', 'columns' => ['id']], ], ]; public $records = [ [ 'namespace' => null, 'slug' => 'color', 'name' => 'Color', 'counter' => 2, ], [ 'namespace' => null, 'slug' => 'dark-color', 'name' => 'Dark Color', 'counter' => 1, ], ]; public function init() { $created = $modified = date('Y-m-d H:i:s'); array_walk($this->records, function (&$record) use ($created, $modified) { $record += compact('created', 'modified'); }); parent::init(); } }
Check for dev version of zmq per @minrk's request
#----------------------------------------------------------------------------- # Copyright (C) 2010 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Verify zmq version dependency >= 2.1.4 #----------------------------------------------------------------------------- import warnings from distutils.version import LooseVersion as V def check_for_zmq(minimum_version, module='IPython.zmq'): try: import zmq except ImportError: raise ImportError("%s requires pyzmq >= %s"%(module, minimum_version)) pyzmq_version = zmq.__version__ if 'dev' not in pyzmq_version and V(pyzmq_version) < V(minimum_version): raise ImportError("%s requires pyzmq >= %s, but you have %s"%( module, minimum_version, pyzmq_version)) # fix missing DEALER/ROUTER aliases in pyzmq < 2.1.9 if not hasattr(zmq, 'DEALER'): zmq.DEALER = zmq.XREQ if not hasattr(zmq, 'ROUTER'): zmq.ROUTER = zmq.XREP if V(zmq.zmq_version()) >= V('4.0.0'): warnings.warn("""libzmq 4 detected. It is unlikely that IPython's zmq code will work properly. Please install libzmq stable, which is 2.1.x or 2.2.x""", RuntimeWarning) check_for_zmq('2.1.4')
#----------------------------------------------------------------------------- # Copyright (C) 2010 The IPython Development Team # # Distributed under the terms of the BSD License. The full license is in # the file COPYING.txt, distributed as part of this software. #----------------------------------------------------------------------------- #----------------------------------------------------------------------------- # Verify zmq version dependency >= 2.1.4 #----------------------------------------------------------------------------- import warnings from distutils.version import LooseVersion as V def check_for_zmq(minimum_version, module='IPython.zmq'): try: import zmq except ImportError: raise ImportError("%s requires pyzmq >= %s"%(module, minimum_version)) pyzmq_version = zmq.__version__ if V(pyzmq_version) < V(minimum_version): raise ImportError("%s requires pyzmq >= %s, but you have %s"%( module, minimum_version, pyzmq_version)) # fix missing DEALER/ROUTER aliases in pyzmq < 2.1.9 if not hasattr(zmq, 'DEALER'): zmq.DEALER = zmq.XREQ if not hasattr(zmq, 'ROUTER'): zmq.ROUTER = zmq.XREP if V(zmq.zmq_version()) >= V('4.0.0'): warnings.warn("""libzmq 4 detected. It is unlikely that IPython's zmq code will work properly. Please install libzmq stable, which is 2.1.x or 2.2.x""", RuntimeWarning) check_for_zmq('2.1.4')