text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
[BUGFIX] Check for existance of $releasesList[0] before using
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release // this is why $releasesList[0] have last release and not current. $overwriteReleases = ['current']; if (!empty($releasesList)) { $overwriteReleases[] = $releasesList[0]; } foreach ($overwriteReleases as $overwriteRelease) { $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease; foreach (get('buffer_config') as $key => $buffer) { if (!isset($buffer['entrypoint_filename'])) { throw new \RuntimeException('entrypoint_filename not set for buffer_data'); } $entrypointFilename = $buffer['entrypoint_filename']; if (isset($buffer['locker_filename'])) { $lockerFilename = $buffer['locker_filename']; } else { $lockerFilename = 'buffer.lock'; } if (dirname($entrypointFilename) != '.') { $entrypointDirectory = dirname($entrypointFilename) . '/'; } else { $entrypointDirectory = ''; } run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename); } } })->desc('Stop buffering reqests to application entrypoints.');
<?php namespace Deployer; task('buffer:stop', function () { $releasesList = get('releases_list'); // Remove lock files also from previous release because it can be still read by apache/nginx after switching. // get('releases_list') is cached by deployer on first call in other task so it does not have the latest release // this is why $releasesList[0] have last release and not current. $overwriteReleases = [ 'releases/' . $releasesList[0], 'current' ]; foreach ($overwriteReleases as $overwriteRelease) { $overwriteReleasePath = get('deploy_path') . '/' . $overwriteRelease; foreach (get('buffer_config') as $key => $buffer) { if (!isset($buffer['entrypoint_filename'])) { throw new \RuntimeException('entrypoint_filename not set for buffer_data'); } $entrypointFilename = $buffer['entrypoint_filename']; if (isset($buffer['locker_filename'])) { $lockerFilename = $buffer['locker_filename']; } else { $lockerFilename = 'buffer.lock'; } if (dirname($entrypointFilename) != '.') { $entrypointDirectory = dirname($entrypointFilename) . '/'; } else { $entrypointDirectory = ''; } run('cd ' . $overwriteReleasePath . ' && rm -f {{web_path}}' . $entrypointDirectory . $lockerFilename); } } })->desc('Stop buffering reqests to application entrypoints.');
Fix broken pagination with Elasticsearch and Undertow Thanks @ashakhov for the solution Fix #4158
(function(){ 'use strict'; angular .module('<%=angularAppName%>') .factory('ParseLinks', ParseLinks); function ParseLinks () { var service = { parse : parse }; return service; function parse(header) { if (header.length === 0) { throw new Error('input must not be of zero length'); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function(p) { var section = p.split('>;'); if (section.length !== 2) { throw new Error('section could not be split on ">;"'); } var url = section[0].replace(/<(.*)/, '$1').trim(); var queryString = {}; url.replace( new RegExp('([^?=&]+)(=([^&]*))?', 'g'), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString.page; if (angular.isString(page)) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } } })();
(function(){ 'use strict'; angular .module('<%=angularAppName%>') .factory('ParseLinks', ParseLinks); function ParseLinks () { var service = { parse : parse }; return service; function parse(header) { if (header.length === 0) { throw new Error('input must not be of zero length'); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function(p) { var section = p.split(';'); if (section.length !== 2) { throw new Error('section could not be split on ";"'); } var url = section[0].replace(/<(.*)>/, '$1').trim(); var queryString = {}; url.replace( new RegExp('([^?=&]+)(=([^&]*))?', 'g'), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString.page; if (angular.isString(page)) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } } })();
Put in a raise for status for now
from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from social.app.models.author import Author class FriendRequestsListView(generic.ListView): context_object_name = "all_friend_requests" template_name = "app/friend_requests_list.html" def get_queryset(self): return self.request.user.profile.incoming_friend_requests.all() def post(self, request): logged_in_author = self.request.user.profile accepted_friend_requests = request.POST.getlist('accepted_friend_requests') for new_friend_id in accepted_friend_requests: new_friend = Author.objects.get(id=new_friend_id) if new_friend.node.local: logged_in_author.accept_friend_request(new_friend) else: r = new_friend.node.post_friend_request(request, logged_in_author, new_friend) if 200 <= r.status_code < 300: # Success! logged_in_author.accept_friend_request(new_friend) else: r.raise_for_status() logged_in_author.save() return HttpResponseRedirect(reverse("app:friend-requests-list"))
from django.http import HttpResponseRedirect from django.urls import reverse from django.views import generic from social.app.models.author import Author class FriendRequestsListView(generic.ListView): context_object_name = "all_friend_requests" template_name = "app/friend_requests_list.html" def get_queryset(self): return self.request.user.profile.incoming_friend_requests.all() def post(self, request): logged_in_author = self.request.user.profile accepted_friend_requests = request.POST.getlist('accepted_friend_requests') for new_friend_id in accepted_friend_requests: new_friend = Author.objects.get(id=new_friend_id) if new_friend.node.local: logged_in_author.accept_friend_request(new_friend) else: r = new_friend.node.post_friend_request(request, logged_in_author, new_friend) if 200 <= r.status_code < 300: # Success! logged_in_author.accept_friend_request(new_friend) else: # This one didn't work. Oh well! No easy way to show an error without ruining other accepts pass logged_in_author.save() return HttpResponseRedirect(reverse("app:friend-requests-list"))
Reduce complexity and try/catch block in Logger
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging() self.function = function return self.wrapped_function def wrapped_function(self, event, context): timeout_notification = self.add_logging_on_timeout(context) try: logging.debug(event) response = self.function(event, context) logging.debug(response) return response except Exception as ex: logging.exception(ex.message) raise finally: if timeout_notification: timeout_notification.cancel() def add_logging_on_timeout(self, context): if hasattr(context, 'get_remaining_time_in_millis'): seconds = (context.get_remaining_time_in_millis() / 1000.00) - 0.5 timer = threading.Timer(seconds, logging.error, args=["Execution is about to timeout."]) timer.start() return timer else: logging.debug('Add logging on timeout failed. context.get_remaining_time_in_millis() missing?')
# -*- coding: utf-8 -*- import os import logging import threading class Logger(object): def configure_logging(self): log_level = getattr(logging, os.environ.get('LOGLEVEL', 'INFO').upper()) logging.getLogger().setLevel(log_level) def __call__(self, function): self.configure_logging() self.function = function return self.wrapped_function def wrapped_function(self, event, context): try: timeout_notification = self.add_logging_on_timeout(context) logging.debug(event) response = self.function(event, context) logging.debug(response) return response except Exception as ex: logging.exception(ex.message) raise finally: if timeout_notification: timeout_notification.cancel() def add_logging_on_timeout(self, context): try: timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout) timer.start() return timer except AttributeError as ex: logging.debug('Add Timeout notification failed. context.get_remaining_time_in_millis() missing?') def timeout(): logging.error("Execution is about to timeout.")
Document the type of NamedEnumField properly
from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum choices = ( (self.get_choice_value(enum_value), enum_value.label) for _, enum_value in enum.choices() ) super(EnumField, self).__init__(choices, **kwargs) def get_choice_value(self, enum_value): return enum_value.value def to_internal_value(self, data): if isinstance(data, six.string_types) and data.isdigit(): data = int(data) try: value = self.enum.get(data).value except AttributeError: # .get() returned None if not self.required: raise serializers.SkipField() self.fail("invalid_choice", input=data) return value def to_representation(self, value): enum_value = self.enum.get(value) if enum_value is not None: return self.get_choice_value(enum_value) class NamedEnumField(EnumField): def get_choice_value(self, enum_value): return enum_value.name class Meta: swagger_schema_fields = {"type": "string"}
from django.utils import six from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers class EnumField(serializers.ChoiceField): default_error_messages = {"invalid_choice": _('"{input}" is not a valid choice.')} def __init__(self, enum, **kwargs): self.enum = enum choices = ( (self.get_choice_value(enum_value), enum_value.label) for _, enum_value in enum.choices() ) super(EnumField, self).__init__(choices, **kwargs) def get_choice_value(self, enum_value): return enum_value.value def to_internal_value(self, data): if isinstance(data, six.string_types) and data.isdigit(): data = int(data) try: value = self.enum.get(data).value except AttributeError: # .get() returned None if not self.required: raise serializers.SkipField() self.fail("invalid_choice", input=data) return value def to_representation(self, value): enum_value = self.enum.get(value) if enum_value is not None: return self.get_choice_value(enum_value) class NamedEnumField(EnumField): def get_choice_value(self, enum_value): return enum_value.name
Make rememberable cache flushes trigger on deletes too
<?php namespace Amelia\Rememberable; use Amelia\Rememberable\Query\Builder as QueryBuilder; use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; trait Rememberable { protected static function bootRememberable() { if (static::rememberable()) { static::saved(function (Model $model) { $model->flush(get_class($model).':'.$model->getKey()); }); static::deleted(function (Model $model) { $model->flush(get_class($model).':'.$model->getKey()); }); } } /** * Get a new query builder instance for the connection. * * @return \Illuminate\Database\Query\Builder */ protected function newBaseQueryBuilder() { $conn = $this->getConnection(); $grammar = $conn->getQueryGrammar(); $builder = new QueryBuilder($conn, $grammar, $conn->getPostProcessor(), $this); if (static::rememberable()) { $builder->remember(-1); } return $builder; } /** * Override the eloquent query builder. * * @param \Illuminate\Database\Query\Builder $query * @return \Amelia\Rememberable\Eloquent\Builder */ public function newEloquentBuilder($query) { return new EloquentBuilder($query); } /** * Check if we're "rememberable". * * @return bool */ public static function rememberable() { return isset(static::$rememberable) && static::$rememberable === true; } }
<?php namespace Amelia\Rememberable; use Amelia\Rememberable\Query\Builder as QueryBuilder; use Amelia\Rememberable\Eloquent\Builder as EloquentBuilder; use Illuminate\Database\Eloquent\Model; trait Rememberable { protected static function bootRememberable() { if (static::rememberable()) { static::saving(function (Model $model) { $model->flush(get_class($model).':'.$model->getKey()); }); } } /** * Get a new query builder instance for the connection. * * @return \Illuminate\Database\Query\Builder */ protected function newBaseQueryBuilder() { $conn = $this->getConnection(); $grammar = $conn->getQueryGrammar(); $builder = new QueryBuilder($conn, $grammar, $conn->getPostProcessor(), $this); if (static::rememberable()) { $builder->remember(-1); } return $builder; } /** * Override the eloquent query builder. * * @param \Illuminate\Database\Query\Builder $query * @return \Amelia\Rememberable\Eloquent\Builder */ public function newEloquentBuilder($query) { return new EloquentBuilder($query); } /** * Check if we're "rememberable". * * @return bool */ public static function rememberable() { return isset(static::$rememberable) && static::$rememberable === true; } }
Increase the buffer to satisfy appmanifest
var phantom = require("phantomjs") , execFile = require("child_process").execFile , jn = require("path").join , u = require("url") , querystring = require("querystring") , r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js") ; exports.generate = function (url, params, cb) { url = u.parse(url); // respec use ";" as query string separators var qs = querystring.parse(url.query, ";") for (var k in params) if (params.hasOwnProperty(k)) qs[k] = params[k]; url.search = querystring.stringify(qs, ";"); url = u.format(url); console.log("Generating", url); // Phantom's own timeouts are never reaching us for some reason, so we do our own var timedout = false; var tickingBomb = setTimeout( function () { timedout = true; cb({ status: 500, message: "Processing timed out." }); } , 10000 ); execFile( phantom.path , ["--ssl-protocol=any", r2hPath, url] , { maxBuffer: 400*1024 } // default * 2 , function (err, stdout, stderr) { if (timedout) return; clearTimeout(tickingBomb); if (err) return cb({ status: 500, message: err + "\n" + (stderr || "") }); cb(null, stdout); } ); };
var phantom = require("phantomjs") , execFile = require("child_process").execFile , jn = require("path").join , u = require("url") , querystring = require("querystring") , r2hPath = jn(__dirname, "../node_modules/respec/tools/respec2html.js") ; exports.generate = function (url, params, cb) { url = u.parse(url); // respec use ";" as query string separators var qs = querystring.parse(url.query, ";") for (var k in params) if (params.hasOwnProperty(k)) qs[k] = params[k]; url.search = querystring.stringify(qs, ";"); url = u.format(url); console.log("Generating", url); // Phantom's own timeouts are never reaching us for some reason, so we do our own var timedout = false; var tickingBomb = setTimeout( function () { timedout = true; cb({ status: 500, message: "Processing timed out." }); } , 10000 ); execFile( phantom.path , ["--ssl-protocol=any", r2hPath, url] , function (err, stdout, stderr) { if (timedout) return; clearTimeout(tickingBomb); if (err) return cb({ status: 500, message: err + "\n" + (stderr || "") }); cb(null, stdout); } ); };
Use Properties interface to get Manager properties. Signed-off-by: mulhern <[email protected]>
""" Manager interface. """ from ._properties import Properties class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ self._dbus_object = dbus_object def CreatePool(self, pool_name, devices, num_devices): """ Create a pool. :param str pool_name: the pool name :param devices: the component devices :type devices: sequence of str """ return self._dbus_object.CreatePool( pool_name, devices, num_devices, dbus_interface=self._INTERFACE_NAME, ) def DestroyPool(self, pool_name): """ Destroy a pool. :param str pool_name: the name of the pool """ return self._dbus_object.DestroyPool( pool_name, dbus_interface=self._INTERFACE_NAME ) def ListPools(self): """ List all pools. """ return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME) @property def Version(self): """ Stratisd Version getter. :rtype: String """ return Properties(self._dbus_object).Get( self._INTERFACE_NAME, 'Version' ) @property def LogLevel(self): """ Stratisd LogLevel getter. :rtype: String """ return Properties(self._dbus_object).Get( self._INTERFACE_NAME, 'LogLevel' ) @LogLevel.setter def LogLevel(self, value): """ Stratisd LogLevel setter. :param str value: the value to set """ return Properties(self._dbus_object).Set( self._INTERFACE_NAME, 'LogLevel', value )
""" Manager interface. """ class Manager(object): """ Manager interface. """ _INTERFACE_NAME = 'org.storage.stratis1.Manager' def __init__(self, dbus_object): """ Initializer. :param dbus_object: the dbus object """ self._dbus_object = dbus_object def CreatePool(self, pool_name, devices, num_devices): """ Create a pool. :param str pool_name: the pool name :param devices: the component devices :type devices: sequence of str """ return self._dbus_object.CreatePool( pool_name, devices, num_devices, dbus_interface=self._INTERFACE_NAME, ) def DestroyPool(self, pool_name): """ Destroy a pool. :param str pool_name: the name of the pool """ return self._dbus_object.DestroyPool( pool_name, dbus_interface=self._INTERFACE_NAME ) def ListPools(self): """ List all pools. """ return self._dbus_object.ListPools(dbus_interface=self._INTERFACE_NAME)
Resolve styles from the scss directory
var path = require('path') module.exports = { entry: { app: './src/main.js', vendors: [ 'vue', 'vue-resource', 'vue-router', ], }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.vue'], alias: { 'src': path.resolve(__dirname, '../src'), } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, sassLoader: { includePaths: [ path.resolve(__dirname, '../src/scss') ], }, module: { loaders: [ { test: /\.vue$/, loader: 'vue', }, { test: /\.js$/, loader: 'babel', // babel!eslint exclude: /node_modules/, }, { test: /\.json$/, loader: 'json', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url', query: { limit: 10000, name: '[name].[ext]?[hash:7]', }, }, ], }, vue: { loaders: { js: 'babel', // babel!eslint }, }, // eslint: { // formatter: require('eslint-friendly-formatter'), // }, };
var path = require('path') module.exports = { entry: { app: './src/main.js', vendors: [ 'vue', 'vue-resource', 'vue-router', ], }, output: { path: path.resolve(__dirname, '../dist'), publicPath: '/themes/{{ name }}/dist/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.vue'], alias: { 'src': path.resolve(__dirname, '../src'), } }, resolveLoader: { root: path.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /\.vue$/, loader: 'vue', }, { test: /\.js$/, loader: 'babel', // babel!eslint exclude: /node_modules/, }, { test: /\.json$/, loader: 'json', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url', query: { limit: 10000, name: '[name].[ext]?[hash:7]', }, }, ], }, vue: { loaders: { js: 'babel', // babel!eslint }, }, // eslint: { // formatter: require('eslint-friendly-formatter'), // }, };
Edit logic for creating mesage success action
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: [ ...state[action.groupId].members, action.member ] } }; case member.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: action.list } }; case message.CREATE_SUCCESS: // return { ...state, // [action.message.groupId]: { // messages: [...state[action.message.groupId].messages, action.message] // } }; return { ...state, [action.message.groupId]: { ...state[action.message.groupId], messages: [ ...state[action.message.groupId].messages, action.message ] } }; case message.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], messages: action.list } }; default: return state; } }; export default groupReducer;
import { group, member, message } from '../actions/actionTypes'; const groupReducer = (state = {}, action = {}) => { switch (action.type) { case group.CREATE_SUCCESS: return { ...state, [action.group.id]: { members: [], messages: [] } }; case member.ADD_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: [ ...state[action.groupId].members, action.member ] } }; case member.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], members: action.list } }; case message.CREATE_SUCCESS: return { ...state, [action.message.groupId]: { messages: [...state[action.message.groupId].messages, action.message] } }; // return { // ...state, // [action.groupId]: { // ...state[action.groupId], // messages: [ // ...state[action.groupId].messages, // action.message // ] // } // }; case message.LIST_SUCCESS: return { ...state, [action.groupId]: { ...state[action.groupId], messages: action.list } }; default: return state; } }; export default groupReducer;
[Form] Allow setting different options to repeating fields
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class RepeatedType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilder $builder, array $options) { $builder ->appendClientTransformer(new ValueToDuplicatesTransformer(array( $options['first_name'], $options['second_name'], ))) ->add($options['first_name'], $options['type'], 0 < count($options['first_options']) ? $options['first_options'] : $options['options']) ->add($options['second_name'], $options['type'], 0 < count($options['second_options']) ? $options['second_options'] : $options['options']) ; } /** * {@inheritdoc} */ public function getDefaultOptions(array $options) { return array( 'type' => 'text', 'options' => array(), 'first_options' => array(), 'second_options' => array(), 'first_name' => 'first', 'second_name' => 'second', 'error_bubbling' => false, ); } /** * {@inheritdoc} */ public function getName() { return 'repeated'; } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Form\Extension\Core\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\Extension\Core\DataTransformer\ValueToDuplicatesTransformer; class RepeatedType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilder $builder, array $options) { $builder ->appendClientTransformer(new ValueToDuplicatesTransformer(array( $options['first_name'], $options['second_name'], ))) ->add($options['first_name'], $options['type'], $options['options']) ->add($options['second_name'], $options['type'], $options['options']) ; } /** * {@inheritdoc} */ public function getDefaultOptions(array $options) { return array( 'type' => 'text', 'options' => array(), 'first_name' => 'first', 'second_name' => 'second', 'error_bubbling' => false, ); } /** * {@inheritdoc} */ public function getName() { return 'repeated'; } }
Fix _ function call from schedule window
Ext.define('Clonos.window.Schedule', { extend: 'Ext.window.Window', alias: 'widget.scheduleWindow', title: 'Schedule refresh', modal: true, draggable: false, shadow: false, items: [{ xtype: 'form', frame: true, width: 320, bodyPadding: 10, reference: 'scheduleForm', url: '/scheduleRefresh', items: [{ xtype: 'timefield', name: 'refreshtime', allowBlank: true, format: 'H:i', fieldLabel: 'First refresh', enableKeyEvents: true, minValue: new Date() }, { xtype: 'numberfield', minValue: 0, name: 'refresh', allowBlank: false, value: 24, fieldLabel: 'Refresh period in hours', enableKeyEvents: true }], buttons: [{ text: 'Schedule' },{ text: 'Cancel' }] }] });
Ext.define('Clonos.window.Schedule', { extend: 'Ext.window.Window', alias: 'widget.scheduleWindow', title: _('Schedule refresh'), modal: true, draggable: false, shadow: false, items: [{ xtype: 'form', frame: true, width: 320, bodyPadding: 10, reference: 'scheduleForm', url: '/scheduleRefresh', items: [{ xtype: 'timefield', name: 'refreshtime', allowBlank: true, format: 'H:i', fieldLabel: _('First refresh'), enableKeyEvents: true, minValue: new Date() }, { xtype: 'numberfield', minValue: 0, name: 'refresh', allowBlank: false, value: 24, fieldLabel: _('Refresh period in hours'), enableKeyEvents: true }], buttons: [{ text: _('Schedule') },{ text: _('Cancel') }] }] });
Remove unnessesairy check in if statement
<?php /** * Particle. * * @link http://github.com/particle-php for the canonical source repository * @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com) * @license https://github.com/particle-php/Filter/blob/master/LICENSE New BSD License */ namespace Particle\Filter; /** * Class Chain * * @package Particle\Filter */ class Chain { /** * @var FilterRule[] */ protected $rules; /** * Execute all filters in the chain * * @param bool $isSet * @param mixed $value * @return FilterResult */ public function filter($isSet, $value = null) { /** @var FilterRule $rule */ foreach ($this->rules as $rule) { if ($isSet || $rule->allowedNotSet()) { $value = $rule->filter($value); $isSet = true; } } return new FilterResult($isSet, $value); } /** * Add a new rule to the chain * * @param FilterRule $rule * @param string|null $encodingFormat * @return $this */ public function addRule(FilterRule $rule, $encodingFormat) { $rule->setEncodingFormat($encodingFormat); $this->rules[] = $rule; return $this; } }
<?php /** * Particle. * * @link http://github.com/particle-php for the canonical source repository * @copyright Copyright (c) 2005-2015 Particle (http://particle-php.com) * @license https://github.com/particle-php/Filter/blob/master/LICENSE New BSD License */ namespace Particle\Filter; /** * Class Chain * * @package Particle\Filter */ class Chain { /** * @var FilterRule[] */ protected $rules; /** * Execute all filters in the chain * * @param bool $isSet * @param mixed $value * @return FilterResult */ public function filter($isSet, $value = null) { /** @var FilterRule $rule */ foreach ($this->rules as $rule) { if ($isSet || !$isSet && $rule->allowedNotSet()) { $value = $rule->filter($value); $isSet = true; } } return new FilterResult($isSet, $value); } /** * Add a new rule to the chain * * @param FilterRule $rule * @param string|null $encodingFormat * @return $this */ public function addRule(FilterRule $rule, $encodingFormat) { $rule->setEncodingFormat($encodingFormat); $this->rules[] = $rule; return $this; } }
Add post fetching on props update
import React, { Component } from 'react' import PostItemContainer from '../../containers/PostItemContainer' import debounce from '../../util/debounce' class PostList extends Component { constructor (props) { super(props) this.onScroll = debounce(this.onScroll, 350).bind(this) } componentDidMount () { this.props.actions.requestPosts( this.props.r, this.props.from ) window.addEventListener('scroll', this.onScroll) } componentWillReceiveProps (nextProps) { if (this.props.r !== nextProps.r) { this.props.actions.requestPosts( nextProps.r, nextProps.from ) } } componentWillUnmount () { window.removeEventListener('scroll', this.onScroll) } onScroll () { if (this.props.posts.length === 0) { // Sub does not contain any post yet // so we do not need to fetch more return } const [lastPost] = this.props.posts.reverse() const scrollBottom = document.body.scrollHeight - document.body.scrollTop - window.innerHeight if (scrollBottom / window.innerHeight < 0.2) { this.props.actions.requestPosts( this.props.r, this.props.from, lastPost.id ) } } render () { return ( <div className='subreddit__post-list'> {this.props.posts.map(p => ( <PostItemContainer key={p.id} {...p} /> ))} </div> ) } } export default PostList
import React, { Component } from 'react' import PostItemContainer from '../../containers/PostItemContainer' import debounce from '../../util/debounce' class PostList extends Component { constructor (props) { super(props) this.onScroll = debounce(this.onScroll, 350).bind(this) } componentDidMount () { this.props.actions.requestPosts( this.props.r, this.props.from ) window.addEventListener('scroll', this.onScroll) } componentWillUnmount () { window.removeEventListener('scroll', this.onScroll) } onScroll () { if (this.props.posts.length === 0) { // Sub does not contain any post yet // so we do not need to fetch more return } const [lastPost] = this.props.posts.reverse() const scrollBottom = document.body.scrollHeight - document.body.scrollTop - window.innerHeight if (scrollBottom / window.innerHeight < 0.2) { this.props.actions.requestPosts( this.props.r, this.props.from, lastPost.id ) } } render () { return ( <div className='subreddit__post-list'> {this.props.posts.map(p => ( <PostItemContainer key={p.id} {...p} /> ))} </div> ) } } export default PostList
Add banner to Grunt banner
module.exports = function(grunt) { require('google-closure-compiler').grunt(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { banner: '// Simple2D.js — v<%= pkg.version %>, built <%= grunt.template.today("mm-dd-yyyy") %>\n\n', separator: '\n\n' }, dist: { src: [ 'src/start.js', 'src/simple2d.js', 'src/shapes.js', 'src/image.js', 'src/sprite.js', 'src/text.js', 'src/sound.js', 'src/music.js', 'src/input.js', 'src/window.js', 'src/gl.js', 'src/end.js' ], dest: 'build/simple2d.js' } }, eslint: { dist: ['build/simple2d.js'] }, 'closure-compiler': { dist: { files: { 'build/simple2d.min.js': ['build/simple2d.js'] }, options: { compilation_level: 'SIMPLE' // ,formatting: 'pretty_print' } } } }); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-contrib-concat'); // Define tasks grunt.registerTask('default', [ 'concat', 'eslint', 'closure-compiler' ]); };
module.exports = function(grunt) { require('google-closure-compiler').grunt(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: '\n\n' }, dist: { src: [ 'src/start.js', 'src/simple2d.js', 'src/shapes.js', 'src/image.js', 'src/sprite.js', 'src/text.js', 'src/sound.js', 'src/music.js', 'src/input.js', 'src/window.js', 'src/gl.js', 'src/end.js' ], dest: 'build/simple2d.js' } }, eslint: { dist: ['build/simple2d.js'] }, 'closure-compiler': { dist: { files: { 'build/simple2d.min.js': ['build/simple2d.js'] }, options: { compilation_level: 'SIMPLE' // ,formatting: 'pretty_print' } } } }); grunt.loadNpmTasks('grunt-eslint'); grunt.loadNpmTasks('grunt-contrib-concat'); // Define tasks grunt.registerTask('default', [ 'concat', 'eslint', 'closure-compiler' ]); };
Handle navigation on keydown instead of keypress to work around automatic input focus acquisition.
window.addEventListener("keydown", function handleNavigation (event) { if (window.document.activeElement !== window.document.body) { return; } const keyCode = event.code; if (keyCode.indexOf("Digit") !== 0) { return; } const digit = Number(keyCode[5]); if (digit < 0 || digit > 9) { return; } const index = (digit === 0) ? 8 : (digit - 1); const results = document.body.querySelectorAll("h3.r"); const result = results[index]; if (!result) { return; } event.stopPropagation(); const anchor = result.querySelector("a"); const href = anchor.href; window.location.href = href; }, true); const emojicationSuffix = "\u{FE0F}\u{20e3} "; function emojifyResults () { const results = document.body.querySelectorAll("h3.r"); const last = results.length - 1; results.forEach((result, index) => { if (index === last || index < 9) { const digit = (index === last) ? 0 : index + 1; const emojiDigit = String(digit) + emojicationSuffix; result.insertAdjacentText("afterbegin", emojiDigit); } }); }; if (window.document.readyState === "complete") { emojifyResults(); } window.document.onreadystatechange = function () { if (document.readyState === "complete") { emojifyResults(); } }
window.addEventListener("keypress", function (event) { if (window.document.activeElement !== window.document.body) { return; } const keyCode = event.code; if (keyCode.indexOf("Digit") !== 0) { return; } const digit = Number(keyCode[5]); if (digit < 0 || digit > 9) { return; } const index = (digit === 0) ? 8 : (digit - 1); const results = document.body.querySelectorAll("h3.r"); const result = results[index]; if (!result) { return; } const anchor = result.querySelector("a"); const href = anchor.href; window.location.href = href; }); const emojicationSuffix = "\u{FE0F}\u{20e3} "; function emojifyResults () { const results = document.body.querySelectorAll("h3.r"); const last = results.length - 1; console.log("results", results); results.forEach((result, index) => { if (index === last || index < 9) { const digit = (index === last) ? 0 : index + 1; const emojiDigit = String(digit) + emojicationSuffix; result.insertAdjacentText("afterbegin", emojiDigit); } }); }; if (window.document.readyState === "complete") { emojifyResults(); } window.document.onreadystatechange = function () { if (document.readyState === "complete") { emojifyResults(); } }
Fix another regression in the architect test dummy
/** * Bogus plugin. Circularity ftw. */ define(function(require, exports, module) { "use strict"; main.consumes = [ "Plugin", "ui", "myplugin" ]; main.provides = ["myplugin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var ui = imports.ui; // Note: the syntax error below is intentional and used by architect_resolver_test.js imports. /***** Initialization *****/ var plugin = new Plugin("Ajax.org", main.consumes); var emit = plugin.getEmitter(); var foo; var bar; var loaded = false; function load() { if (loaded) return false; loaded = true; foo = 1; bar = 2; // ... } function myfunc(arg0, arg1) { } /***** Lifecycle *****/ plugin.on("load", function(){ load(); }); plugin.on("unload", function(){ foo = undefined; }); /***** Register and define API *****/ /** * **/ plugin.freezePublicAPI({ myfunc: myfunc }); //register(null, { "myplugin" : plugin }); register(null, { "myplugin" : { myfunc2: myfunc }}); } });
"use blacklist"; /** * Bogus plugin. Circularity ftw. */ define(function(require, exports, module) { "use strict"; main.consumes = [ "Plugin", "ui", "myplugin" ]; main.provides = ["myplugin"]; return main; function main(options, imports, register) { var Plugin = imports.Plugin; var ui = imports.ui; // Note: the syntax error below is intentional and used by architect_resolver_test.js imports. /***** Initialization *****/ var plugin = new Plugin("Ajax.org", main.consumes); var emit = plugin.getEmitter(); var foo; var bar; var loaded = false; function load() { if (loaded) return false; loaded = true; foo = 1; bar = 2; // ... } function myfunc(arg0, arg1) { } /***** Lifecycle *****/ plugin.on("load", function(){ load(); }); plugin.on("unload", function(){ foo = undefined; }); /***** Register and define API *****/ /** * **/ plugin.freezePublicAPI({ myfunc: myfunc }); //register(null, { "myplugin" : plugin }); register(null, { "myplugin" : { myfunc2: myfunc }}); } });
Handle filenames with path prefixes in git commit logs
import redis import json from django.conf import settings import iconclass import requests import time import os def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) full_name = data['repository']['full_name'] for commit in data.get('commits', []): committer = commit['committer']['email'] timestamp = commit['timestamp'] commit_id = commit['id'] for filename in commit['modified']: if filename.startswith('data/'): filepath, filename = os.path.split(filename) fn, language = iconclass.action(filename[5:]) if not fn: continue r = requests.get('https://raw.githubusercontent.com/'+full_name+'/master/'+filename) if r.status_code == 200: fn(r.content, language) buf = [time.strftime('%Y%m%d %H:%M:%S'), committer, filename, timestamp, commit_id] redis_c.lpush(settings.REDIS_PREFIX + '_gitpushlog', ' '.join(buf))
import redis import json from django.conf import settings import iconclass import requests import time def handle_githubpushes(): redis_c = redis.StrictRedis() while True: data = redis_c.lpop(settings.REDIS_PREFIX + '_gitpushes') if not data: break data = json.loads(data) full_name = data['repository']['full_name'] for commit in data.get('commits', []): committer = commit['committer']['email'] timestamp = commit['timestamp'] commit_id = commit['id'] for filename in commit['modified']: if filename.startswith('data/'): fn, language = iconclass.action(filename[5:]) if not fn: continue r = requests.get('https://raw.githubusercontent.com/'+full_name+'/master/'+filename) if r.status_code == 200: fn(r.content, language) buf = [time.strftime('%Y%m%d %H:%M:%S'), committer, filename, timestamp, commit_id] redis_c.lpush(settings.REDIS_PREFIX + '_gitpushlog', ' '.join(buf))
Make ribbon-webapp's context path configurable.
package org.wildfly.swarm.ribbon.webapp.runtime; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.netflix.ribbon.RibbonArchive; import org.wildfly.swarm.ribbon.webapp.RibbonWebAppFraction; import org.wildfly.swarm.undertow.WARArchive; import java.util.ArrayList; import java.util.List; /** * @author Lance Ball */ public class RibbonWebAppConfiguration extends AbstractServerConfiguration<RibbonWebAppFraction> { private static final String DEFAULT_CONTEXT = "/ribbon"; public RibbonWebAppConfiguration() { super(RibbonWebAppFraction.class); } @Override public RibbonWebAppFraction defaultFraction() { return new RibbonWebAppFraction(); } @Override public List<Archive> getImplicitDeployments(RibbonWebAppFraction fraction) throws Exception { String context = System.getProperty( "wildfly.swarm.ribbon.context.path" ); if (context == null) context = DEFAULT_CONTEXT; List<Archive> list = new ArrayList<>(); WARArchive war = ShrinkWrap.create( WARArchive.class ); war.addClass( RibbonToTheCurbSSEServlet.class ); war.addModule("org.wildfly.swarm.netflix.ribbon"); war.addAsWebResource(new ClassLoaderAsset("ribbon.js", this.getClass().getClassLoader()), "ribbon.js"); war.setContextRoot(context); war.as(RibbonArchive.class); list.add(war); return list; } }
package org.wildfly.swarm.ribbon.webapp.runtime; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.ClassLoaderAsset; import org.wildfly.swarm.container.runtime.AbstractServerConfiguration; import org.wildfly.swarm.netflix.ribbon.RibbonArchive; import org.wildfly.swarm.ribbon.webapp.RibbonWebAppFraction; import org.wildfly.swarm.undertow.WARArchive; import java.util.ArrayList; import java.util.List; /** * @author Lance Ball */ public class RibbonWebAppConfiguration extends AbstractServerConfiguration<RibbonWebAppFraction> { public RibbonWebAppConfiguration() { super(RibbonWebAppFraction.class); } @Override public RibbonWebAppFraction defaultFraction() { return new RibbonWebAppFraction(); } @Override public List<Archive> getImplicitDeployments(RibbonWebAppFraction fraction) throws Exception { List<Archive> list = new ArrayList<>(); WARArchive war = ShrinkWrap.create( WARArchive.class ); war.addClass( RibbonToTheCurbSSEServlet.class ); war.addModule("org.wildfly.swarm.netflix.ribbon"); war.addAsWebResource(new ClassLoaderAsset("ribbon.js", this.getClass().getClassLoader()), "ribbon.js"); war.setContextRoot("/ribbon"); war.as(RibbonArchive.class); list.add(war); return list; } }
Add some debug for debian box
import subprocess import string from pprint import pprint class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) pprint(cliArgs) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.communicate() if process.returncode != 0: return False return output.decode("utf-8").strip() def parseCliArgs(self, command: str): rawArgs = command.split(" ") parsedArgs = [] tmpString = False isSingle = False isDouble = False for arg in rawArgs: # handle strings in single quotes if arg.startswith("'") and isSingle == False and isDouble == False: isSingle = True tmpString = arg elif arg.endswith("'") and isSingle == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isSingle = False tmpString = False # handle strings in double quotes elif arg.startswith('"') and isDouble == False and isSingle == False: isDouble = True tmpString = arg elif arg.endswith('"') and isDouble == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isDouble = False tmpString = False # extend current string elif tmpString != False: tmpString = "%s %s" % (tmpString, arg) else: parsedArgs.append(arg) return parsedArgs
import subprocess import string class Command(object): def execute(self, command: str): cliArgs = self.parseCliArgs(command) process = subprocess.Popen(cliArgs, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, err = process.communicate() if process.returncode != 0: return False return output.decode("utf-8").strip() def parseCliArgs(self, command: str): rawArgs = command.split(" ") parsedArgs = [] tmpString = False isSingle = False isDouble = False for arg in rawArgs: # handle strings in single quotes if arg.startswith("'") and isSingle == False and isDouble == False: isSingle = True tmpString = arg elif arg.endswith("'") and isSingle == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isSingle = False tmpString = False # handle strings in double quotes elif arg.startswith('"') and isDouble == False and isSingle == False: isDouble = True tmpString = arg elif arg.endswith('"') and isDouble == True: arg = "%s %s" % (tmpString, arg) parsedArgs.append(arg) isDouble = False tmpString = False # extend current string elif tmpString != False: tmpString = "%s %s" % (tmpString, arg) else: parsedArgs.append(arg) return parsedArgs
Set the title of the default page
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Initializes a new instance of the `Page` class. */ public function Page() { $this->Template = new BootstrapTemplate($this); $this->Title = 'TemPHPlate - Home'; } /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <h1>TemPHPlate</h1> <p> <img src="./meme.jpg" /> </p> <p> Next you may wanna edit your menu-bar.<br /> Open up <code>/Properties/MenuBar.json</code> for doing so. </p>'; } } } ?>
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace ManuTh\TemPHPlate\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Initializes a new instance of the `Page` class. */ public function Page() { $this->Template = new BootstrapTemplate($this); } /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <h1>TemPHPlate</h1> <p> <img src="./meme.jpg" /> </p> <p> Next you may wanna edit your menu-bar.<br /> Open up <code>/Properties/MenuBar.json</code> for doing so. </p>'; } } } ?>
Add new getExtendedTypes method in form extension for Symfony 4.2 When bumping the requirement to PHP 7.1 the iterable return type should be added
<?php namespace Payum\Bundle\PayumBundle\Form\Extension; use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType; use Payum\Core\Registry\GatewayFactoryRegistryInterface; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Exception; use Symfony\Component\OptionsResolver\OptionsResolver; class GatewayFactoriesChoiceTypeExtension extends AbstractTypeExtension { /** * @var GatewayFactoryRegistryInterface */ private $gatewayFactoryRegistry; /** * @param GatewayFactoryRegistryInterface $gatewayFactoryRegistry */ public function __construct(GatewayFactoryRegistryInterface $gatewayFactoryRegistry) { $this->gatewayFactoryRegistry = $gatewayFactoryRegistry; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $options = $resolver->getDefinedOptions(); if (empty($options['choices'])) { $choices = []; foreach ($this->gatewayFactoryRegistry->getGatewayFactories() as $name => $factory) { $choices['form.choice.'.$name] = $name; } $resolver->setDefaults([ 'choices' => $choices, 'choice_translation_domain' => 'PayumBundle', 'translation_domain' => 'PayumBundle', ]); } } /** * {@inheritdoc} */ public function getExtendedType() { return GatewayFactoriesChoiceType::class; } /** * {@inheritdoc} */ public static function getExtendedTypes() { return [GatewayFactoriesChoiceType::class]; } }
<?php namespace Payum\Bundle\PayumBundle\Form\Extension; use Payum\Core\Bridge\Symfony\Form\Type\GatewayFactoriesChoiceType; use Payum\Core\Registry\GatewayFactoryRegistryInterface; use Symfony\Component\Form\AbstractTypeExtension; use Symfony\Component\Form\Exception; use Symfony\Component\OptionsResolver\OptionsResolver; class GatewayFactoriesChoiceTypeExtension extends AbstractTypeExtension { /** * @var GatewayFactoryRegistryInterface */ private $gatewayFactoryRegistry; /** * @param GatewayFactoryRegistryInterface $gatewayFactoryRegistry */ public function __construct(GatewayFactoryRegistryInterface $gatewayFactoryRegistry) { $this->gatewayFactoryRegistry = $gatewayFactoryRegistry; } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $options = $resolver->getDefinedOptions(); if (empty($options['choices'])) { $choices = []; foreach ($this->gatewayFactoryRegistry->getGatewayFactories() as $name => $factory) { $choices['form.choice.'.$name] = $name; } $resolver->setDefaults([ 'choices' => $choices, 'choice_translation_domain' => 'PayumBundle', 'translation_domain' => 'PayumBundle', ]); } } /** * {@inheritdoc} */ public function getExtendedType() { return GatewayFactoriesChoiceType::class; } }
Add php to extras task
'use strict'; var url = 'http://www.samplesite.com'; var src = './src/'; var build = "./build/"; var dist = "./dist/"; module.exports = { site: { url: url, host: 'hosting.com', user: 'username', password: 'password', uploadPath: '/public_html' }, paths: { src: src, build: build, dist: dist }, browsersync: { port: 4000 }, styles: { paths: [ 'bower_components/foundation-sites/scss', ], version: [ 'last 2 versions', 'ie >= 9' ] }, scripts: { paths: [ // 'bower_components/jquery/dist/jquery.js', // 'bower_components/what-input/what-input.js', // 'bower_components/foundation-sites/js/foundation.core.js', // 'bower_components/foundation-sites/js/foundation.util.*.js', // 'bower_components/foundation-sites/js/foundation.*.js', src + '/assets/scripts/**/*.js', src + '/assets/scripts/main.js' ] }, extras: { 'paths' : [ src + '/favicon.{png,icon,jpg}', src + '/robots.txt', src + '/*html', src + '*.xml', build + '*.php', src + '/.htaccess' ] } };
'use strict'; var url = 'http://www.samplesite.com'; var src = './src/'; var build = "./build/"; var dist = "./dist/"; module.exports = { site: { url: url, host: 'hosting.com', user: 'username', password: 'password', uploadPath: '/public_html' }, paths: { src: src, build: build, dist: dist }, browsersync: { port: 4000 }, styles: { paths: [ 'bower_components/foundation-sites/scss', ], version: [ 'last 2 versions', 'ie >= 9' ] }, scripts: { paths: [ // 'bower_components/jquery/dist/jquery.js', // 'bower_components/what-input/what-input.js', // 'bower_components/foundation-sites/js/foundation.core.js', // 'bower_components/foundation-sites/js/foundation.util.*.js', // 'bower_components/foundation-sites/js/foundation.*.js', src + '/assets/scripts/**/*.js', src + '/assets/scripts/main.js' ] }, extras: { 'paths' : [ src + '/favicon.{png,icon,jpg}', src + '/robots.txt', src + '/*html', src + '*.xml', src + '*.php', src + '/.htaccess' ] } };
Fix invalid error code format for Axes Signed-off-by: Aleksi Häkli <[email protected]>
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e.g. a DummyCache backend and configure it with settings.AXES_CACHE' ) class Codes: CACHE_INVALID = 'axes.E001' @register(Tags.caches) def axes_cache_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument axes_handler = getattr(settings, 'AXES_HANDLER', '') axes_cache_key = getattr(settings, 'AXES_CACHE', 'default') axes_cache_config = settings.CACHES.get(axes_cache_key, {}) axes_cache_backend = axes_cache_config.get('BACKEND', '') axes_cache_backend_incompatible = [ 'django.core.cache.backends.dummy.DummyCache', 'django.core.cache.backends.locmem.LocMemCache', 'django.core.cache.backends.filebased.FileBasedCache', ] errors = [] if axes_handler == 'axes.handlers.cache.AxesCacheHandler': if axes_cache_backend in axes_cache_backend_incompatible: errors.append(Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, )) return errors
from django.core.checks import Error, Tags, register from axes.conf import settings class Messages: CACHE_INVALID = 'invalid cache configuration for settings.AXES_CACHE' class Hints: CACHE_INVALID = ( 'django-axes does not work properly with LocMemCache as the cache backend' ' please add e.g. a DummyCache backend and configure it with settings.AXES_CACHE' ) class Codes: CACHE_INVALID = 'axeslE001' @register(Tags.caches) def axes_cache_backend_check(app_configs, **kwargs): # pylint: disable=unused-argument axes_handler = getattr(settings, 'AXES_HANDLER', '') axes_cache_key = getattr(settings, 'AXES_CACHE', 'default') axes_cache_config = settings.CACHES.get(axes_cache_key, {}) axes_cache_backend = axes_cache_config.get('BACKEND', '') axes_cache_backend_incompatible = [ 'django.core.cache.backends.dummy.DummyCache', 'django.core.cache.backends.locmem.LocMemCache', 'django.core.cache.backends.filebased.FileBasedCache', ] errors = [] if axes_handler == 'axes.handlers.cache.AxesCacheHandler': if axes_cache_backend in axes_cache_backend_incompatible: errors.append(Error( msg=Messages.CACHE_INVALID, hint=Hints.CACHE_INVALID, obj=settings.CACHES, id=Codes.CACHE_INVALID, )) return errors
[REF] openacademy: Modify copy method into inherit
from openerp import api,fields, models ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ] @api.one # api.one send defaults params: cr, uid, id, context def copy(self, default=None): print "estoy pasando por la funcion heredada de copy en cursos" # default['name'] = self.name + ' (copy)' copied_count = self.search_count( [('name', '=like', u"Copy of {}%".format(self.name))]) if not copied_count: new_name = u"Copy of {}".format(self.name) else: new_name = u"Copy of {} ({})".format(self.name, copied_count) default['name'] = new_name return super(Course, self).copy(default)
from openerp import fields, models ''' This module create model of Course ''' class Course(models.Model): ''' This class create model of Course ''' _name = 'openacademy.course' # Model odoo name name = fields.Char(string='Title', required=True) # Field reserved to identified name rec description = fields.Text(string='Description') responsible_id = fields.Many2one('res.users', ondelete='set null', string="Responsible", index=True) session_ids = fields.One2many('openacademy.session', 'course_id', string="Sessions") _sql_constraints = [ ('name_description_check', 'CHECK(name != description)', "The title of the course should not be the description"), ('name_unique', 'UNIQUE(name)', "The course title must be unique"), ]
Allow for 404 not found
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta, false); if (! request) { throw new Error('fluxapp:router:init unable to locate route specified', route); } if (isEnabled()) { window.history.replaceState( request, request.title || '', request.url ); } return request; }, go: function go(id, meta) { var request = router.build(id, meta); if (! request) { throw new Error('fluxapp:router:Go unable to locate route specified', route); } if (isEnabled()) { window.history.pushState( request, request.title, request.url ); } return request; }, back: function back() { if (isEnabled) { window.history.back(); } }, forward: function forward() { if (isEnabled) { window.history.forward(); } } } }
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta); if (! request) { throw new Error('fluxapp:router:init unable to locate route specified', route); } if (isEnabled()) { window.history.replaceState( request, request.title || '', request.url ); } return request; }, go: function go(id, meta) { var request = router.build(id, meta); if (! request) { throw new Error('fluxapp:router:Go unable to locate route specified', route); } if (isEnabled()) { window.history.pushState( request, request.title, request.url ); } return request; }, back: function back() { if (isEnabled) { window.history.back(); } }, forward: function forward() { if (isEnabled) { window.history.forward(); } } } }
Add Execption for invalid Integer Exception class created for invalid integer and raise it if a bad integer is found
from .lexerconstants import * from .ws_token import Tokeniser class IntError(ValueError): '''Exception when invalid integer is found''' class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: raise IntError return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
from .lexerconstants import * from .ws_token import Tokeniser class Lexer(object): def __init__(self, line): self.line = line self.pos = 0 self.tokens = [] def _get_int(self): token = Tokeniser() if self.line[-1] == '\n': const = 'INT' token.scan(self.line, self.pos, const) else: # TODO: Add error handling for invalid integer pass return token def _get_token(self, const): token = Tokeniser() token.scan(self.line, self.pos, const) return token def get_all_tokens(self): while self.pos < len(self.line): const = IMP_CONST if self.pos is 0 else eval( "{}_CONST".format(self.tokens[0].type)) token = self._get_token(const) self.tokens.append(token) self.pos = self.pos + len(token.value) if token.type == 'PUSH': self.tokens.append(self._get_int()) self.pos = len(self.line)
Make sponsored event redirect permanent (HTTP 301)
from django.http import Http404 from django.views.generic import DetailView, ListView, RedirectView from proposals.models import TalkProposal from .models import SponsoredEvent class AcceptedTalkMixin: queryset = ( TalkProposal.objects .filter(accepted=True) .select_related('submitter') .order_by('title') ) class TalkListView(AcceptedTalkMixin, ListView): template_name = 'events/talk_list.html' def get_context_data(self, **kwargs): sponsored_events = ( SponsoredEvent.objects .select_related('host') .order_by('title') ) return super().get_context_data( sponsored_events=sponsored_events, **kwargs ) class TalkDetailView(AcceptedTalkMixin, DetailView): template_name = 'events/talk_detail.html' class SponsoredEventRedirectView(RedirectView): permanent = True def get_redirect_url(self, pk): try: event = SponsoredEvent.objects.get(pk=pk) except SponsoredEvent.DoesNotExist: raise Http404 return event.get_absolute_url() class SponsoredEventDetailView(DetailView): model = SponsoredEvent template_name = 'events/sponsored_event_detail.html' def get_queryset(self): """Fetch user relation before-hand because we'll need it. """ return super().get_queryset().select_related('host')
from django.http import Http404 from django.views.generic import DetailView, ListView, RedirectView from proposals.models import TalkProposal from .models import SponsoredEvent class AcceptedTalkMixin: queryset = ( TalkProposal.objects .filter(accepted=True) .select_related('submitter') .order_by('title') ) class TalkListView(AcceptedTalkMixin, ListView): template_name = 'events/talk_list.html' def get_context_data(self, **kwargs): sponsored_events = ( SponsoredEvent.objects .select_related('host') .order_by('title') ) return super().get_context_data( sponsored_events=sponsored_events, **kwargs ) class TalkDetailView(AcceptedTalkMixin, DetailView): template_name = 'events/talk_detail.html' class SponsoredEventRedirectView(RedirectView): def get_redirect_url(self, pk): try: event = SponsoredEvent.objects.get(pk=pk) except SponsoredEvent.DoesNotExist: raise Http404 return event.get_absolute_url() class SponsoredEventDetailView(DetailView): model = SponsoredEvent template_name = 'events/sponsored_event_detail.html' def get_queryset(self): """Fetch user relation before-hand because we'll need it. """ return super().get_queryset().select_related('host')
REMOVE DEBUG CODE FROM PRODUCTION *whistles innocently*
<?php namespace Korobi\WebBundle\Extension; class ExtensionTwigFunctions extends \Twig_Extension { public function getName() { return 'korobi_extension_twig_functions'; } public function getFunctions() { return [ new \Twig_SimpleFunction('cahFullCard', [$this, 'cahFullCard']), new \Twig_SimpleFunction('cahPlays', [$this, 'cahPlays'], [ 'is_safe' => ['html'] ]), new \Twig_SimpleFunction('gmdate', [$this, 'gmdate']), ]; } public function cahFullCard($blackCard, $data) { foreach($data as $item) { $blackCard = preg_replace('/<BLANK>/', '<strong>' . $item . '</strong>', $blackCard, 1); } return $blackCard; } public function cahPlays($blackCard, $plays) { $result = ''; foreach($plays as $play) { $result .= key($plays) . ': '; $result .= preg_replace('/<BLANK>/', '<strong>' . $play[0] . '</strong>', $blackCard, 1);; $result .= '<br><br>'; next($plays); } return $result; } public function gmdate($format, $timestamp = null) { return gmdate($format, $timestamp); } }
<?php namespace Korobi\WebBundle\Extension; class ExtensionTwigFunctions extends \Twig_Extension { public function getName() { return 'korobi_extension_twig_functions'; } public function getFunctions() { return [ new \Twig_SimpleFunction('cahFullCard', [$this, 'cahFullCard']), new \Twig_SimpleFunction('cahPlays', [$this, 'cahPlays'], [ 'is_safe' => ['html'] ]), new \Twig_SimpleFunction('gmdate', [$this, 'gmdate']), ]; } public function cahFullCard($blackCard, $data) { foreach($data as $item) { $blackCard = preg_replace('/<BLANK>/', '<strong>' . $item . '</strong>', $blackCard, 1); } return $blackCard; } public function cahPlays($blackCard, $plays) { dump($plays); $result = ''; foreach($plays as $play) { $result .= key($plays) . ': '; $result .= preg_replace('/<BLANK>/', '<strong>' . $play[0] . '</strong>', $blackCard, 1);; $result .= '<br><br>'; next($plays); } return $result; } public function gmdate($format, $timestamp = null) { return gmdate($format, $timestamp); } }
Fix wrong merge parameters with same hash
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\Doctrine\QueryBuilder\Filter\ORM; class Between extends AbstractFilter { public function filter($queryBuilder, $metadata, $option) { if (isset($option['where'])) { if ($option['where'] === 'and') { $queryType = 'andWhere'; } elseif ($option['where'] === 'or') { $queryType = 'orWhere'; } } if (! isset($queryType)) { $queryType = 'andWhere'; } if (! isset($option['alias'])) { $option['alias'] = 'row'; } $format = isset($option['format']) ? $option['format'] : null; $from = $this->typeCastField($metadata, $option['field'], $option['from'], $format); $to = $this->typeCastField($metadata, $option['field'], $option['to'], $format); $fromParameter = uniqid('a1'); $toParameter = uniqid('a2'); $queryBuilder->$queryType( $queryBuilder ->expr() ->between( sprintf('%s.%s', $option['alias'], $option['field']), sprintf(':%s', $fromParameter), sprintf(':%s', $toParameter) ) ); $queryBuilder->setParameter($fromParameter, $from); $queryBuilder->setParameter($toParameter, $to); } }
<?php /** * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2014 Zend Technologies USA Inc. (http://www.zend.com) */ namespace ZF\Doctrine\QueryBuilder\Filter\ORM; class Between extends AbstractFilter { public function filter($queryBuilder, $metadata, $option) { if (isset($option['where'])) { if ($option['where'] === 'and') { $queryType = 'andWhere'; } elseif ($option['where'] === 'or') { $queryType = 'orWhere'; } } if (! isset($queryType)) { $queryType = 'andWhere'; } if (! isset($option['alias'])) { $option['alias'] = 'row'; } $format = isset($option['format']) ? $option['format'] : null; $from = $this->typeCastField($metadata, $option['field'], $option['from'], $format); $to = $this->typeCastField($metadata, $option['field'], $option['to'], $format); $fromParameter = uniqid('a'); $toParameter = uniqid('a'); $queryBuilder->$queryType( $queryBuilder ->expr() ->between( sprintf('%s.%s', $option['alias'], $option['field']), sprintf(':%s', $fromParameter), sprintf(':%s', $toParameter) ) ); $queryBuilder->setParameter($fromParameter, $from); $queryBuilder->setParameter($toParameter, $to); } }
Remove confirm_phone_number method from model
#from flask.ext.login import UserMixin from account_verification_flask import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String, nullable = False) email = db.Column(db.String, nullable = False) password = db.Column(db.String) phone_number = db.Column(db.String, nullable = False) country_code = db.Column(db.String, nullable = False) phone_number_confirmed = db.Column(db.Boolean, nullable = False, default = False) authy_user_id = db.Column(db.String, nullable = True) def __init__(self, name, email, password, phone_number, country_code): self.name = name self.email = email self.password = bcrypt.generate_password_hash(password) self.phone_number = phone_number self.country_code = country_code self.phone_number_confirmed = False def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.id) def __unicode__(self): return self.name def __repr__(self): return '<User %r>' % (self.name)
#from flask.ext.login import UserMixin from account_verification_flask import db, bcrypt class User(db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key = True) name = db.Column(db.String, nullable = False) email = db.Column(db.String, nullable = False) password = db.Column(db.String) phone_number = db.Column(db.String, nullable = False) country_code = db.Column(db.String, nullable = False) phone_number_confirmed = db.Column(db.Boolean, nullable = False, default = False) authy_user_id = db.Column(db.String, nullable = True) def __init__(self, name, email, password, phone_number, country_code): self.name = name self.email = email self.password = bcrypt.generate_password_hash(password) self.phone_number = phone_number self.country_code = country_code self.phone_number_confirmed = False def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return unicode(self.id) def confirm_phone_number(self): self.phone_number_confirmed = True def __unicode__(self): return self.name def __repr__(self): return '<User %r>' % (self.name)
Fix race condition in test Registering an event with the shorthand syntax behaves like `.on` and not like `.once` so in this case, if more than one request *will be sent* by the "New Tab" of Chrome then the Mocha's `done()` function gets called twice causing an error. This has been hidden until 85409d3a4633ddb928c64f00db4edce49e88dd17.
var Chrome = require('../'); var assert = require('assert'); describe('registering event', function () { describe('"event"', function () { it('should give the raw message', function (done) { Chrome(function (chrome) { chrome.once('event', function (message) { assert(message.method); chrome.close(done); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); }); it('should give the payload only', function (done) { Chrome(function (chrome) { chrome.once('Network.requestWillBeSent', function (message) { assert(!message.method); chrome.close(done); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); it('should give the payload only (alternate syntax)', function (done) { Chrome(function (chrome) { chrome.Network.requestWillBeSent(function (message) { assert(!message.method); chrome.close(done); // avoid to call `done()` more than once chrome.removeAllListeners(); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); });
var Chrome = require('../'); var assert = require('assert'); describe('registering event', function () { describe('"event"', function () { it('should give the raw message', function (done) { Chrome(function (chrome) { chrome.once('event', function (message) { assert(message.method); chrome.close(done); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); }); it('should give the payload only', function (done) { Chrome(function (chrome) { chrome.once('Network.requestWillBeSent', function (message) { assert(!message.method); chrome.close(done); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); it('should give the payload only (alternate syntax)', function (done) { Chrome(function (chrome) { chrome.Network.requestWillBeSent(function (message) { assert(!message.method); chrome.close(done); }); chrome.send('Network.enable'); chrome.send('Page.navigate', {'url': 'chrome://newtab/'}); }); }); });
Check if text content has been changed
function removeWhitespace(string) { return string.replace(/\s+/g, ''); } describe('scrambler tests', function(){ beforeEach(function() { fixture.setBase('fixtures') }); beforeEach(function(){ this.sample = fixture.load('sample.html'); runSpy = spyOn(scrambler._scrambler, "run").and.callThrough(); jasmine.clock().install(); }); afterEach(function() { fixture.cleanup(); jasmine.clock().uninstall(); }); it('plays with the html fixture', function() { var originalContent = removeWhitespace(this.sample[0].textContent); scrambler.scramble(this.sample[0], false); expect(runSpy.calls.count()).toEqual(1); jasmine.clock().tick(501); expect(runSpy.calls.count()).toEqual(3); expect(originalContent).not.toEqual(removeWhitespace(this.sample[0].textContent)) }); it('defaults on body when calling the go function', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en'); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(document.querySelector('body'), true); }); it('the go function accepts a custom element', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en', this.sample[0]); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(this.sample[0], true); }); });
describe('scrambler tests', function(){ beforeEach(function() { fixture.setBase('fixtures') }); beforeEach(function(){ this.sample = fixture.load('sample.html'); runSpy = spyOn(scrambler._scrambler, "run").and.callThrough(); jasmine.clock().install(); }); afterEach(function() { fixture.cleanup(); jasmine.clock().uninstall(); }); it('plays with the html fixture', function() { scrambler.scramble(this.sample[0], false); expect(runSpy.calls.count()).toEqual(1); jasmine.clock().tick(501); expect(runSpy.calls.count()).toEqual(3); // TODO: check if the text has been scrambled }); it('defaults on body when calling the go function', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en'); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(document.querySelector('body'), true); }); it('the go function accepts a custom element', function() { var scramblerSpy = spyOn(scrambler, "scramble"); scrambler.go('en', this.sample[0]); expect(scramblerSpy.calls.count()).toEqual(1); expect(scramblerSpy).toHaveBeenCalledWith(this.sample[0], true); }); });
Revert "Reduce anonymous function creation during iteration for edge cases" This reverts commit 38006447b94b9113998954f15b6b869313e09d9e.
'use strict' var values = require('../sources/values') var once = require('../sources/once') //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and then stream of streams. _read ? _read(abort, function(err) { read(err || abort, cb) }) : read(abort, cb) } else if(_read) nextChunk() else nextStream() function nextChunk () { _read(null, function (err, data) { if (err) { if (err === true) nextStream() else read(true, function(abortErr) { // TODO: what do we do with the abortErr? cb(err) }) } else cb(null, data) }) } function nextStream () { _read = null read(null, function (end, stream) { if(end) return cb(end) if(stream && 'object' === typeof stream) stream = values(stream) else if ('function' !== typeof stream) stream = once(stream) _read = stream nextChunk() }) } } } }
'use strict' var values = require('../sources/values') var once = require('../sources/once') function getAbortCb(read, abort, cb) { return function(err) { read(err || abort, cb) } } function getChunkErrorCb(err, cb) { return function() { cb(err) } } //convert a stream of arrays or streams into just a stream. module.exports = function flatten () { return function (read) { var _read return function (abort, cb) { if (abort) { //abort the current stream, and then stream of streams. _read ? _read(abort, getAbortCb(read, abort, cb)) : read(abort, cb) } else if(_read) nextChunk() else nextStream() function nextChunk () { _read(null, function (err, data) { if (err) { if (err === true) nextStream() else read(true, getChunkErrorCb(err, cb)) } else cb(null, data) }) } function nextStream () { _read = null read(null, function (end, stream) { if(end) return cb(end) if(stream && 'object' === typeof stream) stream = values(stream) else if ('function' !== typeof stream) stream = once(stream) _read = stream nextChunk() }) } } } }
Add origin function to vendor
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); var currentOrigin = function(url){ var parts = url.split(/\/\/?/); parts[1] = location.origin; return parts.slice(1).join("/"); } tinymce.create('tinymce.plugins.UploadImagePlugin', { init: function(ed, url) { ed.addCommand('mceUploadImage', function() { return ed.windowManager.open({ file: currentOrigin(url) + '/dialog.html', width: 350 + parseInt(ed.getLang('uploadimage.delta_width', 0)), height: 220 + parseInt(ed.getLang('uploadimage.delta_height', 0)), inline: 1 }, { plugin_url: currentOrigin(url) }); }); ed.addButton('uploadimage', { title: 'uploadimage.desc', cmd: 'mceUploadImage', image: url + '/img/uploadimage.png' }); return ed.onNodeChange.add(function(ed, cm, n) { return cm.setActive('uploadimage', n.nodeName === 'IMG'); }); }, createControl: function(n, cm) { return null; }, getInfo: function() { return { longname: 'UploadImage plugin', author: 'Per Christian B. Viken (borrows heavily from work done by Peter Shoukry of 77effects.com)', authorurl: 'eastblue.org/oss', infourl: 'eastblue.org/oss', version: '1.0' }; } }); return tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImagePlugin); })();
(function() { tinymce.PluginManager.requireLangPack('uploadimage'); tinymce.create('tinymce.plugins.UploadImagePlugin', { init: function(ed, url) { ed.addCommand('mceUploadImage', function() { return ed.windowManager.open({ file: url + '/dialog.html', width: 350 + parseInt(ed.getLang('uploadimage.delta_width', 0)), height: 220 + parseInt(ed.getLang('uploadimage.delta_height', 0)), inline: 1 }, { plugin_url: url }); }); ed.addButton('uploadimage', { title: 'uploadimage.desc', cmd: 'mceUploadImage', image: url + '/img/uploadimage.png' }); return ed.onNodeChange.add(function(ed, cm, n) { return cm.setActive('uploadimage', n.nodeName === 'IMG'); }); }, createControl: function(n, cm) { return null; }, getInfo: function() { return { longname: 'UploadImage plugin', author: 'Per Christian B. Viken (borrows heavily from work done by Peter Shoukry of 77effects.com)', authorurl: 'eastblue.org/oss', infourl: 'eastblue.org/oss', version: '1.0' }; } }); return tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImagePlugin); })();
Use the user's getters to check if we need to set the plainpassword
<?php namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject; use SumoCoders\FrameworkMultiUserBundle\User\User; use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword; class UserWithPasswordDataTransferObject implements UserDataTransferObject { /** * @var int */ public $id; /** * @var string */ public $userName; /** * @var string */ public $displayName; /** * @var string */ public $email; /** * @var string */ public $plainPassword; /** * @var User */ private $user; /** * @param User $user * * @return User */ public static function fromUser(User $user) { $baseUserTransferObject = new self(); $baseUserTransferObject->user = $user; $baseUserTransferObject->id = $user->getId(); $baseUserTransferObject->userName = $user->getUsername(); $baseUserTransferObject->displayName = $user->getDisplayName(); $baseUserTransferObject->email = $user->getEmail(); if ($user->hasPlainPassword()) { $baseUserTransferObject->plainPassword = $user->getPlainPassword(); } return $baseUserTransferObject; } /** * @return UserWithPassword */ public function getEntity() { if ($this->user) { $this->user->change($this); return $this->user; } return new UserWithPassword( $this->userName, $this->plainPassword, $this->displayName, $this->email ); } }
<?php namespace SumoCoders\FrameworkMultiUserBundle\DataTransferObject; use SumoCoders\FrameworkMultiUserBundle\User\User; use SumoCoders\FrameworkMultiUserBundle\User\UserWithPassword; class UserWithPasswordDataTransferObject implements UserDataTransferObject { /** * @var int */ public $id; /** * @var string */ public $userName; /** * @var string */ public $displayName; /** * @var string */ public $email; /** * @var string */ public $plainPassword; /** * @var User */ private $user; /** * @param User $user * * @return User */ public static function fromUser(User $user) { $baseUserTransferObject = new self(); $baseUserTransferObject->user = $user; $baseUserTransferObject->id = $user->getId(); $baseUserTransferObject->userName = $user->getUsername(); $baseUserTransferObject->displayName = $user->getDisplayName(); $baseUserTransferObject->email = $user->getEmail(); return $baseUserTransferObject; } /** * @return UserWithPassword */ public function getEntity() { $this->user->change($this); return $this->user; } }
Decrease the threshold for lines in unit tests coverage by 1%
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides (testType) { switch (testType) { case 'cli': return { statements: 80, branches: 65, functions: 85, lines: 80 }; case 'integration': return { statements: 35, branches: 20, functions: 35, lines: 35 }; case 'library': return { statements: 55, branches: 40, functions: 55, lines: 55 }; case 'unit': return { statements: 70, branches: 55, functions: 75, lines: 70 }; default: return {} } } module.exports = { all: true, 'check-coverage': true, 'report-dir': '.coverage', 'temp-dir': '.nyc_output', include: ['lib/**/*.js', 'bin/**/*.js'], reporter: ['lcov', 'json', 'text', 'text-summary'], ...configOverrides(TEST_TYPE), };
const TEST_TYPE = ((argv) => { let match = argv[argv.length - 1].match(/npm\/test-(\w+).js/); return match && match[1] || ''; })(process.argv); function configOverrides (testType) { switch (testType) { case 'cli': return { statements: 80, branches: 65, functions: 85, lines: 80 }; case 'integration': return { statements: 35, branches: 20, functions: 35, lines: 35 }; case 'library': return { statements: 55, branches: 40, functions: 55, lines: 55 }; case 'unit': return { statements: 70, branches: 55, functions: 75, lines: 75 }; default: return {} } } module.exports = { all: true, 'check-coverage': true, 'report-dir': '.coverage', 'temp-dir': '.nyc_output', include: ['lib/**/*.js', 'bin/**/*.js'], reporter: ['lcov', 'json', 'text', 'text-summary'], ...configOverrides(TEST_TYPE), };
Fix pagination of locations filter
from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.locations.permissions import location_safe from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider from custom.enikshay.reports.utils import StubReport @location_safe class LocationsView(View): @method_decorator(login_and_domain_required) def dispatch(self, *args, **kwargs): return super(LocationsView, self).dispatch(*args, **kwargs) def get(self, request, domain, *args, **kwargs): user = self.request.couch_user query_context = ChoiceQueryContext( query=request.GET.get('q', None), limit=int(request.GET.get('limit', 20)), page=int(request.GET.get('page', 1)) - 1, user=user ) location_choice_provider = LocationChoiceProvider(StubReport(domain=domain), None) location_choice_provider.configure({'include_descendants': True}) return JsonResponse( { 'results': [ {'id': location.value, 'text': location.display} for location in location_choice_provider.query(query_context) ], 'total': location_choice_provider.query_count(query_context.query, user) } )
from django.http.response import JsonResponse from django.utils.decorators import method_decorator from django.views.generic.base import View from corehq.apps.domain.decorators import login_and_domain_required from corehq.apps.locations.permissions import location_safe from corehq.apps.userreports.reports.filters.choice_providers import ChoiceQueryContext, LocationChoiceProvider from custom.enikshay.reports.utils import StubReport @location_safe class LocationsView(View): @method_decorator(login_and_domain_required) def dispatch(self, *args, **kwargs): return super(LocationsView, self).dispatch(*args, **kwargs) def get(self, request, domain, *args, **kwargs): user = self.request.couch_user query_context = ChoiceQueryContext( query=request.GET.get('q', None), limit=int(request.GET.get('limit', 20)), page=int(request.GET.get('page', 1)) - 1, user=user ) location_choice_provider = LocationChoiceProvider(StubReport(domain=domain), None) location_choice_provider.configure({'include_descendants': True}) return JsonResponse( { 'results': [ {'id': location.value, 'text': location.display} for location in location_choice_provider.query(query_context) ], 'total': location_choice_provider.query_count(query_context, user) } )
Mark feedback comments starting with a html tag as spammy
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm import re @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks message and link back to the page.""" submit_was_success = False return_to_url = None # If it is a post request try to create the feedback if request.method == 'POST': form = FeedbackForm( request.POST ) if form.is_valid(): feedback = Feedback() feedback.url = form.cleaned_data['url'] feedback.email = form.cleaned_data['email'] feedback.comment = form.cleaned_data['comment'] # if there is any content in the honeypot field then label this comment as spammy if form.cleaned_data['website']: feedback.status = 'spammy' # if the comment starts with an html tag it is probably spam if re.search('\A\s*<\w+>', form.cleaned_data['comment']): feedback.status = 'spammy' if request.user.is_authenticated(): feedback.user = request.user feedback.save() submit_was_success = True return_to_url = feedback.url or None else: # use GET to grab the url if set form = FeedbackForm(initial=request.GET) return render_to_response( 'feedback/add.html', { 'form': form, 'submit_was_success': submit_was_success, 'return_to_url': return_to_url, }, context_instance=RequestContext(request) )
from django.shortcuts import render_to_response from django.template import RequestContext from django.views.decorators.csrf import csrf_protect from models import Feedback from forms import FeedbackForm @csrf_protect def add(request): """Gather feedback for a page, and if it is ok show a thanks message and link back to the page.""" submit_was_success = False return_to_url = None # If it is a post request try to create the feedback if request.method == 'POST': form = FeedbackForm( request.POST ) if form.is_valid(): feedback = Feedback() feedback.url = form.cleaned_data['url'] feedback.email = form.cleaned_data['email'] feedback.comment = form.cleaned_data['comment'] # if there is any content in the honeypot field then label this comment as spammy if form.cleaned_data['website']: feedback.status = 'spammy' if request.user.is_authenticated(): feedback.user = request.user feedback.save() submit_was_success = True return_to_url = feedback.url or None else: # use GET to grab the url if set form = FeedbackForm(initial=request.GET) return render_to_response( 'feedback/add.html', { 'form': form, 'submit_was_success': submit_was_success, 'return_to_url': return_to_url, }, context_instance=RequestContext(request) )
Format translation of "Delete Attribute" for javascript
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <div style="display: none"> <div id="ccm-dialog-delete-attribute" class="ccm-ui"> <form method="post" action="<?= $deleteAction ?>"> <?=Core::make("token")->output('delete_attribute')?> <input type="hidden" name="id" value="<?=$key->getAttributeKeyID()?>"> <p><?=t('Are you sure you want to delete this attribute? This cannot be undone.')?></p> <div class="dialog-buttons"> <button class="btn btn-default pull-left" onclick="jQuery.fn.dialog.closeTop()"><?=t('Cancel')?></button> <button class="btn btn-danger pull-right" onclick="$('#ccm-dialog-delete-attribute form').submit()"><?=t('Delete Attribute')?></button> </div> </form> </div> </div> <button type="button" class="btn btn-danger" data-action="delete-attribute"><?= t('Delete Attribute') ?></button> <script type="text/javascript"> $(function() { $('button[data-action=delete-attribute]').on('click', function() { var $element = $('#ccm-dialog-delete-attribute'); jQuery.fn.dialog.open({ element: $element, modal: true, width: 320, title: <?= json_encode(t('Delete Attribute')) ?>, height: 'auto' }); }); }); </script>
<?php defined('C5_EXECUTE') or die("Access Denied."); ?> <div style="display: none"> <div id="ccm-dialog-delete-attribute" class="ccm-ui"> <form method="post" action="<?= $deleteAction ?>"> <?=Core::make("token")->output('delete_attribute')?> <input type="hidden" name="id" value="<?=$key->getAttributeKeyID()?>"> <p><?=t('Are you sure you want to delete this attribute? This cannot be undone.')?></p> <div class="dialog-buttons"> <button class="btn btn-default pull-left" onclick="jQuery.fn.dialog.closeTop()"><?=t('Cancel')?></button> <button class="btn btn-danger pull-right" onclick="$('#ccm-dialog-delete-attribute form').submit()"><?=t('Delete Attribute')?></button> </div> </form> </div> </div> <button type="button" class="btn btn-danger" data-action="delete-attribute"><?= t('Delete Attribute') ?></button> <script type="text/javascript"> $(function() { $('button[data-action=delete-attribute]').on('click', function() { var $element = $('#ccm-dialog-delete-attribute'); jQuery.fn.dialog.open({ element: $element, modal: true, width: 320, title: '<?=t('Delete Attribute')?>', height: 'auto' }); }); }); </script>
Make \G or \g to end a query.
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon text.endswith('\\g') or # Ended with \g text.endswith('\\G') or # Ended with \G (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
from prompt_toolkit.buffer import Buffer from prompt_toolkit.filters import Condition class CLIBuffer(Buffer): def __init__(self, always_multiline, *args, **kwargs): self.always_multiline = always_multiline @Condition def is_multiline(): doc = self.document return self.always_multiline and not _multiline_exception(doc.text) super(self.__class__, self).__init__(*args, is_multiline=is_multiline, tempfile_suffix='.sql', **kwargs) def _multiline_exception(text): orig = text text = text.strip() # Multi-statement favorite query is a special case. Because there will # be a semicolon separating statements, we can't consider semicolon an # EOL. Let's consider an empty line an EOL instead. if text.startswith('\\fs'): return orig.endswith('\n') return (text.startswith('\\') or # Special Command text.endswith(';') or # Ended with a semi-colon (text == 'exit') or # Exit doesn't need semi-colon (text == 'quit') or # Quit doesn't need semi-colon (text == ':q') or # To all the vim fans out there (text == '') # Just a plain enter without any text )
Fix error with TV screen
var TvApi = require('node-lgtv-api'); var imageName = 'screen.jpg'; module.exports = { handle: function (ctx, message, sendMessage) { var lgTV = ctx.config.network.lgTV; var tvApi = new TvApi(lgTV.host, lgTV.port, lgTV.pairingKey); tvApi.authenticate(function (err, sessionKey) { if (err) { console.error(err); } else { tvApi.takeScreenShot(imageName, function (err, data) { if (err) { console.error(err); } else { ctx.log.debug(message.from.username + ' <- ' + imageName); ctx.bot.sendPhoto(message.from.id, imageName, {caption: 'TV Screen'}); } }); } } ); } };
var TvApi = require('node-lgtv-api'); var imageName = 'screen.jpg'; module.exports = { handle: function (ctx, message, sendMessage) { var lgTV = ctx.network.lgTV; var tvApi = new TvApi(lgTV.host, lgTV.port, lgTV.pairingKey); tvApi.authenticate(function (err, sessionKey) { if (err) { console.error(err); } else { tvApi.takeScreenShot(imageName, function (err, data) { if (err) { console.error(err); } else { ctx.log.debug(message.from.username + ' <- ' + imageName); ctx.bot.sendPhoto(message.from.id, imageName, {caption: 'TV Screen'}); } }); } } ); } };
Add default template for testimonial block
<?php namespace Concrete\Package\Worldskills\Theme\Worldskills; use Concrete\Core\Page\Theme\Theme; class PageTheme extends Theme { public function registerAssets() { $this->requireAsset('javascript', 'jquery'); $this->providesAsset('css', 'bootstrap/*'); $this->providesAsset('css', 'core/frontend/pagination'); $this->requireAsset('css', 'font-awesome'); } protected $pThemeGridFrameworkHandle = 'bootstrap4'; public function getThemeName() { return 'WorldSkills'; } public function getThemeDescription() { return 'A theme in the WorldSkills brand suited for WorldSkills websites.'; } public function getThemeBlockClasses() { return array( ); } public function getThemeAreaClasses() { } public function getThemeDefaultBlockTemplates() { return array( 'content' => 'worldskills_content.php', 'image' => 'worldskills_fluid.php', 'testimonial' => 'worldskills_pullquote.php', ); } public function getThemeEditorClasses() { return array( array('title' => t('Lead'), 'menuClass' => 'lead', 'spanClass' => 'lead', 'forceBlock' => 1), array('title' => t('Cube icon'), 'menuClass' => '', 'spanClass' => 'ws-h-icon', 'forceBlock' => 1), array('title' => t('Serif font'), 'menuClass' => 'text-serif', 'spanClass' => 'text-serif', 'forceBlock' => 1), ); } }
<?php namespace Concrete\Package\Worldskills\Theme\Worldskills; use Concrete\Core\Page\Theme\Theme; class PageTheme extends Theme { public function registerAssets() { $this->requireAsset('javascript', 'jquery'); $this->providesAsset('css', 'bootstrap/*'); $this->providesAsset('css', 'core/frontend/pagination'); $this->requireAsset('css', 'font-awesome'); } protected $pThemeGridFrameworkHandle = 'bootstrap4'; public function getThemeName() { return 'WorldSkills'; } public function getThemeDescription() { return 'A theme in the WorldSkills brand suited for WorldSkills websites.'; } public function getThemeBlockClasses() { return array( ); } public function getThemeAreaClasses() { } public function getThemeDefaultBlockTemplates() { return array( 'content' => 'worldskills_content.php', 'image' => 'worldskills_fluid.php', ); } public function getThemeEditorClasses() { return array( array('title' => t('Lead'), 'menuClass' => 'lead', 'spanClass' => 'lead', 'forceBlock' => 1), array('title' => t('Cube icon'), 'menuClass' => '', 'spanClass' => 'ws-h-icon', 'forceBlock' => 1), array('title' => t('Serif font'), 'menuClass' => 'text-serif', 'spanClass' => 'text-serif', 'forceBlock' => 1), ); } }
Use numbers instead of percent in chart
$(document).ready(function () { google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var elem = $('#pie_chart').get(0); var headerParts = elem.dataset.header.split(','); var data = [[headerParts[0], headerParts[1]]]; var values = elem.dataset.values.split(';'); var names = []; values.forEach(function (str, _, _) { var all = str.split(','); data.push([all[0], parseInt(all[1])]); names.push(all[0]); }); var dataTable = google.visualization.arrayToDataTable(data); var options = { title: elem.dataset.title, pieSliceText: 'value', }; var chart = new google.visualization.PieChart(elem); chart.draw(dataTable, options); google.visualization.events.addListener(chart, 'select', function () { var selectedItem = chart.getSelection()[0]; if (selectedItem) { var name = names[selectedItem.row]; $('#filter_assignee').attr('value', name); $('#filter_form').submit() } }); } });
$(document).ready(function () { google.charts.load('current', { packages: ['corechart', 'bar'] }); google.charts.setOnLoadCallback(drawChart); function drawChart() { var elem = $('#pie_chart').get(0); var headerParts = elem.dataset.header.split(','); var data = [[headerParts[0], headerParts[1]]]; var values = elem.dataset.values.split(';'); var names = []; values.forEach(function (str, _, _) { var all = str.split(','); data.push([all[0], parseInt(all[1])]); names.push(all[0]); }); var dataTable = google.visualization.arrayToDataTable(data); var options = { title: elem.dataset.title, }; var chart = new google.visualization.PieChart(elem); chart.draw(dataTable, options); google.visualization.events.addListener(chart, 'select', function () { var selectedItem = chart.getSelection()[0]; if (selectedItem) { var name = names[selectedItem.row]; $('#filter_assignee').attr('value', name); $('#filter_form').submit() } }); } });
Fix PicleCache error on Python3
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): self._cache[k] = v class PickleCache(Cache): def __init__(self, filename='cache.db'): self.filename = filename self._cache = self.load() def load(self): if os.path.exists(self.filename): with closing(open(self.filename, 'rb')) as fh: return pickle.load(fh) return {} def save(self): with closing(open(self.filename, 'wb')) as fh: pickle.dump(self._cache, fh) if Redis: class RedisCache(Cache): def __init__(self, namespace='micawber', **conn): self.namespace = namespace self.key_fn = lambda self, k: '%s.%s' % (self.namespace, k) self.conn = Redis(**conn) def get(self, k): cached = self.conn.get(self.key_fn(k)) if cached: return pickle.loads(cached) def set(self, k, v): self.conn.set(self.key_fn(k), pickle.dumps(v))
from __future__ import with_statement import os import pickle from contextlib import closing try: from redis import Redis except ImportError: Redis = None class Cache(object): def __init__(self): self._cache = {} def get(self, k): return self._cache.get(k) def set(self, k, v): self._cache[k] = v class PickleCache(Cache): def __init__(self, filename='cache.db'): self.filename = filename self._cache = self.load() def load(self): if os.path.exists(self.filename): with closing(open(self.filename)) as fh: contents = fh.read() return pickle.loads(contents) return {} def save(self): with closing(open(self.filename, 'w')) as fh: fh.write(pickle.dumps(self._cache)) if Redis: class RedisCache(Cache): def __init__(self, namespace='micawber', **conn): self.namespace = namespace self.key_fn = lambda self, k: '%s.%s' % (self.namespace, k) self.conn = Redis(**conn) def get(self, k): cached = self.conn.get(self.key_fn(k)) if cached: return pickle.loads(cached) def set(self, k, v): self.conn.set(self.key_fn(k), pickle.dumps(v))
Add catch for Travis CI testing.
__all__ = [ 'test', ] def test(close=False): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment: ```bash $ python -m PVGeo test ``` ```py >>> import PVGeo >>> PVGeo.test() ``` """ import unittest import fnmatch import os path = os.path.dirname(__file__) # path to remove path = path[0:path.rfind('/')] test_file_strings = [] for root, dirnames, filenames in os.walk(os.path.dirname(__file__)): for filename in fnmatch.filter(filenames, '__test__.py'): test_file_strings.append(os.path.join(root, filename).replace(path, '')) # Remove extensions and change to module import syle module_strings = [str[1:len(str)-3].replace('/', '.') for str in test_file_strings] suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings] testSuite = unittest.TestSuite(suites) run = unittest.TextTestRunner(verbosity=2).run(testSuite) if close: exit(len(run.failures) > 0 or len(run.errors) > 0) return run if __name__ == '__main__': import sys arg = sys.argv[1] if arg.lower() == 'test': test(True) else: raise RuntimeError('Unknown argument: %s' % arg)
__all__ = [ 'test', ] def test(): """ @desc: This is a convienance method to run all of the tests in `PVGeo`. @notes: This can be executed from either the command line of within a standard Python environment: ```bash $ python -m PVGeo test ``` ```py >>> import PVGeo >>> PVGeo.test() ``` """ import unittest import fnmatch import os path = os.path.dirname(__file__) # path to remove path = path[0:path.rfind('/')] test_file_strings = [] for root, dirnames, filenames in os.walk(os.path.dirname(__file__)): for filename in fnmatch.filter(filenames, '__test__.py'): test_file_strings.append(os.path.join(root, filename).replace(path, '')) # Remove extensions and change to module import syle module_strings = [str[1:len(str)-3].replace('/', '.') for str in test_file_strings] suites = [unittest.defaultTestLoader.loadTestsFromName(str) for str in module_strings] testSuite = unittest.TestSuite(suites) return unittest.TextTestRunner(verbosity=2).run(testSuite) if __name__ == '__main__': import sys arg = sys.argv[1] if arg.lower() == 'test': test() else: raise RuntimeError('Unknown argument: %s' % arg)
Add basic e2e for search field.
describe('idai field app', function() { function createObject() { return clickCreateObject() .then(selectTypeObject) .then(typeInIdentifier) .then(saveObject); } function clickCreateObject() { return element(by.id('object-overview-button-create-object')).click() } function selectTypeObject() { return element(by.id('create-object-option-0')).click(); } function typeInIdentifier() { return element(by.id('object-edit-input-identifier')).clear().sendKeys('1').sendKeys('2'); } function typeInIdentifierInSearchField() { return element(by.id('object-search')).clear().sendKeys('1').sendKeys('2'); } function saveObject() { return element(by.id('object-edit-button-save-object')).click(); } beforeEach(function(){ browser.get('/'); }); it('should create a new object of first listed type ', function() { createObject() .then(function(){ expect(element(by.id('object-overview-identifier-0')).getText()).toEqual("12"); }); }); it('should warn if an existing id is used ', function() { createObject() .then(createObject) .then(function(){ expect(element(by.id('message-0')).getText()). toEqual("Objekt Identifier existiert bereits. Bei Klick auf ein anderes Objekt wird der ursprüngliche Zustand wiederhergestellt."); }); }); it('should find it by its identifier', function() { createObject() .then(typeInIdentifierInSearchField) .then(function(){ expect(element(by.id('object-overview-identifier-0')).getText()).toEqual("12"); }); }); });
describe('idai field app', function() { function createObject() { return clickCreateObject() .then(selectTypeObject) .then(typeInIdentifier) .then(saveObject); } function clickCreateObject() { return element(by.id('object-overview-button-create-object')).click() } function selectTypeObject() { return element(by.id('create-object-option-0')).click(); } function typeInIdentifier() { return element(by.id('object-edit-input-identifier')).clear().sendKeys('1').sendKeys('2'); } function saveObject() { return element(by.id('object-edit-button-save-object')).click(); } beforeEach(function(){ browser.get('/'); }); it('should create a new object of first listed type ', function() { createObject() .then(function(){ expect(element(by.id('object-overview-identifier-0')).getText()).toEqual("12"); }); }); it('should warn if an existing id is used ', function() { createObject() .then(createObject) .then(function(){ expect(element(by.id('message-0')).getText()). toEqual("Objekt Identifier existiert bereits. Bei Klick auf ein anderes Objekt wird der ursprüngliche Zustand wiederhergestellt."); }); }); });
Handle an authentication edge case
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: request.season = Season.objects.get_by_year(year) except Season.DoesNotExist: raise Http404("Такой сезон еще не создан") class MemberMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs and request.user.is_authenticated: year = int(view_kwargs["year"]) try: request.member = Member.objects.get_by_user_and_year( request.user, year) except Member.DoesNotExist: request.member = None class XUserMiddleware(object): def process_response(self, request, response): if not hasattr(request, "user"): return response if request.user.is_anonymous: return response # Чтобы Nginx мог писать имя пользователя в логи response["X-User"] = request.user.username return response
from django.http import Http404 from django.utils import timezone from clubadm.models import Member, Season class SeasonMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs: year = int(view_kwargs["year"]) try: request.season = Season.objects.get_by_year(year) except Season.DoesNotExist: raise Http404("Такой сезон еще не создан") class MemberMiddleware(object): def process_view(self, request, view_func, view_args, view_kwargs): if "year" in view_kwargs and request.user.is_authenticated: year = int(view_kwargs["year"]) try: request.member = Member.objects.get_by_user_and_year( request.user, year) except Member.DoesNotExist: request.member = None class XUserMiddleware(object): def process_response(self, request, response): if request.user.is_anonymous: return response # Чтобы Nginx мог писать имя пользователя в логи response["X-User"] = request.user.username return response
Add note about how to generate trajectories
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename # command for generating reference data: # gmx mdrun -nsteps 5000 -s frame0.tpr -cpi -noappend # # Do that three times. def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
"""Tools for setting up a fake directory structure for processing.""" from tempfile import mkdtemp import os import shutil import json from pkg_resources import resource_filename def write_run_clone(proj, run, clone, gens=None): if gens is None: gens = [0, 1] rc = "data/PROJ{proj}/RUN{run}/CLONE{clone}/".format(proj=proj, run=run, clone=clone) os.makedirs(rc, exist_ok=True) tpr_fn = resource_filename(__name__, 'topol.tpr') shutil.copy(tpr_fn, "{}/frame0.tpr".format(rc)) for gen in gens: shutil.copy(resource_filename(__name__, "traj_comp.part{:04d}.xtc".format( gen + 1)), "{}/frame{}.xtc".format(rc, gen)) def generate_project(): global wd wd = mkdtemp() os.chdir(wd) write_run_clone(1234, 5, 7) write_run_clone(1234, 6, 0) with open('structs-p1234.json', 'w') as f: json.dump({ 5: {'struct': 'stru1', 'fext': 'pdb'}, 6: {'struct': 'stru2', 'fext': 'pdb'} }, f) def cleanup(): shutil.rmtree(wd)
Allow webpack errors to be displayed (suppress browserSyncInstance.reload)
let argv = require('yargs').argv; let command = require('node-cmd'); let jigsaw = require('./tasks/bin'); let mix = require('laravel-mix'); let AfterBuild = require('on-build-webpack'); let BrowserSync = require('browser-sync'); let BrowserSyncPlugin = require('browser-sync-webpack-plugin'); let Watch = require('webpack-watch'); const env = argv.e || argv.env || 'local'; const port = argv.p || argv.port || 3000; const buildPath = 'build_' + env + '/'; let browserSyncInstance; let plugins = [ new AfterBuild(() => { command.get(jigsaw.path() + ' build ' + env, (error, stdout, stderr) => { console.log(error ? stderr : stdout); if (browserSyncInstance) { browserSyncInstance.reload(); } }); }), new BrowserSyncPlugin({ proxy: null, port: port, server: { baseDir: buildPath }, notify: false, }, { reload: false, callback: function() { browserSyncInstance = BrowserSync.get('bs-webpack-plugin'); }, }), new Watch({ paths: ['source/**/*.md', 'source/**/*.php'], options: { ignoreInitial: true } }), ]; mix.webpackConfig({ plugins }); mix.disableSuccessNotifications(); mix.setPublicPath('source/assets/'); mix.js('source/_assets/js/main.js', 'js/') .sass('source/_assets/sass/main.scss', 'css/') .version();
let argv = require('yargs').argv; let command = require('node-cmd'); let jigsaw = require('./tasks/bin'); let mix = require('laravel-mix'); let AfterBuild = require('on-build-webpack'); let BrowserSync = require('browser-sync'); let BrowserSyncPlugin = require('browser-sync-webpack-plugin'); let Watch = require('webpack-watch'); const env = argv.e || argv.env || 'local'; const port = argv.p || argv.port || 3000; const buildPath = 'build_' + env + '/'; let browserSyncInstance; let plugins = [ new AfterBuild(() => { command.get(jigsaw.path() + ' build ' + env, (error, stdout, stderr) => { console.log(error ? stderr : stdout); browserSyncInstance.reload(); }); }), new BrowserSyncPlugin({ proxy: null, port: port, server: { baseDir: buildPath }, notify: false, }, { reload: false, callback: function() { browserSyncInstance = BrowserSync.get('bs-webpack-plugin'); }, }), new Watch({ paths: ['source/**/*.md', 'source/**/*.php'], options: { ignoreInitial: true } }), ]; mix.webpackConfig({ plugins }); mix.disableSuccessNotifications(); mix.setPublicPath('source/assets/'); mix.js('source/_assets/js/main.js', 'js/') .sass('source/_assets/sass/main.scss', 'css/') .version();
Use LocalFileAdapter when no scheme is given >>> t1 = Transporter('/file/path') >>> t2 = Transporter('file:/file/path') >>> type(t1.adapter) == type(t2.adapter) True >>> t1.pwd() == t2.pwd() True
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapter, "ftps": adapters.FtpAdapter, "file": adapters.LocalFileAdapter } default_scheme = "file" adapter = None def __init__(self, uri): uri = urlparse(uri) scheme = uri.scheme or self.default_scheme if scheme not in self.availible_adapters: msg = u"{0} is not a support scheme. Availible schemes: {1}".format( scheme, [s for s in self.availible_adapters]) raise NotImplemented(msg) self.adapter = self.availible_adapters[scheme](uri) def __getattr__(self, attr): return getattr(self.adapter, attr) def __repr__(self): return u'<Transporter {0}>'.format(self.adapter.__repr__()) def download(uri): f = os.path.basename(uri) uri = os.path.dirname(uri) uri = urlparse(uri) return Transporter(uri).download(f) def upload(f, uri): return Transporter(uri).upload(f) def transport(source, destination): f = download(source) return upload(destination, f)
from urlparse import urlparse import os import adapters try: import paramiko except ImportError: pass """The following protocals are supported ftp, ftps, http and https. sftp and ssh require paramiko to be installed """ class Transporter(object): availible_adapters = { "ftp": adapters.FtpAdapter, "ftps": adapters.FtpAdapter, "file": adapters.LocalFileAdapter } adapter = None def __init__(self, uri): uri = urlparse(uri) if uri.scheme not in self.availible_adapters: msg = u"{0} is not a support scheme. Availible schemes: {1}".format( uri.scheme, [s for s in self.availible_adapters]) raise NotImplemented(msg) self.adapter = self.availible_adapters[uri.scheme](uri) def __getattr__(self, attr): return getattr(self.adapter, attr) def __repr__(self): return u'<Transporter {0}>'.format(self.adapter.__repr__()) def download(uri): f = os.path.basename(uri) uri = os.path.dirname(uri) uri = urlparse(uri) return Transporter(uri).download(f) def upload(f, uri): return Transporter(uri).upload(f) def transport(source, destination): f = download(source) return upload(destination, f)
Remove beta. from email domain
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart DOMAIN = 'donut.caltech.edu' def send_email(to, text, subject, use_prefix=True, group=None, poster='', richtext=''): """ Sends an email to a user. Expects 'to' to be a comma separated string of emails, and for 'msg' and 'subject' to be strings. If group is not none, the email is sent to a newsgroup and the to emails are hidden. """ if richtext: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text, 'plain')) msg.attach(MIMEText(richtext, 'html')) else: msg = MIMEText(text) if use_prefix and '[ASCIT Donut]' not in subject: subject = '[ASCIT Donut] ' + subject msg['Subject'] = subject msg['From'] = f'{poster} <auto@{DOMAIN}>' if group: msg['To'] = group.lower().replace(' ', '_') else: msg['To'] = to with smtplib.SMTP('localhost') as s: s.sendmail('auto@' + DOMAIN, to, msg.as_string())
import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart DOMAIN = "beta.donut.caltech.edu" def send_email(to, text, subject, use_prefix=True, group=None, poster='', richtext=''): """ Sends an email to a user. Expects 'to' to be a comma separated string of emails, and for 'msg' and 'subject' to be strings. If group is not none, the email is sent to a newsgroup and the to emails are hidden. """ if richtext: msg = MIMEMultipart('alternative') msg.attach(MIMEText(text, 'plain')) msg.attach(MIMEText(richtext, 'html')) else: msg = MIMEText(text) if use_prefix and '[ASCIT Donut]' not in subject: subject = '[ASCIT Donut] ' + subject msg['Subject'] = subject msg['From'] = f'{poster} <auto@{DOMAIN}>' if group: msg['To'] = group.lower().replace(' ', '_') else: msg['To'] = to with smtplib.SMTP('localhost') as s: s.sendmail('auto@' + DOMAIN, to, msg.as_string())
Hide starting dots when n/a
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dots from './Dots'; import StartingDots from './StartingDots'; import dotSelector from '../utils/dotSelector'; import { capitalizeFirstLetter } from '../utils/stringUtils'; class Trait extends Component { static propTypes = { name: PropTypes.string.isRequired, displayName: PropTypes.string, maxDots: PropTypes.number.isRequired, availableStartingDots: PropTypes.arrayOf( PropTypes.shape({ dots: PropTypes.number.isRequired, count: PropTypes.number.isRequired }) ).isRequired, traitState: PropTypes.object.isRequired, onStartingDotsChange: PropTypes.func.isRequired }; handleStartingDotsChange = e => { const startingDots = parseInt(e.target.value, 10); this.props.onStartingDotsChange(this.props.name, startingDots); }; render() { const { name, displayName = capitalizeFirstLetter(name), maxDots, availableStartingDots, traitState } = this.props; return ( <div> {displayName} <Dots level={dotSelector(traitState)} max={maxDots} /> {availableStartingDots.length > 0 && ( <StartingDots available={availableStartingDots} value={traitState.startingDots} onChange={this.handleStartingDotsChange} /> )} </div> ); } } export default Trait;
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Dots from './Dots'; import StartingDots from './StartingDots'; import dotSelector from '../utils/dotSelector'; import { capitalizeFirstLetter } from '../utils/stringUtils'; class Trait extends Component { static propTypes = { name: PropTypes.string.isRequired, displayName: PropTypes.string, maxDots: PropTypes.number.isRequired, availableStartingDots: PropTypes.arrayOf( PropTypes.shape({ dots: PropTypes.number.isRequired, count: PropTypes.number.isRequired }) ).isRequired, traitState: PropTypes.object.isRequired, onStartingDotsChange: PropTypes.func.isRequired }; handleStartingDotsChange = e => { const startingDots = parseInt(e.target.value, 10); this.props.onStartingDotsChange(this.props.name, startingDots); }; render() { const { name, displayName = capitalizeFirstLetter(name), maxDots, availableStartingDots, traitState } = this.props; return ( <div> {displayName} <Dots level={dotSelector(traitState)} max={maxDots} /> <StartingDots available={availableStartingDots} value={traitState.startingDots} onChange={this.handleStartingDotsChange} /> </div> ); } } export default Trait;
Fix password field name on administration page.
<?php /** @var array $roles */ return [ 'elements' => [ 'name' => [ 'text', [ 'label' => __('Display Name'), 'class' => 'half-width', 'label_class' => 'mb-2', ], ], 'email' => [ 'email', [ 'label' => __('E-mail Address'), 'required' => true, 'autocomplete' => 'new-password', 'label_class' => 'mb-2', 'form_group_class' => 'mt-3', ], ], 'new_password' => [ 'password', [ 'label' => __('Reset Password'), 'description' => __('Leave blank to use the current password.'), 'autocomplete' => 'off', 'required' => false, 'label_class' => 'mb-2', 'form_group_class' => 'mt-3', ], ], 'roles' => [ 'multiCheckbox', [ 'label' => __('Roles'), 'options' => $roles, 'form_group_class' => 'mt-3', ], ], 'submit' => [ 'submit', [ 'type' => 'submit', 'label' => __('Save Changes'), 'class' => 'btn btn-lg btn-primary', 'form_group_class' => 'mt-3', ], ], ], ];
<?php /** @var array $roles */ return [ 'elements' => [ 'name' => [ 'text', [ 'label' => __('Display Name'), 'class' => 'half-width', 'label_class' => 'mb-2', ] ], 'email' => [ 'email', [ 'label' => __('E-mail Address'), 'required' => true, 'autocomplete' => 'new-password', 'label_class' => 'mb-2', 'form_group_class' => 'mt-3', ] ], 'auth_password' => [ 'password', [ 'label' => __('Reset Password'), 'description' => __('Leave blank to use the current password.'), 'autocomplete' => 'off', 'required' => false, 'label_class' => 'mb-2', 'form_group_class' => 'mt-3', ] ], 'roles' => [ 'multiCheckbox', [ 'label' => __('Roles'), 'options' => $roles, 'form_group_class' => 'mt-3', ] ], 'submit' => [ 'submit', [ 'type' => 'submit', 'label' => __('Save Changes'), 'class' => 'btn btn-lg btn-primary', 'form_group_class' => 'mt-3', ] ], ], ];
BB-2188: Add posibility to use parameters in data providers - fixed old-style data-providers after master backmerge
<?php namespace Oro\Component\Layout\Extension\Theme\DataProvider; use Oro\Component\Layout\Extension\Theme\Model\Theme; use Oro\Component\Layout\Extension\Theme\Model\ThemeManager; class ThemeProvider { /** @var ThemeManager */ protected $themeManager; /** @var Theme[] */ protected $themes = []; /** * @param ThemeManager $themeManager */ public function __construct(ThemeManager $themeManager) { $this->themeManager = $themeManager; } /** * @param string $themeName * * @return string */ public function getIcon($themeName) { return $this->getTheme($themeName)->getIcon(); } /** * @param string $themeName * * @return string|null */ public function getStylesOutput($themeName) { $assets = $this->getTheme($themeName)->getConfigByKey('assets'); if ($assets && array_key_exists('styles', $assets)) { return array_key_exists('output', $assets['styles']) ? $assets['styles']['output'] : null; } return null; } /** * @param string $themeName * * @return Theme */ private function getTheme($themeName) { if (!array_key_exists($themeName, $this->themes)) { $this->themes[$themeName] = $this->themeManager->getTheme($themeName); } return $this->themes[$themeName]; } }
<?php namespace Oro\Component\Layout\Extension\Theme\DataProvider; use Oro\Component\Layout\Extension\Theme\Model\Theme; use Oro\Component\Layout\Extension\Theme\Model\ThemeManager; class ThemeProvider { /** @var ThemeManager */ protected $themeManager; /** @var Theme[] */ protected $themes = []; /** * @param ThemeManager $themeManager */ public function __construct(ThemeManager $themeManager) { $this->themeManager = $themeManager; } /** * @param string $themeName * * @return string */ public function getIcon($themeName) { return $this->getTheme($themeName)->getIcon(); } /** * @param string $themeName * * @return string|null */ public function getStylesOutput($themeName) { $assets = $this->getTheme($themeName)->getDataByKey('assets'); if ($assets && array_key_exists('styles', $assets)) { return array_key_exists('output', $assets['styles']) ? $assets['styles']['output'] : null; } return null; } /** * @param string $themeName * * @return Theme */ private function getTheme($themeName) { if (!array_key_exists($themeName, $this->themes)) { $this->themes[$themeName] = $this->themeManager->getTheme($themeName); } return $this->themes[$themeName]; } }
Use previous commit as reference point for updates
import binascii import git import sys import os import logging logger = logging.getLogger('root') __match__ = r"!update|!reload" def on_message(bot, channel, user, message): requires_reload = message == '!reload' if message == '!update': local = git.Repo(os.getcwd()) origin = git.remote.Remote(local, 'origin') prev_commit = local.heads[0].commit logger.info("Updating from origin repository") for pull_info in origin.pull(): if prev_commit == pull_info.commit: bot.send_text(channel, "`{}` is already up-to-date!".format( bot.name)) break requires_reload = True commit_hash = binascii.hexlify(pull_info.commit.binsha).decode() commit_message = pull_info.commit.message.strip() bot.send_text(channel, "*Fast-forwarding* to `{}`".format( commit_hash)) logger.debug("Fast-forwarding to {}".format(commit_hash)) bot.send_text(channel, "*Latest commit*: `{}`".format( commit_message)) logger.debug("Latest commit: {}".format(commit_message)) if requires_reload: bot.send_text(channel, "_Reloading...see you on the other side!_") python = sys.executable os.execl(python, python, *sys.argv)
import binascii import git import sys import os import logging logger = logging.getLogger('root') __match__ = r"!update|!reload" def on_message(bot, channel, user, message): requires_reload = message == '!reload' if message == '!update': local = git.Repo(os.getcwd()) origin = git.remote.Remote(local, 'origin') head = local.heads[0] logger.info("Updating from origin repository") for pull_info in origin.pull(): if head.commit == pull_info.commit: bot.send_text(channel, "`{}` is already up-to-date!".format( bot.name)) break requires_reload = True commit_hash = binascii.hexlify(pull_info.commit.binsha).decode() commit_message = pull_info.commit.message.strip() bot.send_text(channel, "*Fast-forwarding* to `{}`".format( commit_hash)) logger.debug("Fast-forwarding to {}".format(commit_hash)) bot.send_text(channel, "*Latest commit*: `{}`".format( commit_message)) logger.debug("Latest commit: {}".format(commit_message)) if requires_reload: bot.send_text(channel, "_Reloading...see you on the other side!_") python = sys.executable os.execl(python, python, *sys.argv)
Update the driving time periodically
(function(N) { N.Map = function(opts) { self = this; self.directionsService = new google.maps.DirectionsService(); self.directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { center: new google.maps.LatLng(39.875, -75.238), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"),mapOptions), traffic = new google.maps.TrafficLayer(); traffic.setMap(map); self.directionsDisplay.setMap(map); // Update the travel times ever minute setInterval($.proxy(self.calculateRoute,self), 60 * 1000); }; N.Map.prototype.calculateRoute = function() { var self = this, start = $('#addr').val(), end = "Philadelphia International Airport", request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; self.directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { self.directionsDisplay.setDirections(result); self.trigger('route-time-update', result.routes[0].legs[0]); } }); }; _.extend(N.Map.prototype, Backbone.Events); }(this));
(function(N) { N.Map = function(opts) { self = this; self.directionsService = new google.maps.DirectionsService(); self.directionsDisplay = new google.maps.DirectionsRenderer(); var mapOptions = { center: new google.maps.LatLng(39.875, -75.238), zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map"),mapOptions), traffic = new google.maps.TrafficLayer(); traffic.setMap(map); self.directionsDisplay.setMap(map); // Update the travel times ever minute setInterval(self.calculateRoute, 60 * 1000); }; N.Map.prototype.calculateRoute = function() { var self = this, start = $('#addr').val(), end = "Philadelphia International Airport", request = { origin: start, destination: end, travelMode: google.maps.TravelMode.DRIVING }; self.directionsService.route(request, function(result, status) { if (status == google.maps.DirectionsStatus.OK) { self.directionsDisplay.setDirections(result); self.trigger('route-time-update', result.routes[0].legs[0]); } }); }; _.extend(N.Map.prototype, Backbone.Events); }(this));
Verify that recent list is cleared when language is changed
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import nose.tools as nose import yv_suggest.set_pref as yvs import context_managers as ctx def test_set_language(): """should set preferred language""" with ctx.preserve_prefs() as prefs: with ctx.preserve_recent_refs(): yvs.shared.update_recent_refs(['8/mat.5']) languages = yvs.shared.get_languages() for language in languages: if language['id'] != prefs['language']: new_language = language['id'] break yvs.main('language:{}'.format(new_language)) prefs = yvs.shared.get_prefs() bible = yvs.shared.get_bible_data(prefs['language']) nose.assert_equal(prefs['language'], new_language) nose.assert_equal(prefs['version'], bible['default_version']) nose.assert_equal(len(yvs.shared.get_recent_refs()), 0) def test_set_version(): """should set preferred version""" with ctx.preserve_prefs() as prefs: bible = yvs.shared.get_bible_data(prefs['language']) versions = bible['versions'] for version in versions: if version['id'] != prefs['language']: new_version = version['id'] break yvs.main('version:{}'.format(new_version)) prefs = yvs.shared.get_prefs() nose.assert_equal(prefs['version'], new_version)
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import nose.tools as nose import yv_suggest.set_pref as yvs import context_managers as ctx def test_set_language(): """should set preferred language""" with ctx.preserve_prefs() as prefs: with ctx.preserve_recent_refs() as recent_refs: languages = yvs.shared.get_languages() for language in languages: if language['id'] != prefs['language']: new_language = language['id'] break yvs.main('language:{}'.format(new_language)) # Check if new values have been saved to preferences prefs = yvs.shared.get_prefs() bible = yvs.shared.get_bible_data(prefs['language']) nose.assert_equal(prefs['language'], new_language) nose.assert_equal(prefs['version'], bible['default_version']) def test_set_version(): """should set preferred version""" with ctx.preserve_prefs() as prefs: bible = yvs.shared.get_bible_data(prefs['language']) versions = bible['versions'] for version in versions: if version['id'] != prefs['language']: new_version = version['id'] break yvs.main('version:{}'.format(new_version)) # Check if new values have been saved to preferences prefs = yvs.shared.get_prefs() nose.assert_equal(prefs['version'], new_version)
Use initialState in Modal reducer spec
import reducer from './'; describe('Modal reducer', () => { let initialState; let state; let actionType; let payload; const callReducer = () => reducer(state, { type: actionType, payload }); beforeEach(() => { initialState = { isOpen: false, modalName: '', modalOptions: {} }; }); it('returns initial state', () => { expect(callReducer()).toEqual(initialState); }); context('when state is present', () => { beforeEach(() => { state = initialState; payload = { name: 'Awesome Modal', someOption: 'Some option value' }; }); describe('OPEN_MODAL', () => { beforeEach(() => { actionType = 'OPEN_MODAL'; }); it('returns new state', () => { expect(callReducer()).toEqual({ isOpen: true, modalName: 'Awesome Modal', modalOptions: { someOption: 'Some option value' } }); }); }); describe('CLOSE_MODAL', () => { beforeEach(() => { actionType = 'CLOSE_MODAL'; state = { isOpen: true, modalName: 'Awesome Modal', modalOptions: { someOption: 'Some option value' } }; }); it('returns initial state', () => { expect(callReducer()).toEqual(initialState); }); }); }); });
import reducer from './'; describe('Modal reducer', () => { let initialState; let state; let actionType; let payload; const callReducer = () => reducer(state, { type: actionType, payload }); beforeEach(() => { initialState = { isOpen: false, modalName: '', modalOptions: {} }; }); it('returns initial state', () => { expect(callReducer()).toEqual(initialState); }); context('when state is present', () => { beforeEach(() => { state = initialState; payload = { name: 'Awesome Modal', someOption: 'Some option value' }; }); describe('OPEN_MODAL', () => { beforeEach(() => { actionType = 'OPEN_MODAL'; }); it('returns new state', () => { expect(callReducer()).toEqual({ isOpen: true, modalName: 'Awesome Modal', modalOptions: { someOption: 'Some option value' } }); }); }); describe('CLOSE_MODAL', () => { beforeEach(() => { actionType = 'CLOSE_MODAL'; state = { isOpen: true, modalName: 'Awesome Modal', modalOptions: { someOption: 'Some option value' } }; }); it('returns initial state', () => { expect(callReducer()).toEqual({ isOpen: false, modalName: '', modalOptions: {} }); }); }); }); });
Change from `preLoaders` to `postLoaders`
var _ = require('lodash'), path = require('path'), webpackConfig = require('./webpack.config.js'); _.merge(webpackConfig, { devtool: 'inline-source-map', module: { postLoaders: [ { test: /\.(js|jsx)?$/, include: path.resolve('src/'), loader: 'babel-istanbul-instrumenter' } ] } }); module.exports = function(config) { config.set({ frameworks: ['jasmine'], browsers: ['PhantomJS'], plugins: [ 'karma-jasmine', 'karma-phantomjs-launcher', 'karma-sourcemap-loader', require('karma-webpack') ], reporters: ['progress'], coverageReporter: { type : 'lcov', dir: 'coverage/' }, preprocessors: { 'webpack.tests.js': [ 'webpack', 'sourcemap' ] }, singleRun: false, webpack: webpackConfig, webpackServer: { watchOptions: { aggregateTimeout: 500, poll: 1000 }, stats: { colors: true }, noInfo: true }, files: [ './node_modules/phantomjs-polyfill/bind-polyfill.js', 'webpack.tests.js' ] }); };
var _ = require('lodash'), path = require('path'), webpackConfig = require('./webpack.config.js'); _.merge(webpackConfig, { devtool: 'inline-source-map', module: { preLoaders: [ { test: /\.(js|jsx)?$/, include: path.resolve('src/'), loader: 'babel-istanbul-instrumenter' } ] } }); module.exports = function(config) { config.set({ frameworks: ['jasmine'], browsers: ['PhantomJS'], plugins: [ 'karma-coveralls', 'karma-coverage', 'karma-jasmine', 'karma-phantomjs-launcher', 'karma-sourcemap-loader', require('karma-webpack') ], reporters: ['progress', 'coverage', 'coveralls'], coverageReporter: { type : 'lcov', dir: 'coverage/' }, preprocessors: { 'webpack.tests.js': [ 'webpack', 'sourcemap' ] }, singleRun: false, webpack: webpackConfig, webpackServer: { watchOptions: { aggregateTimeout: 500, poll: 1000 }, stats: { colors: true }, noInfo: true }, files: [ './node_modules/phantomjs-polyfill/bind-polyfill.js', 'webpack.tests.js' ] }); };
Swap order of clean calls
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): super(AddAPIForm, self).clean() self._clean() return self.cleaned_data def _clean(self): """Check the access mask and characters of the supplied keypair. """ key_id = self.cleaned_data.get('key_id') v_code = self.cleaned_data.get('v_code') if not (key_id and v_code): return api = evelink.api.API(api_key=(key_id, v_code)) account = evelink.account.Account(api) try: key_info = account.key_info().result except evelink.api.APIError as error: self.add_error(None, error.message) return if key_info['type'] != 'account': self.add_error(None, 'The API key should select Character: All') if key_info['access_mask'] != 4294967295: self.add_error(None, 'The API key should have full access') if key_info['expire_ts']: self.add_error(None, 'The API key should have no expiry checked')
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): self._clean() return super(AddAPIForm, self).clean() def _clean(self): """Check the access mask and characters of the supplied keypair. """ key_id = self.cleaned_data.get('key_id') v_code = self.cleaned_data.get('v_code') if not (key_id and v_code): return api = evelink.api.API(api_key=(key_id, v_code)) account = evelink.account.Account(api) try: key_info = account.key_info().result except evelink.api.APIError as error: self.add_error(None, error.message) return if key_info['type'] != 'account': self.add_error(None, 'The API key should select Character: All') if key_info['access_mask'] != 4294967295: self.add_error(None, 'The API key should have full access') if key_info['expire_ts']: self.add_error(None, 'The API key should have no expiry checked')
Use input param key instead of using HEADER field
from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, key, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } if track_psms: if not new: peptide['psms'] = allpeps[key]['psms'] peptide['psms'].append('{0}_{1}'.format(psm[fncol], psm[psmtsvdata.HEADER_SCANNR])) allpeps[key] = peptide def evaluate_peptide(peptides, psm, key, higherbetter, scorecol, fncol=None, track_psms=True): try: existing_score = peptides[key]['score'] except KeyError: add_peptide(peptides, psm, key, scorecol, fncol, True, track_psms) else: if higherbetter and psm[scorecol] > existing_score: add_peptide(peptides, psm, key, scorecol, fncol, track_psms=track_psms) elif not higherbetter and psm[scorecol] < existing_score: add_peptide(peptides, psm, key, scorecol, fncol, track_psms=track_psms) return peptides
from app.dataformats import peptable as peptabledata from app.dataformats import mzidtsv as psmtsvdata def add_peptide(allpeps, psm, scorecol=False, fncol=None, new=False, track_psms=True): peptide = {'score': psm[scorecol], 'line': psm, 'psms': [] } if track_psms: if not new: peptide['psms'] = allpeps[psm[peptabledata.HEADER_PEPTIDE]]['psms'] peptide['psms'].append('{0}_{1}'.format(psm[fncol], psm[psmtsvdata.HEADER_SCANNR])) allpeps[psm[peptabledata.HEADER_PEPTIDE]] = peptide def evaluate_peptide(peptides, psm, key, higherbetter, scorecol, fncol=None, track_psms=True): try: existing_score = peptides[key]['score'] except KeyError: add_peptide(peptides, psm, scorecol, fncol, True, track_psms) else: if higherbetter and psm[scorecol] > existing_score: add_peptide(peptides, psm, scorecol, fncol, track_psms=track_psms) elif not higherbetter and psm[scorecol] < existing_score: add_peptide(peptides, psm, scorecol, fncol, track_psms=track_psms) return peptides
Enable .map extension in CompressionPlugin to ship compressed source maps as well
const TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const safePostCssParser = require('postcss-safe-parser') const Base = require('./base') module.exports = class extends Base { constructor() { super() this.plugins.append( 'Compression', new CompressionPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', cache: true, test: /\.(js|css|html|json|ico|svg|eot|otf|ttf|map)$/ }) ) this.plugins.append( 'OptimizeCSSAssets', new OptimizeCSSAssetsPlugin({ parser: safePostCssParser, map: { inline: false, annotation: true } }) ) this.config.merge({ devtool: 'source-map', stats: 'normal', bail: true, optimization: { minimizer: [ new TerserPlugin({ parallel: true, cache: true, sourceMap: true, terserOptions: { parse: { // Let terser parse ecma 8 code but always output // ES5 compliant code for older browsers ecma: 8 }, compress: { ecma: 5, warnings: false, comparisons: false }, mangle: { safari10: true }, output: { ecma: 5, comments: false, ascii_only: true } } }) ] } }) } }
const TerserPlugin = require('terser-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin') const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin') const safePostCssParser = require('postcss-safe-parser') const Base = require('./base') module.exports = class extends Base { constructor() { super() this.plugins.append( 'Compression', new CompressionPlugin({ filename: '[path].gz[query]', algorithm: 'gzip', cache: true, test: /\.(js|css|html|json|ico|svg|eot|otf|ttf)$/ }) ) this.plugins.append( 'OptimizeCSSAssets', new OptimizeCSSAssetsPlugin({ parser: safePostCssParser, map: { inline: false, annotation: true } }) ) this.config.merge({ devtool: 'source-map', stats: 'normal', bail: true, optimization: { minimizer: [ new TerserPlugin({ parallel: true, cache: true, sourceMap: true, terserOptions: { parse: { // Let terser parse ecma 8 code but always output // ES5 compliant code for older browsers ecma: 8 }, compress: { ecma: 5, warnings: false, comparisons: false }, mangle: { safari10: true }, output: { ecma: 5, comments: false, ascii_only: true } } }) ] } }) } }
Make use of jquery no conflict for stripe JS
Stripe.setPublishableKey('$PublishKey'); jQuery.noConflict(); var payment_form_id = '#$FormName'; (function($) { var payment_form = $(payment_form_id); payment_form.bind( "submit", function(event) { // Disable the submit button to prevent repeated clicks: payment_form .find('.submit') .prop('disabled', true); // Request a token from Stripe: Stripe.card.createToken(payment_form, stripeResponseHandler); // Prevent the form from being submitted: return false; } ); function stripeResponseHandler(status, response) { // Grab the form: var payment_form = $(payment_form_id); if (response.error) { // Problem! // Show the errors on the form: payment_form .find(payment_form_id + '_error') .text(response.error.message) .show(); payment_form .find('.submit') .prop('disabled', false); } else { // Get the token ID: var token = response.id; // Insert the token ID into the form so it gets submitted to the server: payment_form .find(payment_form_id + "_StripeToken") .val(token); // Submit the form: payment_form .get(0) .submit(); } }; }(jQuery));
Stripe.setPublishableKey('$PublishKey'); var payment_form_id = '#$FormName'; $(function() { var payment_form = $(payment_form_id); payment_form.bind( "submit", function(event) { // Disable the submit button to prevent repeated clicks: payment_form .find('.submit') .prop('disabled', true); // Request a token from Stripe: Stripe.card.createToken(payment_form, stripeResponseHandler); // Prevent the form from being submitted: return false; } ); function stripeResponseHandler(status, response) { // Grab the form: var payment_form = $(payment_form_id); if (response.error) { // Problem! // Show the errors on the form: payment_form .find(payment_form_id + '_error') .text(response.error.message) .show(); payment_form .find('.submit') .prop('disabled', false); } else { // Get the token ID: var token = response.id; // Insert the token ID into the form so it gets submitted to the server: payment_form .find(payment_form_id + "_StripeToken") .val(token); // Submit the form: payment_form .get(0) .submit(); } }; });
Clean up implementation of TimeModifierTemplatePlugin No need to use the DateUtil here. `getDateTimeByTimestamp()` is trivial, localization already happens via `IntlDateFormatter` and the `c` format is meant for technical consumption, thus no need to run this via `DateUtil`’s localization and TZ logic.
<?php namespace wcf\system\template\plugin; use wcf\system\template\TemplateEngine; use wcf\system\WCF; /** * Template modifier plugin which formats a unix timestamp. * Default date format contains year, month, day, hour and minute. * * Usage: * {$timestamp|time} * {"132845333"|time} * * @author Alexander Ebert, Marcel Werk * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Template\Plugin */ class TimeModifierTemplatePlugin implements IModifierTemplatePlugin { /** * @inheritDoc */ public function execute($tagArgs, TemplateEngine $tplObj) { $timestamp = \intval($tagArgs[0]); $dateTime = new \DateTimeImmutable('@' . $timestamp); $isFutureDate = $dateTime->getTimestamp() > TIME_NOW; $dateAndTime = \IntlDateFormatter::create( WCF::getLanguage()->getLocale(), \IntlDateFormatter::LONG, \IntlDateFormatter::SHORT, WCF::getUser()->getTimeZone() )->format($dateTime); return \sprintf( '<woltlab-core-date-time date="%s"%s>%s</woltlab-core-date-time>', $dateTime->format('c'), $isFutureDate ? ' static' : '', $dateAndTime ); } }
<?php namespace wcf\system\template\plugin; use wcf\system\template\TemplateEngine; use wcf\system\WCF; use wcf\util\DateUtil; /** * Template modifier plugin which formats a unix timestamp. * Default date format contains year, month, day, hour and minute. * * Usage: * {$timestamp|time} * {"132845333"|time} * * @author Alexander Ebert, Marcel Werk * @copyright 2001-2022 WoltLab GmbH * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php> * @package WoltLabSuite\Core\System\Template\Plugin */ class TimeModifierTemplatePlugin implements IModifierTemplatePlugin { /** * @inheritDoc */ public function execute($tagArgs, TemplateEngine $tplObj) { $timestamp = \intval($tagArgs[0]); $dateTimeObject = DateUtil::getDateTimeByTimestamp($timestamp); $isFutureDate = ($timestamp > TIME_NOW); $dateAndTime = \IntlDateFormatter::create( WCF::getLanguage()->getLocale(), \IntlDateFormatter::LONG, \IntlDateFormatter::SHORT, WCF::getUser()->getTimeZone() )->format($dateTimeObject); return \sprintf( '<woltlab-core-date-time date="%s"%s>%s</woltlab-core-date-time>', DateUtil::format($dateTimeObject, 'c'), $isFutureDate ? ' static' : '', $dateAndTime ); } }
Clear warnings and errors when type checking passes
from app.questionnaire_state.item import Item class Answer(Item): def __init__(self, id): super().__init__(id=id) # typed value self.value = None # actual user input self.input = None def update_state(self, user_input, schema_item): if self.id in user_input.keys(): self.input = user_input[self.id] if schema_item: try: # Do we have the item or it's containing block? if schema_item.id != self.id: schema_item = schema_item.questionnaire.get_item_by_id(self.id) # Mandatory check if self.input: self.value = schema_item.get_typed_value(user_input) self.is_valid = True self.errors = None self.warnings = None elif schema_item.mandatory: self.errors = [] self.errors.append(schema_item.questionnaire.get_error_message('MANDATORY', schema_item.id)) self.is_valid = False except Exception as e: self.value = None # @TODO: Need to look again at this interface when we come to warnings self.errors = [] self.errors.append(schema_item.questionnaire.get_error_message(str(e), schema_item.id)) self.is_valid = False def get_answers(self): return [self]
from app.questionnaire_state.item import Item class Answer(Item): def __init__(self, id): super().__init__(id=id) # typed value self.value = None # actual user input self.input = None def update_state(self, user_input, schema_item): if self.id in user_input.keys(): self.input = user_input[self.id] if schema_item: try: # Do we have the item or it's containing block? if schema_item.id != self.id: schema_item = schema_item.questionnaire.get_item_by_id(self.id) # Mandatory check if self.input: self.value = schema_item.get_typed_value(user_input) self.is_valid = True elif schema_item.mandatory: self.errors = [] self.errors.append(schema_item.questionnaire.get_error_message('MANDATORY', schema_item.id)) self.is_valid = False except Exception as e: self.value = None # @TODO: Need to look again at this interface when we come to warnings self.errors = [] self.errors.append(schema_item.questionnaire.get_error_message(str(e), schema_item.id)) self.is_valid = False def get_answers(self): return [self]
Update comments in message repo remote
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function() { // TODO: need to pull this out different source (i.e. Metadata) var uri = '/Glimpse/MessageHistory'; request .get(uri) .set('Accept', 'application/json') .end(function(err, res){ // this is done because we want to delay the response if (!FAKE_SERVER) { if (res.ok) { glimpse.emit('data.message.summary.found.remote', res.body); } else { console.log('ERROR: Error reaching server for summary request') } } }); }, triggerGetDetailsFor: function(requestId) { // TODO: need to pull this out different source (i.e. Metadata) var uri = '/Glimpse/MessageDetail/' + requestId; request .get(uri) .set('Accept', 'application/json') .end(function(err, res){ // this is done because we want to delay the response if (!FAKE_SERVER) { if (res.ok) { glimpse.emit('data.message.summary.found.remote', res.body); } else { console.log('ERROR: Error reaching server for summary request') } } }); } };
'use strict'; var request = require('superagent'); var glimpse = require('glimpse'); module.exports = { triggerGetLastestSummaries: function() { // TODO: need to pull this out different source var uri = '/Glimpse/MessageHistory'; request //TODO: this will probably change in time to the below //.query({ latest: true }) .get(uri) .set('Accept', 'application/json') .end(function(err, res){ // this is done because we want to delay the response if (!FAKE_SERVER) { if (res.ok) { glimpse.emit('data.message.summary.found.remote', res.body); } else { console.log('ERROR: Error reaching server for summary request') } } }); }, triggerGetDetailsFor: function(requestId) { // TODO: need to pull this out different source var uri = '/Glimpse/MessageDetail/' + requestId; request .get(uri) //TODO: this will probably change in time to the below //.query({ context: requestId }) .set('Accept', 'application/json') .end(function(err, res){ // this is done because we want to delay the response if (!FAKE_SERVER) { if (res.ok) { glimpse.emit('data.message.summary.found.remote', res.body); } else { console.log('ERROR: Error reaching server for summary request') } } }); } };
Use any_endpoint on invalid id test
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pytest.mark.usefixtures('verify_mock_vuforia') class TestInvalidGivenID: """ Tests for giving an invalid ID to endpoints which require a target ID to be given. """ def test_not_real_id( self, vuforia_database_keys: VuforiaDatabaseKeys, any_endpoint: TargetAPIEndpoint, target_id: str, ) -> None: """ A `NOT_FOUND` error is returned when an endpoint is given a target ID of a target which does not exist. """ endpoint = any_endpoint if not endpoint.prepared_request.path_url.endswith(target_id): return delete_target( vuforia_database_keys=vuforia_database_keys, target_id=target_id, ) session = requests.Session() response = session.send( # type: ignore request=endpoint.prepared_request, ) assert_vws_failure( response=response, status_code=codes.NOT_FOUND, result_code=ResultCodes.UNKNOWN_TARGET, )
""" Tests for passing invalid endpoints which require a target ID to be given. """ import pytest import requests from requests import codes from mock_vws._constants import ResultCodes from tests.mock_vws.utils import ( TargetAPIEndpoint, VuforiaDatabaseKeys, assert_vws_failure, delete_target, ) @pytest.mark.usefixtures('verify_mock_vuforia') class TestInvalidGivenID: """ Tests for giving an invalid ID to endpoints which require a target ID to be given. """ def test_not_real_id( self, vuforia_database_keys: VuforiaDatabaseKeys, endpoint: TargetAPIEndpoint, target_id: str, ) -> None: """ A `NOT_FOUND` error is returned when an endpoint is given a target ID of a target which does not exist. """ if not endpoint.prepared_request.path_url.endswith(target_id): return delete_target( vuforia_database_keys=vuforia_database_keys, target_id=target_id, ) session = requests.Session() response = session.send( # type: ignore request=endpoint.prepared_request, ) assert_vws_failure( response=response, status_code=codes.NOT_FOUND, result_code=ResultCodes.UNKNOWN_TARGET, )
Update vigenereDicitonaryHacker: fixed PEP8 spacing
# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz.""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print('Copying hacked message to clipboard:') print(hackedMessage) pyperclip.copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in lines: word = word.strip() # Remove the newline at the end. decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main()
# Vigenère Cipher Dictionary Hacker # https://www.nostarch.com/crackingcodes/ (BSD Licensed) import detectEnglish, vigenereCipher, pyperclip def main(): ciphertext = """Tzx isnz eccjxkg nfq lol mys bbqq I lxcz.""" hackedMessage = hackVigenereDictionary(ciphertext) if hackedMessage != None: print('Copying hacked message to clipboard:') print(hackedMessage) pyperclip.copy(hackedMessage) else: print('Failed to hack encryption.') def hackVigenereDictionary(ciphertext): fo = open('dictionary.txt') words = fo.readlines() fo.close() for word in lines: word = word.strip() # Remove the newline at the end. decryptedText = vigenereCipher.decryptMessage(word, ciphertext) if detectEnglish.isEnglish(decryptedText, wordPercentage=40): # Check with user to see if the decrypted key has been found: print() print('Possible encryption break:') print('Key ' + str(word) + ': ' + decryptedText[:100]) print() print('Enter D for done, or just press Enter to continue breaking:') response = input('> ') if response.upper().startswith('D'): return decryptedText if __name__ == '__main__': main()
Add print statement to send invite command
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <[email protected]>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() print "Voting email sent to %r" % vote_token.user.email vote_token.token_sent = datetime.datetime.now() vote_token.save()
import datetime from django.core.mail.message import EmailMultiAlternatives from django.core.management.base import BaseCommand from django.template import Context from django.template.loader import get_template from project import settings from voting.models import VoteToken class Command(BaseCommand): def handle(self, *args, **options): voting_enabled = settings.VOTING_ENABLED if not voting_enabled: print 'Voting is disabled' return vote_tokens = VoteToken.objects.filter(token_sent__isnull=True).select_related('user') txt_template = get_template('voting/email/vote_invite.txt') html_template = get_template('voting/email/vote_invite.html') for vote_token in vote_tokens: context = Context({'token': vote_token}) txt = txt_template.render(context) html = html_template.render(context) msg = EmailMultiAlternatives( 'Community voting open', txt, 'WebCamp Zagreb <[email protected]>', [vote_token.user.email], ) msg.attach_alternative(html, "text/html") msg.send() vote_token.token_sent = datetime.datetime.now() vote_token.save()
Update sidebar logic and UI
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Drawer from 'material-ui/Drawer'; import AppBar from 'material-ui/AppBar'; import MenuItem from 'material-ui/MenuItem'; import { isSidebarOpen } from '../../reducers'; import toggleSidebar from '../../actions/sidebar-action'; class Sidebar extends Component { redirect(path) { this.props.history.push(path); } render() { return ( <Drawer docked={false} open={this.props.isOpen} > <AppBar title="Menu" iconClassNameRight="muidocs-icon-navigation-expand-more" onLeftIconButtonTouchTap={this.props.toggleSidebar} /> <MenuItem onClick={() => this.redirect('/')}> Caravanas </MenuItem> <MenuItem onClick={() => this.redirect('/companies')}> Companies </MenuItem> </Drawer> ); } } function mapStateToProps(state) { return { isOpen: isSidebarOpen(state), }; } Sidebar.propTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(connect( mapStateToProps, { toggleSidebar, } )(Sidebar));
import { connect } from 'react-redux'; import { withRouter } from 'react-router-dom'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Drawer from 'material-ui/Drawer'; import AppBar from 'material-ui/AppBar'; import MenuItem from 'material-ui/MenuItem'; import { isSidebarOpen } from '../../reducers'; import toggleSidebar from '../../actions/sidebar-action'; class Sidebar extends Component { redirect(path) { this.props.history.push(path); } render() { return ( <Drawer docked={false} open={this.props.isOpen} > <AppBar title="Caravanas" iconClassNameRight="muidocs-icon-navigation-expand-more" onLeftIconButtonTouchTap={this.props.toggleSidebar} /> <MenuItem onClick={() => this.redirect('/')}> Caravanas </MenuItem> <MenuItem onClick={() => this.redirect('/companies')}> Companies </MenuItem> </Drawer> ); } } function mapStateToProps(state) { return { isOpen: isSidebarOpen(state), }; } Sidebar.propTypes = { history: PropTypes.shape({ push: PropTypes.func.isRequired, }).isRequired, }; export default withRouter(connect( mapStateToProps, { toggleSidebar, } )(Sidebar));
Change method name for archive and add unarchive method
<?php namespace Belvedere\Basecamp\Sections; use Belvedere\Basecamp\Models\Recording; class Recordings extends AbstractSection { /** * Index all recordings. * * @param string $type * @param array $parameters * @param int $page * @return \Illuminate\Support\Collection */ public function index($type, array $parameters = array(), $page = null) { $url = 'projects/recordings.json'; $recordings = $this->client->get($url, [ 'query' => array_merge([ 'type' => $type, 'page' => $page, ], $parameters) ]); return $this->indexResponse($recordings, Recording::class); } /** * Trash a recording. * * @param int $id * @return string */ public function destroy($id) { return $this->client->put( sprintf('buckets/%d/recordings/%d/status/trashed.json', $this->bucket, $id) ); } /** * Archive a recording. * * @param int $id * @return string */ public function archive(int $id) { return $this->client->put( sprintf('buckets/%d/recordings/%d/status/archived.json', $this->bucket, $id) ); } /** * Archive a recording. * * @param int $id * @return string */ public function unarchive(int $id) { return $this->client->put( sprintf('buckets/%d/recordings/%d/status/active.json', $this->bucket, $id) ); } }
<?php namespace Belvedere\Basecamp\Sections; use Belvedere\Basecamp\Models\Recording; class Recordings extends AbstractSection { /** * Index all recordings. * * @param string $type * @param array $parameters * @param int $page * @return \Illuminate\Support\Collection */ public function index($type, array $parameters = array(), $page = null) { $url = 'projects/recordings.json'; $recordings = $this->client->get($url, [ 'query' => array_merge([ 'type' => $type, 'page' => $page, ], $parameters) ]); return $this->indexResponse($recordings, Recording::class); } /** * Trash a recording. * * @param int $id * @return string */ public function destroy($id) { return $this->client->put( sprintf('buckets/%d/recordings/%d/status/trashed.json', $this->bucket, $id) ); } /** * Archived a recording. * * @param int $id * @return string */ public function archived(int $id) { return $this->client->put( sprintf('buckets/%d/recordings/%d/status/archived.json', $this->bucket, $id) ); } }
Add Framework::Pytest to list of classifiers
import re from setuptools import setup with open('pytest_mock.py') as f: m = re.search("version = '(.*)'", f.read()) assert m is not None version = m.group(1) setup( name='pytest-mock', version=version, entry_points={ 'pytest11': ['pytest_mock = pytest_mock'], }, py_modules=['pytest_mock'], platforms='any', install_requires=[ 'pytest>=2.7', ], extras_require={ ':python_version=="2.6" or python_version=="2.7"': ['mock'], }, url='https://github.com/pytest-dev/pytest-mock/', license='LGPL', author='Bruno Oliveira', author_email='[email protected]', description='Thin-wrapper around the mock package for easier use with py.test', long_description=open('README.rst').read(), keywords="pytest mock", classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Testing', ] )
import re from setuptools import setup with open('pytest_mock.py') as f: m = re.search("version = '(.*)'", f.read()) assert m is not None version = m.group(1) setup( name='pytest-mock', version=version, entry_points={ 'pytest11': ['pytest_mock = pytest_mock'], }, py_modules=['pytest_mock'], platforms='any', install_requires=[ 'pytest>=2.7', ], extras_require={ ':python_version=="2.6" or python_version=="2.7"': ['mock'], }, url='https://github.com/pytest-dev/pytest-mock/', license='LGPL', author='Bruno Oliveira', author_email='[email protected]', description='Thin-wrapper around the mock package for easier use with py.test', long_description=open('README.rst').read(), keywords="pytest mock", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Topic :: Software Development :: Testing', ] )
Fix deployer not finding resources
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const assert = require('hoek').assert; class Deployer { constructor(namespace, kubectl) { this.namespace = namespace; this.kubectl = kubectl; } deployResource(path, options) { let requirements = Promise.resolve(); const resource = this.namespace.getResource(path); assert(resource, "Resource not defined"); const dependencies = _.get(resource.value, ["metadata", "annotations", "x-truder.net/dependencies"]); if (dependencies) { requirements = Promise.map(dependencies.split(','), dep => { return this.deployResource(dep, options); }); } return requirements.then(() => { if (options.rollingUpdate && resource.type === 'replicationcontrollers') { return this.kubectl.rollingUpdate(resource.namespace, options.rollingUpdate, resource.value); } return this.kubectl.deploy(resource.namespace, resource.kind, resource.name, resource.value); }).then(() => { if (options.restart && resource.type === 'replicationcontrollers') { return this.kubectl.deleteByLabels(resource.name, 'pod', resource.value.spec.selector); } }); } deploy(include, options) { let resources; if (_.isEmpty(include)) { resources = this.namespace.resources; } else { resources = _.isArray(include) ? include : [include]; } return Promise.mapSeries(resources, path => this.deployResource(path, options)); } } module.exports = Deployer;
'use strict'; const _ = require('lodash'); const Promise = require('bluebird'); const assert = require('hoek').assert; class Deployer { constructor(namespace, kubectl) { this.namespace = namespace; this.kubectl = kubectl; } deployResource(path, options) { let requirements = Promise.resolve(); const resource = this.namespace.getResource(path); assert(resource, "Resource not defined"); const dependencies = _.get(resource.value, ["metadata", "annotations", "x-truder.net/dependencies"]); if (dependencies) { requirements = Promise.map(dependencies.split(','), dep => { return this.deployResource(dep, options); }); } return requirements.then(() => { if (options.rollingUpdate && resource.type === 'replicationcontrollers') { return this.kubectl.rollingUpdate(resource.namespace, options.rollingUpdate, resource.value); } return this.kubectl.deploy(resource.namespace, resource.kind, resource.name, resource.value); }).then(() => { if (options.restart && resource.type === 'replicationcontrollers') { return this.kubectl.deleteByLabels(resource.name, 'pod', resource.value.spec.selector); } }); } deploy(include, options) { let resources; if (_.isEmpty(include)) { resources = _.keys(this.namespace.resources); } else { resources = _.isArray(include) ? include : [include]; } return Promise.mapSeries(resources, path => this.deployResource(path, options)); } } module.exports = Deployer;
Use `npm test' to run test in grunt
'use strict'; module.exports = function(grunt) { var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'update LiveScript source', function () { var done = this.async(); // FIXME: Compile changed file only shell.exec(lsc + ' -c lib'); shell.exec(lsc + ' -c test'); grunt.task.run('test'); done(); }); grunt.registerTask('package_ls', 'update package.ls', function () { var done = this.async(); shell.exec(lsc + ' -cj package.ls'); shell.exec(npm + ' install'); done(); }); grunt.registerTask('test', 'run test', function () { var done = this.async(); shell.exec(npm + ' test'); done(); }); grunt.initConfig({ watch: { livescript_src: { files: ['lib/**/*.ls', 'test/**/*.ls'], tasks: ['livescript_src'] }, package_ls: { files: ['package.ls'], tasks: ['package_ls'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); };
'use strict'; module.exports = function(grunt) { var path = require('path'); var shell = require('shelljs'); var bin = ['node_modules', '.bin'].join(path.sep); var lsc = [bin, 'lsc'].join(path.sep); var mocha = [bin, 'mocha'].join(path.sep); var npm = 'npm'; grunt.registerTask('livescript_src', 'update LiveScript source', function () { var done = this.async(); // FIXME: Compile changed file only shell.exec(lsc + ' -c lib'); shell.exec(lsc + ' -c test'); grunt.task.run('mocha'); done(); }); grunt.registerTask('package_ls', 'update package.ls', function () { var done = this.async(); shell.exec(lsc + ' -cj package.ls'); shell.exec(npm + ' install'); done(); }); grunt.registerTask('mocha', 'run mocha', function () { var done = this.async(); shell.exec(mocha); done(); }); grunt.initConfig({ watch: { livescript_src: { files: ['lib/**/*.ls', 'test/**/*.ls'], tasks: ['livescript_src'] }, package_ls: { files: ['package.ls'], tasks: ['package_ls'] } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.registerTask('default', ['watch']); };
Change to map rather use `FlatList` to avoid press event handling issues
import React, { Component } from 'react'; import { StyleSheet, View } from 'react-native'; import Prediction from './Prediction'; class Predictions extends Component { static defaultProps = { predictions: [] } constructor(props) { super(props); } render() { return ( <View style={style.container}> { this.props.predictions.map(prediction => { return ( <Prediction key={prediction.place_id} prediction={prediction} title={prediction.structured_formatting.main_text} description={prediction.structured_formatting.secondary_text} onPress={this.props.onPressPrediction} /> ); }) } </View> ); } } export const style = StyleSheet.create({ container: { backgroundColor: 'white', }, }); export default Predictions;
import React, { Component } from 'react'; import { StyleSheet, FlatList, View } from 'react-native'; import Prediction from './Prediction'; class Predictions extends Component { constructor(props) { super(props); } render() { return ( <View style={style.container}> <FlatList data={this.props.predictions} keyExtractor={this._keyExtractor} renderItem={this._renderItem} /> </View> ); } _keyExtractor = (prediction) => { return prediction.place_id; } _renderItem = (data) => { return ( <Prediction prediction={data.item} title={data.item.structured_formatting.main_text} description={data.item.structured_formatting.secondary_text} onPress={this.props.onPressPrediction} /> ); } } export const style = StyleSheet.create({ container: { backgroundColor: 'white', }, }); export default Predictions;
Split item search into its own function
<?php namespace Scat; class SearchService { public function __construct() { } public function search($q) { return [ 'items' => $this->searchItems($q), 'products' => $this->searchProducts($q) ]; } public function searchItems($q) { $scanner= new \OE\Lukas\Parser\QueryScanner(); $parser= new \OE\Lukas\Parser\QueryParser($scanner); $parser->readString($q); $query= $parser->parse(); $v= new \Scat\SearchVisitor(); $query->accept($v); $items= \Model::factory('Item')->select('item.*') ->left_outer_join('brand', array('brand.id', '=', 'item.brand')) ->left_outer_join('barcode', array('barcode.item', '=', 'item.id')) ->where_raw($v->where_clause()) ->where_gte('item.active', 1) ->order_by_asc('code') ->find_many(); return $items; } public function searchProducts($q) { return []; } }
<?php namespace Scat; use OE\Lukas\Parser\QueryParser; use OE\Lukas\Visitor\QueryItemPrinter; class SearchService { public function __construct() { } public function search($q) { $scanner= new \OE\Lukas\Parser\QueryScanner(); $parser= new \OE\Lukas\Parser\QueryParser($scanner); $parser->readString($q); $query= $parser->parse(); $v= new \Scat\SearchVisitor(); $query->accept($v); $items= \Model::factory('Item')->select('item.*') ->left_outer_join('brand', array('brand.id', '=', 'item.brand')) ->left_outer_join('barcode', array('barcode.item', '=', 'item.id')) ->where_raw($v->where_clause()) ->where_gte('item.active', 1) ->order_by_asc('code') ->find_many(); return [ 'items' => $items ]; } }
Fix bug with appending new attributes
<?php namespace MageTest\Manager\Attributes\Provider; /** * Trait OverrideAttributes * * @package spec\MageTest\Manager\Attributes\Provider */ trait OverrideAttributes { /** * Overrides previously defined attributes, and optionally adds new * * @param array $attributes * @param bool $appendNew * @return mixed */ public function overrideAttributes(array $attributes, $appendNew = true) { $type = $this->getModelType(); foreach ($this->model[$type]['attributes'] as $key => $value) { if (array_key_exists($key, $attributes)) { $this->model[$type]['attributes'][$key] = $attributes[$key]; } } if ($appendNew) { $this->appendNewAttributes($attributes); } } /** * Append new values to the attributes array * * @param array $attributes */ private function appendNewAttributes(array $attributes) { $type = $this->getModelType(); foreach ($attributes as $key => $value) { if (!array_key_exists($key, $this->model[$type])) { $this->model[$type]['attributes'][$key] = $value; } } } }
<?php namespace MageTest\Manager\Attributes\Provider; /** * Trait OverrideAttributes * * @package spec\MageTest\Manager\Attributes\Provider */ trait OverrideAttributes { /** * Overrides previously defined attributes, and optionally adds new * * @param array $attributes * @param bool $appendNew * @return mixed */ public function overrideAttributes(array $attributes, $appendNew = true) { $type = $this->getModelType(); foreach ($this->model[$type]['attributes'] as $key => $value) { if (array_key_exists($key, $attributes)) { $this->model[$type]['attributes'][$key] = $attributes[$key]; } } if ($appendNew) { $this->appendNewAttributes($attributes); } } /** * Append new values to the attributes array * * @param array $attributes */ private function appendNewAttributes(array $attributes) { $type = $this->getModelType(); foreach ($attributes as $key => $value) { if (!array_key_exists($key, $this->model[$type])) { $this->model[$type][$key] = $value; } } } }
Sort guests in ad form
<?php namespace DinnerBundle\Form; use DinnerBundle\Entity\Guest; use Doctrine\ORM\EntityRepository; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class AdType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('adType') ->add('copy') ->add('note') ->add('sentToPrinter', DateType::class, ['widget' => 'single_text', 'required' => false]) ->add('proofFromPrinter', DateType::class, ['widget' => 'single_text', 'required' => false]) ->add('proofApproved') ->add('guests', EntityType::class, [ 'class' => Guest::class, 'label' => 'This ad is for', 'multiple' => true, 'query_builder' => function (EntityRepository $er) { return $er->createQueryBuilder('g')->orderBy('g.familyName, g.hisName', 'ASC'); }, ]); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'DinnerBundle\Entity\Ad' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'dinnerbundle_ad'; } }
<?php namespace DinnerBundle\Form; use DinnerBundle\Entity\Guest; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class AdType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('adType') ->add('copy') ->add('note') ->add('sentToPrinter', DateType::class, ['widget' => 'single_text', 'required' => false]) ->add('proofFromPrinter', DateType::class, ['widget' => 'single_text', 'required' => false]) ->add('proofApproved') ->add('guests', EntityType::class, ['class' => Guest::class, 'label' => 'This ad is for', 'multiple' => true]); } /** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'DinnerBundle\Entity\Ad' )); } /** * {@inheritdoc} */ public function getBlockPrefix() { return 'dinnerbundle_ad'; } }
Fix fatal error in data processing. The wrong identifier was being used as the key to tell whether a propagandist had been seen before in the dataset, leading to a completely, and incorrectly disconnected graph.
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident) if aoid is None: node_table[ident] = aoid = ObjectId() print bson.json_util.dumps({"_id": aoid, "type": "node", "data": {"twitter_id": ident, "type": "audience", "propaganda_urls_exposed_to": record["propaganda_urls_exposed_to"], "geos": record["geos"], "timestamps_of_propaganda": record["timestamps_of_propaganda"]}}) for p in record["propagandists_followed"]: oid = node_table.get(p) if oid is None: node_table[p] = oid = ObjectId() print bson.json_util.dumps({"_id": oid, "type": "node", "data": {"twitter_id": p, "type": "propagandist"}}) print bson.json_util.dumps({"_id": ObjectId(), "type": "link", "source": aoid, "target": oid, "data": {}}) if __name__ == "__main__": sys.exit(main())
import bson.json_util from bson.objectid import ObjectId import json import sys def main(): node_table = {} while True: line = sys.stdin.readline() if not line: break record = json.loads(line) ident = str(record["twitter_id"]) aoid = node_table.get(ident) if aoid is None: node_table[ident] = aoid = ObjectId() print bson.json_util.dumps({"_id": aoid, "type": "node", "data": {"twitter_id": ident, "type": "audience", "propaganda_urls_exposed_to": record["propaganda_urls_exposed_to"], "geos": record["geos"], "timestamps_of_propaganda": record["timestamps_of_propaganda"]}}) for p in record["propagandists_followed"]: oid = node_table.get(p) if oid is None: node_table[ident] = oid = ObjectId() print bson.json_util.dumps({"_id": oid, "type": "node", "data": {"twitter_id": p, "type": "propagandist"}}) print bson.json_util.dumps({"_id": ObjectId(), "type": "link", "source": aoid, "target": oid, "data": {}}) if __name__ == "__main__": sys.exit(main())
Allow Pro users to specify multiple domains to serve their blog. Specifically for www/non-www setups.
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('www.', '').split('.') if host != 'snipt.net' and host != 'snipt.localhost': if len(host_s) > 2: if host_s[1] == 'snipt': blog_user = ''.join(host_s[:-2]) if '-' in blog_user: request.blog_user = get_object_or_None(User, username__iexact=blog_user) if request.blog_user is None: request.blog_user = get_object_or_404(User, username__iexact=blog_user.replace('-', '_')) else: request.blog_user = get_object_or_404(User, username__iexact=blog_user) if request.blog_user is None: pro_users = User.objects.filter(userprofile__is_pro=True) for pro_user in pro_users: if host in pro_user.profile.blog_domain.split(' '): request.blog_user = pro_user
from django.shortcuts import get_object_or_404 from django.contrib.auth.models import User from annoying.functions import get_object_or_None class BlogMiddleware: def process_request(self, request): request.blog_user = None host = request.META.get('HTTP_HOST', '') host_s = host.replace('www.', '').split('.') if host != 'snipt.net' and host != 'snipt.localhost': if len(host_s) > 2: if host_s[1] == 'snipt': blog_user = ''.join(host_s[:-2]) if '-' in blog_user: request.blog_user = get_object_or_None(User, username__iexact=blog_user) if request.blog_user is None: request.blog_user = get_object_or_404(User, username__iexact=blog_user.replace('-', '_')) else: request.blog_user = get_object_or_404(User, username__iexact=blog_user) if request.blog_user is None: pro_users = User.objects.filter(userprofile__is_pro=True) for pro_user in pro_users: if host == pro_user.profile.blog_domain: request.blog_user = pro_user
Change author and email to the same as atomic-reactor has
#!/usr/bin/python """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import re from setuptools import setup, find_packages data_files = { "share/osbs": [ "inputs/prod.json", "inputs/prod_inner.json", "inputs/simple.json", "inputs/simple_inner.json", ], } def _get_requirements(path): try: with open(path) as f: packages = f.read().splitlines() except (IOError, OSError) as ex: raise RuntimeError("Can't open file with requirements: %s", repr(ex)) return [p.strip() for p in packages if not re.match(r"^\s*#", p)] def _install_requirements(): requirements = _get_requirements('requirements.txt') return requirements setup( name="osbs-client", description='Python module and command line client for OpenShift Build Service', version="0.14", author='Red Hat, Inc.', author_email='[email protected]', url='https://github.com/projectatomic/osbs-client', license="BSD", packages=find_packages(exclude=["tests"]), entry_points={ 'console_scripts': ['osbs=osbs.cli.main:main'], }, install_requires=_install_requirements(), data_files=data_files.items(), )
#!/usr/bin/python """ Copyright (c) 2015 Red Hat, Inc All rights reserved. This software may be modified and distributed under the terms of the BSD license. See the LICENSE file for details. """ import re from setuptools import setup, find_packages data_files = { "share/osbs": [ "inputs/prod.json", "inputs/prod_inner.json", "inputs/simple.json", "inputs/simple_inner.json", ], } def _get_requirements(path): try: with open(path) as f: packages = f.read().splitlines() except (IOError, OSError) as ex: raise RuntimeError("Can't open file with requirements: %s", repr(ex)) return [p.strip() for p in packages if not re.match(r"^\s*#", p)] def _install_requirements(): requirements = _get_requirements('requirements.txt') return requirements setup( name="osbs-client", description='Python module and command line client for OpenShift Build Service', version="0.14", author='Tomas Tomecek', author_email='[email protected]', url='https://github.com/projectatomic/osbs-client', license="BSD", packages=find_packages(exclude=["tests"]), entry_points={ 'console_scripts': ['osbs=osbs.cli.main:main'], }, install_requires=_install_requirements(), data_files=data_files.items(), )
Fix a bug in file_open (os.open does not take keyword argument).
# -*- encoding: utf-8 -*- import os import errno def ensure_intermediate_dir(path): """ Basiclly equivalent to command `mkdir -p` """ try: os.makedirs(os.path.dirname(path)) except OSError, e: if e.errno != errno.EEXIST: raise e def open_file(filename, flag, mode=0777): """ Wrapper of `os.open` which ensure intermediate dirs are created as well. """ try: return os.open(filename, flag, mode) except OSError, e: if e.errno != errno.ENOENT or not (flag & os.O_CREAT): raise e # a directory component not exists ensure_intermediate_dir(filename) # second try return os.open(filename, flag, mode) def link_file(src, dst): """ Wrapper of `os.link` which ensure intermediate dirs are created as well. """ try: return os.link(src, dst) except OSError, e: if e.errno != errno.ENOENT: raise e ensure_intermediate_dir(dst) return os.link(src, dst) def rename_file(old, new): """ Wrapper of `os.rename` which ensure intermediate dirs are created as well. """ try: return os.rename(old, new) except OSError, e: if e.errno != errno.ENOENT: raise e ensure_intermediate_dir(new) return os.rename(old, new)
# -*- encoding: utf-8 -*- import os import errno def ensure_intermediate_dir(path): """ Basiclly equivalent to command `mkdir -p` """ try: os.makedirs(os.path.dirname(path)) except OSError, e: if e.errno != errno.EEXIST: raise e def open_file(filename, flag, mode=0777): """ Wrapper of `os.open` which ensure intermediate dirs are created as well. """ try: return os.open(filename, flag, mode=mode) except OSError, e: if e.errno != errno.ENOENT or not (flag & os.O_CREAT): raise e # a directory component not exists ensure_intermediate_dir(filename) # second try return os.open(filename, flag, mode=mode) def link_file(src, dst): """ Wrapper of `os.link` which ensure intermediate dirs are created as well. """ try: return os.link(src, dst) except OSError, e: if e.errno != errno.ENOENT: raise e ensure_intermediate_dir(dst) return os.link(src, dst) def rename_file(old, new): """ Wrapper of `os.rename` which ensure intermediate dirs are created as well. """ try: return os.rename(old, new) except OSError, e: if e.errno != errno.ENOENT: raise e ensure_intermediate_dir(new) return os.rename(old, new)
Return object, not string from Cordova plugin calls
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = JSON.parse(params.message); try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter'); var ReactNative = require('react-native'); function CordovaPluginAdapter() { this.nativeInterface = ReactNative.NativeModules.CordovaPluginAdapter; this._callbackCount = Math.random(); this._callbacks = {}; this.initCallbackChannel(); }; CordovaPluginAdapter.prototype.exec = function(success, fail, service, action, args) { var callbackId = [service, action, this._callbackCount].join(':'); this._callbacks[callbackId] = { success: success, fail: fail }; this.nativeInterface.exec(service, action, callbackId, JSON.stringify(args)); this._callbackCount++; }; CordovaPluginAdapter.prototype.initCallbackChannel = function() { RCTDeviceEventEmitter.addListener('CordovaWebViewProxy', this.onChannelCallback, this); }; CordovaPluginAdapter.prototype.onChannelCallback = function(params) { if (typeof this._callbacks[params.callbackId] === 'object') { var result = params.message; try { if (params.status === 1) { this._callbacks[params.callbackId].success(result); } else if (params.status === 1) { this._callbacks[params.callbackId].fail(result); } } finally { if (!params.keepCallback) { delete this._callbacks[params.callbackId]; } } } }; module.exports = CordovaPluginAdapter;
Make mutation trigger guarantee a probability
package com.agricraft.agricore.templates; import com.agricraft.agricore.core.AgriCore; import com.google.gson.JsonObject; public class AgriMutationTrigger { private final String id; private final boolean required; private final double guaranteedChance; private final JsonObject parameters; public AgriMutationTrigger() { this.id = "none"; this.required = false; this.guaranteedChance = 0; this.parameters = new JsonObject(); } public AgriMutationTrigger(String id, boolean required, double guaranteedChance, JsonObject parameters) { this.id = id; this.required = required; this.guaranteedChance = guaranteedChance; this.parameters = parameters; } public String getId() { return this.id; } public boolean isRequired() { return this.required; } public double getGuaranteedChance() { return this.guaranteedChance; } public JsonObject getParameters() { return this.parameters; } public boolean validate() { if(!AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters())) { AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters()); return false; } if(this.getGuaranteedChance() < 0 || this.getGuaranteedChance() > 1) { AgriCore.getCoreLogger().info("Invalid Mutation trigger guaranteed probability: {1}, the value must be between 0 and 1 (both inclusive)", this.getId(), this.getParameters()); return false; } return true; } }
package com.agricraft.agricore.templates; import com.agricraft.agricore.core.AgriCore; import com.google.gson.JsonObject; public class AgriMutationTrigger { private final String id; private final boolean required; private final boolean guaranteed; private final JsonObject parameters; public AgriMutationTrigger() { this.id = "none"; this.required = false; this.guaranteed = false; this.parameters = new JsonObject(); } public AgriMutationTrigger(String id, boolean required, boolean guaranteed, JsonObject parameters) { this.id = id; this.required = required; this.guaranteed = guaranteed; this.parameters = parameters; } public String getId() { return this.id; } public boolean isRequired() { return this.required; } public boolean isGuaranteed() { return this.guaranteed; } public JsonObject getParameters() { return this.parameters; } public boolean validate() { boolean valid = AgriCore.getValidator().isValidMutationTrigger(this.getId(), this.getParameters()); if(!valid) { AgriCore.getCoreLogger().info("Invalid Mutation trigger {0}: {1}", this.getId(), this.getParameters()); } return valid; } }
Fix JSON test data parsing
package org.ethereum.jsontestsuite.builder; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.jsontestsuite.Utils; import org.ethereum.jsontestsuite.model.BlockHeaderTck; import java.math.BigInteger; import static org.ethereum.jsontestsuite.Utils.parseData; import static org.ethereum.jsontestsuite.Utils.parseNumericData; public class BlockHeaderBuilder { public static BlockHeader build(BlockHeaderTck headerTck){ BlockHeader header = new BlockHeader( parseData(headerTck.getParentHash()), parseData(headerTck.getUncleHash()), parseData(headerTck.getCoinbase()), parseData(headerTck.getBloom()), parseNumericData(headerTck.getDifficulty()), new BigInteger(1, parseData(headerTck.getNumber())).longValue(), parseData(headerTck.getGasLimit()), new BigInteger(1, parseData(headerTck.getGasUsed())).longValue(), new BigInteger(1, parseData(headerTck.getTimestamp())).longValue(), parseData(headerTck.getExtraData()), parseData(headerTck.getMixHash()), parseData(headerTck.getNonce()) ); header.setReceiptsRoot(parseData(headerTck.getReceiptTrie())); header.setTransactionsRoot(parseData(headerTck.getTransactionsTrie())); header.setStateRoot(parseData(headerTck.getStateRoot())); return header; } }
package org.ethereum.jsontestsuite.builder; import org.ethereum.core.Block; import org.ethereum.core.BlockHeader; import org.ethereum.jsontestsuite.Utils; import org.ethereum.jsontestsuite.model.BlockHeaderTck; import java.math.BigInteger; import static org.ethereum.jsontestsuite.Utils.parseData; import static org.ethereum.jsontestsuite.Utils.parseNumericData; public class BlockHeaderBuilder { public static BlockHeader build(BlockHeaderTck headerTck){ BlockHeader header = new BlockHeader( parseData(headerTck.getParentHash()), parseData(headerTck.getUncleHash()), parseData(headerTck.getCoinbase()), parseData(headerTck.getBloom()), parseNumericData(headerTck.getDifficulty()), new BigInteger(parseData(headerTck.getNumber())).longValue(), parseData(headerTck.getGasLimit()), new BigInteger(parseData(headerTck.getGasUsed())).longValue(), new BigInteger(parseData(headerTck.getTimestamp())).longValue(), parseData(headerTck.getExtraData()), parseData(headerTck.getMixHash()), parseData(headerTck.getNonce()) ); header.setReceiptsRoot(parseData(headerTck.getReceiptTrie())); header.setTransactionsRoot(parseData(headerTck.getTransactionsTrie())); header.setStateRoot(parseData(headerTck.getStateRoot())); return header; } }
Fix variable already defined JSHint error
exports.fixed = function(x, y, r) { var orient = r.split('!')[1]; var ratio = r.split('!')[0].split(':').sort(); var vertical = y > x; var rotate = y > x && orient === 'h' || x > y && orient === 'v'; if ((vertical || rotate) && !(vertical && rotate)) { x = x + y; y = x - y; x = x - y; } var xʹ = x; var yʹ = x * (ratio[1] / ratio[0]); if (yʹ > y || rotate && yʹ > x) { yʹ = y; xʹ = y * (ratio[1] / ratio[0]); if (xʹ > x) { xʹ = x; yʹ = x * (ratio[0] / ratio[1]); } } var Δx = Math.floor((x - xʹ) / 2); var Δy = Math.floor((y - yʹ) / 2); if ((vertical || rotate) && !(vertical && rotate)) { return [ Δy, // crop top left x Δx, // crop top left y y - Δy * 2, // crop width x - Δx * 2 // crop height ]; } else { return [ Δx, // crop top left x Δy, // crop top left y x - Δx * 2, // crop width y - Δy * 2 // crop height ]; } };
exports.fixed = function(x, y, ratio) { var orient = ratio.split('!')[1]; var ratio = ratio.split('!')[0].split(':').sort(); var vertical = y > x; var rotate = y > x && orient === 'h' || x > y && orient === 'v'; if ((vertical || rotate) && !(vertical && rotate)) { x = x + y; y = x - y; x = x - y; } var xʹ = x; var yʹ = x * (ratio[1] / ratio[0]); if (yʹ > y || rotate && yʹ > x) { yʹ = y; xʹ = y * (ratio[1] / ratio[0]); if (xʹ > x) { xʹ = x; yʹ = x * (ratio[0] / ratio[1]); } } var Δx = Math.floor((x - xʹ) / 2); var Δy = Math.floor((y - yʹ) / 2); if ((vertical || rotate) && !(vertical && rotate)) { return [ Δy, // crop top left x Δx, // crop top left y y - Δy * 2, // crop width x - Δx * 2 // crop height ]; } else { return [ Δx, // crop top left x Δy, // crop top left y x - Δx * 2, // crop width y - Δy * 2 // crop height ]; } };
Fix fatal error on pages with nested nodes in header
import React, {PureComponent, PropTypes, createElement} from 'react' import {Link} from 'react-scroll' import {Link as LinkIcon} from '../icons' import {scrollDuration} from '../../constants/animations' const createId = data => { if (Array.isArray(data)) { data = data.map(value => { if (typeof value === 'object') return value.attributes.text return value }).join('') } return data.toLowerCase().replace(/\s/g, '-').replace(/[^-\w]/g, '') } /** * Renders `h*` tags and generates a github like id attribute. */ export default class H extends PureComponent { static propTypes = { sheet: PropTypes.object.isRequired, tag: PropTypes.string.isRequired, children: PropTypes.node.isRequired } onClick() { // We need to set the hash manually because <Link/> will not. // Also we can't use `onSetActive` callback because it doesn't work if // an element is on very bottom so that there is no scroll possible. setTimeout(() => { location.hash = this.to }, scrollDuration) } render() { const { children, tag, sheet: {classes}, ...rest } = this.props const id = createId(children) const content = [ <Link className={classes.headingAnchor} to={id} // Needed for the cursor. href={`#${id}`} smooth duration={scrollDuration} onClick={this.onClick} > <LinkIcon /> </Link>, children ] return createElement(tag, {...rest, id, className: classes.heading}, content) } }
import React, {PureComponent, PropTypes, createElement} from 'react' import {Link} from 'react-scroll' import {Link as LinkIcon} from '../icons' import {scrollDuration} from '../../constants/animations' const createId = str => str.toLowerCase().replace(/\s/g, '-').replace(/[^-\w]/g, '') /** * Renders `h*` tags and generates a github like id attribute. */ export default class H extends PureComponent { static propTypes = { sheet: PropTypes.object.isRequired, tag: PropTypes.string.isRequired, children: PropTypes.node.isRequired } onClick() { // We need to set the hash manually because <Link/> will not. // Also we can't use `onSetActive` callback because it doesn't work if // an element is on very bottom so that there is no scroll possible. setTimeout(() => { location.hash = this.to }, scrollDuration) } render() { const { children, tag, sheet: {classes}, ...rest } = this.props const id = createId(children) const content = [ <Link className={classes.headingAnchor} to={id} // Needed for the cursor. href={`#${id}`} smooth duration={scrollDuration} onClick={this.onClick} > <LinkIcon /> </Link>, children ] return createElement(tag, {...rest, id, className: classes.heading}, content) } }
Return full path if it exists for OSF
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): return self.raw['path'] @property def modified(self): return self.raw.get('modified') @property def size(self): return self.raw.get('size') @property def full_path(self): return self.raw.get('fullPath') @property def content_type(self): return None @property def extra(self): return { key: self.raw[key] for key in ('version', 'downloads', 'fullPath') if key in self.raw } class OsfStorageFolderMetadata(BaseOsfStorageMetadata, metadata.BaseFolderMetadata): @property def name(self): return self.raw['name'] @property def path(self): return self.raw['path'] class OsfStorageRevisionMetadata(BaseOsfStorageMetadata, metadata.BaseFileRevisionMetadata): @property def modified(self): return self.raw['date'] @property def version_identifier(self): return 'version' @property def version(self): return str(self.raw['index']) @property def extra(self): return { 'user': self.raw['user'], 'downloads': self.raw['downloads'], }
from waterbutler.core import metadata class BaseOsfStorageMetadata: @property def provider(self): return 'osfstorage' class OsfStorageFileMetadata(BaseOsfStorageMetadata, metadata.BaseFileMetadata): @property def name(self): return self.raw['name'] @property def path(self): return self.raw['path'] @property def modified(self): return self.raw.get('modified') @property def size(self): return self.raw.get('size') @property def content_type(self): return None @property def extra(self): return { key: self.raw[key] for key in ('version', 'downloads', 'fullPath') if key in self.raw } class OsfStorageFolderMetadata(BaseOsfStorageMetadata, metadata.BaseFolderMetadata): @property def name(self): return self.raw['name'] @property def path(self): return self.raw['path'] class OsfStorageRevisionMetadata(BaseOsfStorageMetadata, metadata.BaseFileRevisionMetadata): @property def modified(self): return self.raw['date'] @property def version_identifier(self): return 'version' @property def version(self): return str(self.raw['index']) @property def extra(self): return { 'user': self.raw['user'], 'downloads': self.raw['downloads'], }
Add optional dependencies for the docs
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='dltk', version='0.1', description='Deep Learning Toolkit for Medical Image Analysis', author='DLTK Contributors', url='https://dltk.github.io', packages=find_packages(exclude=['_docs', 'contrib', 'data', 'examples']), keywords='machine learning tensorflow deep learning biomedical imaging', license='Apache License 2.0', classifiers=['Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4'], install_requires=['numpy>=1.12.1', 'scipy>=0.19.0', 'pandas>=0.19.0', 'matplotlib>=1.5.3', 'scikit-image>=0.13.0', 'tensorflow-gpu>=1.1.0', 'SimpleITK>=1.0.0', 'jupyter>=1.0.0'], extras_require={'doc': ['sphinx', 'sphinx-rtd-theme', 'recommonmark']} )
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='dltk', version='0.1', description='Deep Learning Toolkit for Medical Image Analysis', author='DLTK Contributors', url='https://dltk.github.io', packages=find_packages(exclude=['_docs', 'contrib', 'data', 'examples']), keywords='machine learning tensorflow deep learning biomedical imaging', license='Apache License 2.0', classifiers=['Intended Audience :: Developers', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Operating System :: Microsoft :: Windows', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4'], install_requires=['numpy>=1.12.1', 'scipy>=0.19.0', 'pandas>=0.19.0', 'matplotlib>=1.5.3', 'scikit-image>=0.13.0', 'tensorflow-gpu>=1.1.0', 'SimpleITK>=1.0.0', 'jupyter>=1.0.0'] )
Clone context to prevent pass-by-reference issues
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { constructor(name, config, parent) { super(); this.isEntity = true; this._contextData = {}; this._hasResolvedContext = false; this.initEntity(name, config, parent); this.setHeritable(parent); Object.defineProperty(this, 'status', { enumerable: true, get() { return this.source.statusInfo(this.getProp('status')); }, }); this.setProps(config); } getResolvedContext() { return this.source.resolve(this.context); } hasContext() { return this.getResolvedContext().then(context => Object.keys(context).length); } getContext() { return _.cloneDeep(this._contextData); } toJSON() { const self = super.toJSON(); self.isEntity = true; return self; } static defineProperty(key, opts) { if (_.isPlainObject(opts)) { Object.defineProperty(this.prototype, key, opts); } else { Object.defineProperty(this.prototype, key, { enumerable: true, writable: true, value: opts }); } } };
'use strict'; const _ = require('lodash'); const utils = require('../utils'); const Log = require('../log'); const mix = require('../mixins/mix'); const Heritable = require('../mixins/heritable'); const EntityMixin = require('../mixins/entity'); module.exports = class Entity extends mix(Heritable, EntityMixin) { constructor(name, config, parent) { super(); this.isEntity = true; this._contextData = {}; this._hasResolvedContext = false; this.initEntity(name, config, parent); this.setHeritable(parent); Object.defineProperty(this, 'status', { enumerable: true, get() { return this.source.statusInfo(this.getProp('status')); }, }); this.setProps(config); } getResolvedContext() { return this.source.resolve(this.context); } hasContext() { return this.getResolvedContext().then(context => Object.keys(context).length); } getContext() { return this._contextData; } toJSON() { const self = super.toJSON(); self.isEntity = true; return self; } static defineProperty(key, opts) { if (_.isPlainObject(opts)) { Object.defineProperty(this.prototype, key, opts); } else { Object.defineProperty(this.prototype, key, { enumerable: true, writable: true, value: opts }); } } };
BAP-2667: Modify CLI installer to allow run common commands from Package Manager[
<?php namespace Oro\Bundle\InstallerBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Oro\Bundle\InstallerBundle\CommandExecutor; class PlatformUpdateCommand extends ContainerAwareCommand { /** * @inheritdoc */ protected function configure() { $this->setName('oro:platform:update') ->setDescription('Execute platform update commands.'); } /** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $commandExecutor = new CommandExecutor( $input->hasOption('env') ? $input->getOption('env') : null, $output, $this->getApplication() ); $commandExecutor ->runCommand('oro:entity-config:update') ->runCommand('oro:entity-extend:update') ->runCommand('oro:navigation:init') ->runCommand('assets:install') ->runCommand('assetic:dump') ->runCommand('fos:js-routing:dump', array('--target' => 'js/routes.js')) ->runCommand('oro:localization:dump') ->runCommand('oro:translation:dump') ->runCommand('oro:requirejs:build'); } }
<?php namespace Oro\Bundle\InstallerBundle\Command; use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Oro\Bundle\InstallerBundle\CommandExecutor; class PlatformUpdateCommand extends ContainerAwareCommand { /** * @inheritdoc */ protected function configure() { $this->setName('oro:platform:update') ->setDescription('Execute platform update commands.'); } /** * @inheritdoc */ protected function execute(InputInterface $input, OutputInterface $output) { $commandExecutor = new CommandExecutor( $input->hasOption('env') ? $input->getOption('env') : null, $output, $this->getApplication() ); $commandExecutor ->runCommand('oro:entity-config:update') ->runCommand('oro:entity-extend:init') ->runCommand( 'oro:entity-extend:update-config', array('--process-isolation' => true) ) ->runCommand( 'doctrine:schema:update', array('--process-isolation' => true, '--force' => true, '--no-interaction' => true) ) ->runCommand('oro:search:create-index') ->runCommand('oro:navigation:init') ->runCommand('assets:install') ->runCommand('assetic:dump') ->runCommand('fos:js-routing:dump', array('--target' => 'js/routes.js')) ->runCommand('oro:localization:dump') ->runCommand('oro:translation:dump') ->runCommand('oro:requirejs:build'); } }
Add more libraries that are used at runtime
from distutils.core import setup setup(name="stellar-magnate", version="0.1", description="A space-themed commodity trading game", long_description=""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel by Brian Winn. """, author="Toshio Kuratomi", author_email="[email protected]", maintainer="Toshio Kuratomi", maintainer_email="[email protected]", url="https://github.com/abadger/pubmarine", license="GNU Affero General Public License v3 or later (AGPLv3+)", keywords='game trading', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console :: Curses', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Games/Entertainment', 'Topic :: Games/Entertainment :: Simulation', ], packages=['magnate', 'magnate.ui'], scripts=['bin/magnate'], install_requires=['ConfigObj', 'PyYaml', 'attrs', 'jsonschema', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'], )
from distutils.core import setup setup(name="stellar-magnate", version="0.1", description="A space-themed commodity trading game", long_description=""" Stellar Magnate is a space-themed trading game in the spirit of Planetary Travel by Brian Winn. """, author="Toshio Kuratomi", author_email="[email protected]", maintainer="Toshio Kuratomi", maintainer_email="[email protected]", url="https://github.com/abadger/pubmarine", license="GNU Affero General Public License v3 or later (AGPLv3+)", keywords='game trading', classifiers=[ 'Development Status :: 3 - Alpha', 'Environment :: Console :: Curses', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3 :: Only', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', 'Topic :: Games/Entertainment', 'Topic :: Games/Entertainment :: Simulation', ], packages=['magnate', 'magnate.ui'], scripts=['bin/magnate'], install_requires=['ConfigObj', 'kitchen', 'pubmarine >= 0.3', 'straight.plugin', 'urwid'], )
Rename master to main request
<?php declare(strict_types=1); namespace App\EventSubscriber; use App\Service\Config; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class RedirectInsecureConnections implements EventSubscriberInterface { protected bool $requireSecureConnection; public function __construct(Config $config) { $this->requireSecureConnection = $config->get('requireSecureConnection'); } public static function getSubscribedEvents(): array { // return the subscribed events, their methods and priorities return [ KernelEvents::REQUEST => [ ['checkAndRedirect', 10], ] ]; } /** * If we are enforcing a secure connection redirect any users who land * here accidentally. */ public function checkAndRedirect(RequestEvent $event) { if ($this->requireSecureConnection && $event->isMainRequest()) { $request = $event->getRequest(); if (!$request->isSecure()) { $path = $request->getPathInfo(); $host = $request->getHttpHost(); $url = 'https://' . $host . $path; $response = new RedirectResponse($url); $event->setResponse($response); } } } }
<?php declare(strict_types=1); namespace App\EventSubscriber; use App\Service\Config; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpKernel\Event\RequestEvent; use Symfony\Component\HttpKernel\KernelEvents; class RedirectInsecureConnections implements EventSubscriberInterface { /** * @var string */ protected $requireSecureConnection; public function __construct(Config $config) { $this->requireSecureConnection = $config->get('requireSecureConnection'); } public static function getSubscribedEvents(): array { // return the subscribed events, their methods and priorities return [ KernelEvents::REQUEST => [ ['checkAndRedirect', 10], ] ]; } /** * If we are enforcing a secure connection redirect any users who land * here accidentally. */ public function checkAndRedirect(RequestEvent $event) { if ($this->requireSecureConnection && $event->isMasterRequest()) { $request = $event->getRequest(); if (!$request->isSecure()) { $path = $request->getPathInfo(); $host = $request->getHttpHost(); $url = 'https://' . $host . $path; $response = new RedirectResponse($url); $event->setResponse($response); } } } }
Replace jQuery .unbind with .off The .unbind method is deprecated in jQuery 3.
import $ from 'jquery'; import _ from 'underscore'; import AlertDialogTemplate from './alertDialog.pug'; /** * Miscellaneous utility functions. */ /** * Show an alert dialog with a single button. * @param [text] The text to display. * @param [buttonText] The text for the button. * @param [buttonClass] Class string to apply to the button. * @param [escapedHtml] If you want to render the text as HTML rather than * plain text, set this to true to acknowledge that you have escaped any * user-created data within the text to prevent XSS exploits. * @param callback Callback function called when the user clicks the button. */ const showAlertDialog = function (params) { params = _.extend({ text: '', buttonText: 'OK', buttonClass: 'btn-primary', escapedHtml: false }, params); let container = $('#g-dialog-container'); container .html(AlertDialogTemplate({ params: params })) .girderModal(false) .on('hidden.bs.modal', () => { if (params.callback) { params.callback(); } }); let el = container.find('.modal-body>p'); if (params.escapedHtml) { el.html(params.text); } else { el.text(params.text); } $('#isic-alert-dialog-button') .off('click') .click(() => { container.modal('hide'); }); }; export {showAlertDialog};
import $ from 'jquery'; import _ from 'underscore'; import AlertDialogTemplate from './alertDialog.pug'; /** * Miscellaneous utility functions. */ /** * Show an alert dialog with a single button. * @param [text] The text to display. * @param [buttonText] The text for the button. * @param [buttonClass] Class string to apply to the button. * @param [escapedHtml] If you want to render the text as HTML rather than * plain text, set this to true to acknowledge that you have escaped any * user-created data within the text to prevent XSS exploits. * @param callback Callback function called when the user clicks the button. */ const showAlertDialog = function (params) { params = _.extend({ text: '', buttonText: 'OK', buttonClass: 'btn-primary', escapedHtml: false }, params); let container = $('#g-dialog-container'); container .html(AlertDialogTemplate({ params: params })) .girderModal(false) .on('hidden.bs.modal', () => { if (params.callback) { params.callback(); } }); let el = container.find('.modal-body>p'); if (params.escapedHtml) { el.html(params.text); } else { el.text(params.text); } $('#isic-alert-dialog-button') .unbind('click') .click(() => { container.modal('hide'); }); }; export {showAlertDialog};
Disable SSL test on python 2.5
#!/usr/bin/env python from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase from tornado.web import Application, RequestHandler import os import pycurl import re import unittest import urllib try: import ssl except ImportError: ssl = None class HelloWorldRequestHandler(RequestHandler): def get(self): self.finish("Hello world") class SSLTest(AsyncHTTPTestCase, LogTrapTestCase): def get_app(self): return Application([('/', HelloWorldRequestHandler)]) def get_httpserver_options(self): # Testing keys were generated with: # openssl req -new -keyout tornado/test/test.key -out tornado/test/test.crt -nodes -days 3650 -x509 test_dir = os.path.dirname(__file__) return dict(ssl_options=dict( certfile=os.path.join(test_dir, 'test.crt'), keyfile=os.path.join(test_dir, 'test.key'))) def test_ssl(self): def disable_cert_check(curl): # Our certificate was not signed by a CA, so don't check it curl.setopt(pycurl.SSL_VERIFYPEER, 0) self.http_client.fetch(self.get_url('/').replace('http', 'https'), self.stop, prepare_curl_callback=disable_cert_check) response = self.wait() self.assertEqual(response.body, "Hello world") if ssl is None: # Don't try to run ssl tests if we don't have the ssl module del SSLTest
#!/usr/bin/env python from tornado.testing import AsyncHTTPTestCase, LogTrapTestCase from tornado.web import Application, RequestHandler import os import pycurl import re import unittest import urllib class HelloWorldRequestHandler(RequestHandler): def get(self): self.finish("Hello world") class SSLTest(AsyncHTTPTestCase, LogTrapTestCase): def get_app(self): return Application([('/', HelloWorldRequestHandler)]) def get_httpserver_options(self): # Testing keys were generated with: # openssl req -new -keyout tornado/test/test.key -out tornado/test/test.crt -nodes -days 3650 -x509 test_dir = os.path.dirname(__file__) return dict(ssl_options=dict( certfile=os.path.join(test_dir, 'test.crt'), keyfile=os.path.join(test_dir, 'test.key'))) def test_ssl(self): def disable_cert_check(curl): # Our certificate was not signed by a CA, so don't check it curl.setopt(pycurl.SSL_VERIFYPEER, 0) self.http_client.fetch(self.get_url('/').replace('http', 'https'), self.stop, prepare_curl_callback=disable_cert_check) response = self.wait() self.assertEqual(response.body, "Hello world")
Allow passing of template folder path as a string argument
/* * grunt-nunjucks-2-html * https://github.com/vitkarpov/grunt-nunjucks-2-html * * Copyright (c) 2014 Vit Karpov * Licensed under the MIT license. */ 'use strict'; var nunjucks = require('nunjucks'); var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('nunjucks', 'Renders nunjucks` template to HTML', function() { var options = this.options(); this.files.forEach(function(f) { var filepath = path.resolve(__dirname, '../../../', f.src[0]); if (!grunt.file.exists(filepath)) { grunt.log.warn('Template`s file "' + filepath + '" not found.'); return false; } if (!options.data) { grunt.log.warn('Template`s data is empty. Guess you forget to specify data option'); } var data = (typeof options.preprocessData === 'function') ? options.preprocessData.call(f, options.data || {}) : options.data || {}; var template = grunt.file.read(filepath); if (Array.isArray(options.paths) && options.paths.length || typeof options.paths == 'string') { nunjucks.configure(options.paths); } var compiledHtml = nunjucks.renderString(template, data); grunt.file.write(f.dest, compiledHtml); grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
/* * grunt-nunjucks-2-html * https://github.com/vitkarpov/grunt-nunjucks-2-html * * Copyright (c) 2014 Vit Karpov * Licensed under the MIT license. */ 'use strict'; var nunjucks = require('nunjucks'); var path = require('path'); module.exports = function(grunt) { grunt.registerMultiTask('nunjucks', 'Renders nunjucks` template to HTML', function() { var options = this.options(); this.files.forEach(function(f) { var filepath = path.resolve(__dirname, '../../../', f.src[0]); if (!grunt.file.exists(filepath)) { grunt.log.warn('Template`s file "' + filepath + '" not found.'); return false; } if (!options.data) { grunt.log.warn('Template`s data is empty. Guess you forget to specify data option'); } var data = (typeof options.preprocessData === 'function') ? options.preprocessData.call(f, options.data || {}) : options.data || {}; var template = grunt.file.read(filepath); if (Array.isArray(options.paths) && options.paths.length) { nunjucks.configure(options.paths); } var compiledHtml = nunjucks.renderString(template, data); grunt.file.write(f.dest, compiledHtml); grunt.log.writeln('File "' + f.dest + '" created.'); }); }); };
Refactor duplication out of tests.
/* global describe, it */ import assert from 'assert'; import GroupedKata from '../src/grouped-kata.js'; function remoteFileLoaderWhichReturnsGivenData(data) { return (url, onLoaded) => { onLoaded(null, data); }; } function remoteFileLoaderWhichReturnsError(error) { return (url, onLoaded) => { onLoaded(error); }; } describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } const validData = JSON.stringify({groups: {}}); const loaderStub = remoteFileLoaderWhichReturnsGivenData(validData); new GroupedKata(loaderStub, 'irrelevant url').load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { function onError(err) { assert.ok(err); done(); } const loaderStub = remoteFileLoaderWhichReturnsError(new Error('')); new GroupedKata(loaderStub, 'irrelevant url').load(onError); }); it('for invalid data', function(done) { function onError(err) { assert.ok(err); done(); } const invalidData = JSON.stringify({propertyGroupsMissing:{}}); const loaderStub = remoteFileLoaderWhichReturnsGivenData(invalidData); new GroupedKata(loaderStub, 'irrelevant url').load(onError); }); }); });
/* global describe, it */ import assert from 'assert'; import {KATAS_URL, URL_PREFIX} from '../src/config.js'; import GroupedKata from '../src/grouped-kata.js'; describe('load ES6 kata data', function() { it('loaded data are as expected', function(done) { const loadRemoteFileStub = (url, onLoaded) => { let validData = JSON.stringify({groups: {}}); onLoaded(null, validData); }; function onSuccess(groupedKatas) { assert.ok(groupedKatas); done(); } new GroupedKata(loadRemoteFileStub, KATAS_URL).load(() => {}, onSuccess); }); describe('on error, call error callback and the error passed', function() { it('invalid JSON', function(done) { const loadRemoteFileStub = (url, onLoaded) => { onLoaded(new Error('')); }; function onError(err) { assert.ok(err); done(); } new GroupedKata(loadRemoteFileStub, '').load(onError); }); it('for invalid data', function(done) { const invalidData = JSON.stringify({propertyGroupsMissing:{}}); const loadRemoteFileStub = (url, onLoaded) => { onLoaded(null, invalidData); }; function onError(err) { assert.ok(err); done(); } new GroupedKata(loadRemoteFileStub, '').load(onError); }); }); });
Update triangle validate check at main script
$(window).ready(function(){ $('#triangle-calculator').submit(function(e){ e.preventDefault(); // // Code start here // var triangleType = 'Not a triangle'; var a = parseInt( $('#a_number').val() ); var b = parseInt( $('#b_number').val() ); var c = parseInt( $('#c_number').val() ); if ( ( a < 0 || a > 200 ) || ( b < 0 || b > 200 ) || ( c < 0 || c > 200 ) ) { triangleType = 'Some input value is out of range'; } else { if ( a <= b + c && b <= a + c && c <= a + b ) { if ( a == b && a == c ) { triangleType = 'Equilateral'; } else if ( a != b && b != c && c != a ) { triangleType = 'Scalene'; } else { triangleType = 'Isoscalene'; } } } $('#log-msg').append('Triangle type: ' + triangleType + "\n"); // // Code end here // }); });
$(window).ready(function(){ $('#triangle-calculator').submit(function(e){ e.preventDefault(); // // Code start here // var triangleType = 'Not a triangle'; var a = parseInt( $('#a_number').val() ); var b = parseInt( $('#b_number').val() ); var c = parseInt( $('#c_number').val() ); if ( ( a < 0 || a > 200 ) && ( b < 0 || b > 200 ) && ( c < 0 || c > 200 ) ) { triangleType = 'Some input value is out of range'; } else { if ( a <= b + c && b <= a + c && c <= a + b ) { if ( a == b && a == c ) { triangleType = 'Equilateral'; } else if ( a != b && b != c && c != a ) { triangleType = 'Scalene'; } else { triangleType = 'Isoscalene'; } } } $('#log-msg').append('Triangle type: ' + triangleType + "\n"); // // Code end here // }); });
Add dynamic 'column' key for foreign constraints
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Str; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID column definition. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param array $attributes * @return void */ public function __construct(Blueprint $blueprint, $attributes = []) { parent::__construct($attributes); $this->blueprint = $blueprint; } /** * Create a foreign key constraint on this column referencing the column of the conventionally related table. * * @param string|null $table * @param string $column * @return \Illuminate\Support\Fluent|\Illuminate\Database\Schema\ForeignKeyDefinition */ public function constrained($table = null, $column = 'id') { return $this->references($column)->on($table ?: Str::plural(Str::before($this->name, '_' . $column))); } /** * Specify which column this foreign ID references on another table. * * @param string $column * @return \Illuminate\Support\Fluent|\Illuminate\Database\Schema\ForeignKeyDefinition */ public function references($column) { return $this->blueprint->foreign($this->name)->references($column); } }
<?php namespace Illuminate\Database\Schema; use Illuminate\Support\Str; class ForeignIdColumnDefinition extends ColumnDefinition { /** * The schema builder blueprint instance. * * @var \Illuminate\Database\Schema\Blueprint */ protected $blueprint; /** * Create a new foreign ID column definition. * * @param \Illuminate\Database\Schema\Blueprint $blueprint * @param array $attributes * @return void */ public function __construct(Blueprint $blueprint, $attributes = []) { parent::__construct($attributes); $this->blueprint = $blueprint; } /** * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table. * * @param string|null $table * @return \Illuminate\Support\Fluent|\Illuminate\Database\Schema\ForeignKeyDefinition */ public function constrained($table = null) { return $this->references('id')->on($table ?: Str::plural(Str::before($this->name, '_id'))); } /** * Specify which column this foreign ID references on another table. * * @param string $column * @return \Illuminate\Support\Fluent|\Illuminate\Database\Schema\ForeignKeyDefinition */ public function references($column) { return $this->blueprint->foreign($this->name)->references($column); } }