text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Fix for reverse sorting. Styling fixes
ko.bindingHandlers.sortBy = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var asc = true; element.style.cursor = 'pointer'; element.onclick = function(){ var value = valueAccessor(); var data = value.array; var sortBy = value.sortBy; if((ko.isObservable(data) && !Array.isArray(data()))) throw "Incorrect argument for array. Array must be an observableArray"; asc = !asc; switch(true) { case typeof sortBy === "function": data.sort(sortBy); break; case Array.isArray(sortBy): var length = sortBy.length; data.sort(function(a,b){ var index = -1; while(++index < length) { var field = sortBy[index]; if(a[field] == b[field]) continue; return a[field] > b[field] ? 1 : -1; } }); break; case typeof sortBy === "string": data.sort(function(a,b){ return a[sortBy] > b[sortBy] ? 1 : a[sortBy] < b[sortBy] ? -1 : 0; }); break; default: throw "Incorrect argument for sortBy"; } if(!asc) data.reverse(); }; } };
ko.bindingHandlers.sortBy = { init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) { var asc = true; element.style.cursor = 'pointer'; element.onclick = function(){ var value = valueAccessor(); var data = value.array; var sortBy = value.sortBy; if((ko.isObservable(data) && !Array.isArray(data()))) throw "Incorrect argument for array. Array must be an observableArray"; asc = !asc; switch(true) { case typeof sortBy === "function": data.sort(sortBy); break; case Array.isArray(sortBy): var length = sortBy.length; data.sort(function(a,b){ var index = -1; while(++index < length) { var field = sortBy[index]; if(a[field] == b[field]) continue; return a[field] > b[field] ? 1 : -1; } }) break; case typeof sortBy === "string": data.sort(function(a,b){ return a[sortBy] > b[sortBy] ? 1 : a[sortBy] < b[sortBy] ? -1 : 0; }) break; default: throw "Incorrect argument for sortBy"; break; } }; } };
Add incoming number for the project and attutude
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) attitute = models.TextField(blank=True, null=True) number = models.CharField(max_length=30, blank=True, null=True) def __unicode__(self): return self.name
# -*- encoding:utf-8 -*- from django.db import models class Project(models.Model): STATUS = ( ('unrevised', u'Неразгледан'), ('returned', u'Върнат за корекция'), ('pending', u'Предстои да бъде разгледан на СИС'), ('approved', u'Разгледан и одобрен на СИС'), ('rejected', u'Разгледан и неодобрен на СИС')) user = models.ForeignKey('members.User') name = models.CharField(max_length=100) flp = models.ForeignKey('members.User', related_name='flp') team = models.ManyToManyField('members.User', related_name='team') description = models.TextField() targets = models.TextField() tasks = models.TextField() target_group = models.TextField() schedule = models.TextField() resources = models.TextField() finance_description = models.TextField() partners = models.TextField(blank=True, null=True) files = models.ManyToManyField('attachments.Attachment') status = models.CharField(max_length=50, choices=STATUS, default='unrevised') discussed_at = models.DateField(blank=True, null=True) def __unicode__(self): return self.name
Set stations as started when loading fixtures.
<?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity; use App\Radio\Enums\BackendAdapters; use App\Radio\Enums\FrontendAdapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Persistence\ObjectManager; final class Station extends AbstractFixture { public function load(ObjectManager $manager): void { $station = new Entity\Station(); $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setEnableRequests(true); $station->setFrontendType(FrontendAdapters::Icecast->value); $station->setBackendType(BackendAdapters::Liquidsoap->value); $station->setEnableHls(true); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); $station->setHasStarted(true); $station->ensureDirectoriesExist(); $mediaStorage = $station->getMediaStorageLocation(); $recordingsStorage = $station->getRecordingsStorageLocation(); $podcastsStorage = $station->getPodcastsStorageLocation(); $stationQuota = getenv('INIT_STATION_QUOTA'); if (!empty($stationQuota)) { $mediaStorage->setStorageQuota($stationQuota); $recordingsStorage->setStorageQuota($stationQuota); $podcastsStorage->setStorageQuota($stationQuota); } $manager->persist($station); $manager->persist($mediaStorage); $manager->persist($recordingsStorage); $manager->persist($podcastsStorage); $manager->flush(); $this->addReference('station', $station); } }
<?php declare(strict_types=1); namespace App\Entity\Fixture; use App\Entity; use App\Radio\Enums\BackendAdapters; use App\Radio\Enums\FrontendAdapters; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Persistence\ObjectManager; final class Station extends AbstractFixture { public function load(ObjectManager $manager): void { $station = new Entity\Station(); $station->setName('AzuraTest Radio'); $station->setDescription('A test radio station.'); $station->setEnableRequests(true); $station->setFrontendType(FrontendAdapters::Icecast->value); $station->setBackendType(BackendAdapters::Liquidsoap->value); $station->setEnableHls(true); $station->setRadioBaseDir('/var/azuracast/stations/azuratest_radio'); $station->ensureDirectoriesExist(); $mediaStorage = $station->getMediaStorageLocation(); $recordingsStorage = $station->getRecordingsStorageLocation(); $podcastsStorage = $station->getPodcastsStorageLocation(); $stationQuota = getenv('INIT_STATION_QUOTA'); if (!empty($stationQuota)) { $mediaStorage->setStorageQuota($stationQuota); $recordingsStorage->setStorageQuota($stationQuota); $podcastsStorage->setStorageQuota($stationQuota); } $manager->persist($station); $manager->persist($mediaStorage); $manager->persist($recordingsStorage); $manager->persist($podcastsStorage); $manager->flush(); $this->addReference('station', $station); } }
Use ugettext_lazy instead of ugettext to make it compatible with Django 1.7 https://docs.djangoproject.com/en/dev/ref/applications/#applications-troubleshooting
# -*- coding: utf-8 -*- __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext_lazy as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL')) css_class = models.CharField(max_length=20, verbose_name=_('CSS Class')) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
# -*- coding: utf-8 -*- __author__ = 'sandlbn' from django.db import models from django.utils.translation import ugettext as _ from utils import datetime_to_timestamp class CalendarEvent(models.Model): """ Calendar Events """ CSS_CLASS_CHOICES = ( ('', _('Normal')), ('event-warning', _('Warning')), ('event-info', _('Info')), ('event-success', _('Success')), ('event-inverse', _('Inverse')), ('event-special', _('Special')), ('event-important', _('Important')), ) title = models.CharField(max_length=255, verbose_name=_('Title')) url = models.URLField(verbose_name=_('URL')) css_class = models.CharField(max_length=20, verbose_name=_('CSS Class')) start = models.DateTimeField(verbose_name=_('Start Date')) end = models.DateTimeField(verbose_name=_('End Date'), blank=True) @property def start_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.start) @property def end_timestamp(self): """ Return end date as timestamp """ return datetime_to_timestamp(self.end) def __unicode__(self): return self.title
[FIX] Add source and sourceId to db model
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Activities', { id: { type: Sequelize.INTEGER, allowNull: false, unique: true, autoIncrement:true, primaryKey: true }, name: { type: Sequelize.STRING, allowNull: false }, description: { type: Sequelize.STRING }, tags: { type: Sequelize.ARRAY(Sequelize.TEXT) }, address: { type: Sequelize.STRING }, latitude: { type: Sequelize.DECIMAL }, longitude: { type: Sequelize.DECIMAL }, temporary: { type: Sequelize.BOOLEAN }, date_start: { type: Sequelize.DATE }, date_end: { type: Sequelize.DATE }, opening_hours: { type: Sequelize.ARRAY(Sequelize.INTEGER) }, type: { type: Sequelize.ENUM, }, source: { type: Sequelize.STRING, }, idSource: { type: Sequelize.DECIMAL, }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Activities'); } };
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('Activities', { id: { type: Sequelize.INTEGER, allowNull: false, unique: true, autoIncrement:true, primaryKey: true }, name: { type: Sequelize.STRING, allowNull: false }, description: { type: Sequelize.STRING }, tags: { type: Sequelize.ARRAY(Sequelize.TEXT) }, address: { type: Sequelize.STRING }, latitude: { type: Sequelize.DECIMAL }, longitude: { type: Sequelize.DECIMAL }, temporary: { type: Sequelize.BOOLEAN }, date_start: { type: Sequelize.DATE }, date_end: { type: Sequelize.DATE }, opening_hours: { type: Sequelize.ARRAY(Sequelize.INTEGER) }, type: { type: Sequelize.ENUM, }, source: { type: DataTypes.STRING, }, idSource: { type: DataTypes.DECIMAL, }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('Activities'); } };
Change mark item schema to be oneOf group or non-group mark
var parseMark = require('./mark'); function parseRootMark(model, spec, width, height) { return { type: "group", width: width, height: height, scales: spec.scales || [], axes: spec.axes || [], legends: spec.legends || [], marks: (spec.marks || []).map(function(m) { return parseMark(model, m); }) }; } module.exports = parseRootMark; parseRootMark.schema = { "defs": { "container": { "type": "object", "properties": { "scales": { "type": "array", "items": {"$ref": "#/defs/scale"} }, "axes": { "type": "array", "items": {"$ref": "#/defs/axis"} }, "legends": { "type": "array", "items": {"$ref": "#/defs/legend"} }, "marks": { "type": "array", "items": {"oneOf":[{"$ref": "#/defs/groupMark"}, {"$ref": "#/defs/nonGroupMark"}]} } } }, "groupMark": { "allOf": [ { "properties": { "type": {"enum": ["group"]} }, "required": ["type"] }, {"$ref": "#/defs/mark"}, {"$ref": "#/defs/container"} ] }, "nonGroupMark": { "allOf": [ {"$ref": "#/defs/mark"}, { "not": {"$ref": "#/defs/groupMark"} } ] } } };
var parseMark = require('./mark'); function parseRootMark(model, spec, width, height) { return { type: "group", width: width, height: height, scales: spec.scales || [], axes: spec.axes || [], legends: spec.legends || [], marks: (spec.marks || []).map(function(m) { return parseMark(model, m); }) }; } module.exports = parseRootMark; parseRootMark.schema = { "defs": { "container": { "type": "object", "properties": { "scales": { "type": "array", "items": {"$ref": "#/defs/scale"} }, "axes": { "type": "array", "items": {"$ref": "#/defs/axis"} }, "legends": { "type": "array", "items": {"$ref": "#/defs/legend"} }, "marks": { "type": "array", "items": {"anyOf":[{"$ref": "#/defs/groupMark"}, {"$ref": "#/defs/mark"}]} } } }, "groupMark": { "allOf": [{"$ref": "#/defs/mark"}, {"$ref": "#/defs/container"}, { "properties": { "type": {"enum": ["group"]} }, "required": ["type"] }] } } };
Add a navigation item to go to the tools section
import React from "react"; import styled from "styled-components"; import Link from "gatsby-link"; import Headroom from "react-headroom"; const StyledMenu = styled.div` .headroom { background: white; nav { display: flex; flex-direction: row; justify-content: flex-end; align-items: center; max-width: 850px; margin: 0 auto; padding: 15px 25px; } a { margin-bottom: -4px; text-decoration: none; margin-left: 1rem; &:first-child { margin-left: 0; } &.active { text-decoration: underline wavy; } &.hidden { opacity: 0; } } } `; class Navigation extends React.Component { render() { return ( <StyledMenu> <Headroom> <nav> <Link to="/" exact activeClassName="hidden"> Home </Link> <Link to="/about-me" activeClassName="active"> About Me </Link> <Link to="/tools" activeClassName="active"> Tools </Link> </nav> </Headroom> </StyledMenu> ); } } export default Navigation;
import React from "react"; import styled from "styled-components"; import Link from "gatsby-link"; import Headroom from "react-headroom"; const StyledMenu = styled.div` .headroom { background: white; nav { display: flex; flex-direction: row; justify-content: flex-end; align-items: center; max-width: 850px; margin: 0 auto; padding: 15px 25px; } a { margin-bottom: -4px; text-decoration: none; margin-left: 1rem; &:first-child { margin-left: 0; } &.active { text-decoration: underline wavy; } &.hidden { opacity: 0; } } } `; class Navigation extends React.Component { render() { return ( <StyledMenu> <Headroom> <nav> <Link to="/" exact activeClassName="hidden"> Home </Link> <Link to="/about-me" activeClassName="active"> About Me </Link> </nav> </Headroom> </StyledMenu> ); } } export default Navigation;
Change email validator regexp. Previous one was too dummy :)
angular.module('codebrag.invitations') .service('invitationService', function($http, $q) { this.loadRegisteredUsers = function() { return $http.get('rest/users/all').then(function(response) { return response.data.registeredUsers; }); }; this.loadInvitationLink = function() { var dfd = $q.defer(); function success(response) { dfd.resolve(response.data.invitationLink); return dfd.promise; } function error() { dfd.resolve('Sorry. We could not generate invitation link.'); return dfd.promise; } return $http.get('rest/invitation').then(success, error); }; this.sendInvitation = function(invitations, invitationLink) { var invitationRequestPayload = { emails: invitations.map(function(i) { return i.email; }), invitationLink: invitationLink }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); }; this.validateEmails = function(emailsString) { var regexp = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(regexp.test(email)); }); return !foundInvalid; } });
angular.module('codebrag.invitations') .service('invitationService', function($http, $q) { this.loadRegisteredUsers = function() { return $http.get('rest/users/all').then(function(response) { return response.data.registeredUsers; }); }; this.loadInvitationLink = function() { var dfd = $q.defer(); function success(response) { dfd.resolve(response.data.invitationLink); return dfd.promise; } function error() { dfd.resolve('Sorry. We could not generate invitation link.'); return dfd.promise; } return $http.get('rest/invitation').then(success, error); }; this.sendInvitation = function(invitations, invitationLink) { var invitationRequestPayload = { emails: invitations.map(function(i) { return i.email; }), invitationLink: invitationLink }; return $http.post('rest/invitation', invitationRequestPayload, {unique: true, requestId: 'invitation'}); } this.validateEmails = function(emailsString) { var foundInvalid = emailsString.split(/[\s;,]+/).some(function (email) { return !(/^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/.test(email)); }); return !foundInvalid; } });
Update exception handling syntax for python 3 compatibility.
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals try: from faker import Factory as FakerFactory except ImportError as error: message = '{0}. Try running `pip install fake-factory`.'.format(error) raise ImportError(message) try: import factory except ImportError as error: message = '{0}. Try running `pip install factory_boy`.'.format(error) raise ImportError(message) faker = FakerFactory.create() class AuthorshipFactory(factory.django.DjangoModelFactory): class Meta(object): abstract = True created_by = factory.SubFactory('thecut.authorship.factories.UserFactory') updated_by = factory.SelfAttribute('created_by') class UserFactory(factory.django.DjangoModelFactory): class Meta(object): model = 'auth.User' django_get_or_create = ['username'] username = factory.Sequence(lambda n: 'user-{0}'.format(n)) class UserFakerFactory(UserFactory): class Meta(object): model = 'auth.User' django_get_or_create = ['username'] first_name = factory.LazyAttribute(lambda o: faker.first_name()) last_name = factory.LazyAttribute(lambda o: faker.last_name()) username = factory.LazyAttribute( lambda o: '{0}.{1}'.format(o.first_name.lower(), o.last_name.lower())) email = factory.LazyAttribute( lambda o: '{0}@example.com'.format(o.username))
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals try: from faker import Factory as FakerFactory except ImportError, error: message = '{0}. Try running `pip install fake-factory`.'.format(error) raise ImportError(message) try: import factory except ImportError, error: message = '{0}. Try running `pip install factory_boy`.'.format(error) raise ImportError(message) faker = FakerFactory.create() class AuthorshipFactory(factory.django.DjangoModelFactory): class Meta(object): abstract = True created_by = factory.SubFactory('thecut.authorship.factories.UserFactory') updated_by = factory.SelfAttribute('created_by') class UserFactory(factory.django.DjangoModelFactory): class Meta(object): model = 'auth.User' django_get_or_create = ['username'] username = factory.Sequence(lambda n: 'user-{0}'.format(n)) class UserFakerFactory(UserFactory): class Meta(object): model = 'auth.User' django_get_or_create = ['username'] first_name = factory.LazyAttribute(lambda o: faker.first_name()) last_name = factory.LazyAttribute(lambda o: faker.last_name()) username = factory.LazyAttribute( lambda o: '{0}.{1}'.format(o.first_name.lower(), o.last_name.lower())) email = factory.LazyAttribute( lambda o: '{0}@example.com'.format(o.username))
Configure `UserClass` field and validator
<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = [ 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'default' => null ], 'Used' => [ 'type' => 'timestamp', 'default' => null ], 'UserClass' => [ 'default' => null ] ]; public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public static $validators = [ 'UserClass' => [ 'validator' => 'selection', 'choices' => [], 'required' => false ] ]; public static function __classLoaded() { static::$fields['UserClass']['default'] = User::getDefaultClass(); static::$validators['UserClass']['choices'] = User::getSubClasses(); } public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }
<?php namespace Emergence\People; use HandleBehavior; class Invitation extends \ActiveRecord { public static $tableName = 'invitations'; public static $singularNoun = 'invitation'; public static $pluralNoun = 'invitations'; public static $fields = [ 'RecipientID' => [ 'type' => 'uint', 'index' => true ], 'Handle' => [ 'unique' => true ], 'Status' => [ 'type' => 'enum', 'values' => ['Pending', 'Used', 'Revoked'], 'default' => 'Pending' ], 'Expires' => [ 'type' => 'timestamp', 'default' => null ], 'Used' => [ 'type' => 'timestamp', 'default' => null ], 'UserClass' => [ 'default' => User::class ] ]; public static $relationships = [ 'Recipient' => [ 'type' => 'one-one', 'class' => Person::class ] ]; public static $validators = [ 'UserClass' => [ 'validator' => 'selection', 'choices' => [], 'required' => false ] ]; public static function __classLoaded() { $fieldCls = User::getStackedConfig('fields', 'Class'); static::$validators['UserClass']['choices'] = $fieldCls['values']; parent::__classLoaded(); } public function save($deep = true) { // set handle if (!$this->Handle) { $this->Handle = HandleBehavior::generateRandomHandle($this); } // call parent parent::save($deep); } }
Change `bind('click', ...` to `on('click', ...`
(function() { 'use strict'; angular .module('semantic.ui.elements.checkbox', []) .directive('smCheckbox', smCheckbox); function smCheckbox() { return { restrict: 'E', require: '?ngModel', transclude: true, replace: true, scope: { ngDisabled: '=' }, template: '<div class="ui checkbox">' + '<input type="checkbox" ng-disabled="ngDisabled" ng-checked="isChecked">' + '<label ng-transclude></label>' + '</div>', link: function(scope, element, attrs, ngModel) { element.on('click', toggleFn); if (ngModel) { ngModel.$render = function() { scope.isChecked = ngModel.$viewValue; }; } if (attrs.toggle !== void 0) { angular.element(element).addClass('toggle'); } else if (attrs.slider !== void 0) { angular.element(element).addClass('slider'); } if (attrs.ariaLabel === void 0) { element.attr('aria-label', element[0].textContent.trim()); } function toggleFn() { if (scope.ngDisabled) { return; } scope.isChecked = !scope.isChecked; if (ngModel) { ngModel.$setViewValue(scope.isChecked); } scope.$apply(); } } }; } })();
(function() { 'use strict'; angular .module('semantic.ui.elements.checkbox', []) .directive('smCheckbox', smCheckbox); function smCheckbox() { return { restrict: 'E', require: '?ngModel', transclude: true, replace: true, scope: { ngDisabled: '=' }, template: '<div class="ui checkbox">' + '<input type="checkbox" ng-disabled="ngDisabled" ng-checked="isChecked">' + '<label ng-transclude></label>' + '</div>', link: function(scope, element, attrs, ngModel) { element.bind('click', toggleFn); if (ngModel) { ngModel.$render = function() { scope.isChecked = ngModel.$viewValue; }; } if (attrs.toggle !== void 0) { angular.element(element).addClass('toggle'); } else if (attrs.slider !== void 0) { angular.element(element).addClass('slider'); } if (attrs.ariaLabel === void 0) { element.attr('aria-label', element[0].textContent.trim()); } function toggleFn() { if (scope.ngDisabled) { return; } scope.isChecked = !scope.isChecked; if (ngModel) { ngModel.$setViewValue(scope.isChecked); } scope.$apply(); } } }; } })();
Add group id, now required for fifo
'use strict'; const AWS = require('aws-sdk'); module.exports = {}; module.exports.generic = generic; module.exports.minuteAggregation = minuteAggregation; function generic(queue, body) { const sqs = new AWS.SQS(); return new Promise((resolve, reject) => { sqs.sendMessage({ QueueUrl: queue, MessageBody: JSON.stringify(body), MessageGroupId: body.jobType }, (err, data) => { if (err) return reject(err); resolve(data); }); }); } function minuteAggregation(keys, propogate) { const promises = []; keys.forEach(key => { promises.push(generic(process.env.perMinQueue, { worker: 'aggregator', jobType: 'minute', key: key.slice(0, 16) })); }); if (propogate) { promises.push(hourAggregation(keys)); // promises.push(dayAggregation); // promises.push(monthAggregation); } return Promise.all(promises); } function hourAggregation(keys) { const promises = []; keys.forEach(key => { promises.push(generic(process.env.perMinQueue, { worker: 'aggregator', jobType: 'hour', key: key.slice(0, 13) })); }); return Promise.all(promises); }
'use strict'; const AWS = require('aws-sdk'); module.exports = {}; module.exports.generic = generic; module.exports.minuteAggregation = minuteAggregation; function generic(queue, body) { const sqs = new AWS.SQS(); return new Promise((resolve, reject) => { sqs.sendMessage({ QueueUrl: queue, MessageBody: JSON.stringify(body) }, (err, data) => { if (err) return reject(err); resolve(data); }); }); } function minuteAggregation(keys, propogate) { const promises = []; keys.forEach(key => { promises.push(generic(process.env.perMinQueue, { worker: 'aggregator', jobType: 'minute', key: key.slice(0, 16) })); }); if (propogate) { promises.push(hourAggregation(keys)); // promises.push(dayAggregation); // promises.push(monthAggregation); } return Promise.all(promises); } function hourAggregation(keys) { const promises = []; keys.forEach(key => { promises.push(generic(process.env.perMinQueue, { worker: 'aggregator', jobType: 'hour', key: key.slice(0, 13) })); }); return Promise.all(promises); }
Remove manual setting of application environment
/* ************************************************************************ coretest Copyright: 2010 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /* ************************************************************************ #asset(coretest/*) ************************************************************************ */ /** * Unify application class */ core.Class("coretest.Application", { include : [unify.Application], members : { // overridden main : function() { // Call super class unify.Application.prototype.main.call(this); // Configure application document.title = "coretest"; // Create view managers var MasterViewManager = new unify.view.ViewManager("master"); // Register your view classes... MasterViewManager.register(coretest.view.Start, true); MasterViewManager.register(coretest.view.Test); MasterViewManager.register(coretest.view.OtherTest); // Add TabViews or SplitViews... var TabView = new unify.view.TabViewManager(MasterViewManager); TabView.register(coretest.view.Start); TabView.register(coretest.view.Test); // Add view manager (or SplitView or TabView) to the root this.add(TabView); //this.add(MasterViewManager); // Add at least one view manager to the navigation managment var Navigation = unify.view.Navigation.getInstance(); Navigation.register(MasterViewManager); Navigation.init(); }, _getTheme : function() { return new unify.theme.Dark(); } } });
/* ************************************************************************ coretest Copyright: 2010 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /* ************************************************************************ #asset(coretest/*) ************************************************************************ */ core.Env.define("application", "coretest.Application"); /** * Unify application class */ core.Class("coretest.Application", { include : [unify.Application], members : { // overridden main : function() { // Call super class unify.Application.prototype.main.call(this); // Configure application document.title = "coretest"; // Create view managers var MasterViewManager = new unify.view.ViewManager("master"); // Register your view classes... MasterViewManager.register(coretest.view.Start, true); MasterViewManager.register(coretest.view.Test); MasterViewManager.register(coretest.view.OtherTest); // Add TabViews or SplitViews... var TabView = new unify.view.TabViewManager(MasterViewManager); TabView.register(coretest.view.Start); TabView.register(coretest.view.Test); // Add view manager (or SplitView or TabView) to the root this.add(TabView); //this.add(MasterViewManager); // Add at least one view manager to the navigation managment var Navigation = unify.view.Navigation.getInstance(); Navigation.register(MasterViewManager); Navigation.init(); }, _getTheme : function() { return new unify.theme.Dark(); } } });
Remove unused section of SettingsForm
from django.contrib.auth.models import User from django import forms from account.models import UserProfile attributes = {"class": "required"} class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^[\w.@+-]+$', max_length=30, widget=forms.TextInput(attrs=attributes), label="Username", error_message={'invalid': "This value may contain only letters, numbers and @.+- characters."} ) email = forms.EmailField() def clean_username(self): username = self.cleaned_data["username"] existing = User.objects.filter(username__iexact=username) if existing.exists(): raise forms.ValidationError("A user with that username already exists.") else: return self.cleaned_data["username"] class SettingsForm(forms.Form): email = forms.EmailField() xsede_username = forms.CharField(max_length=50, required=False, label="XSEDE Username") new_ssh_keypair = forms.BooleanField(required=False) class UserProfileForm(forms.ModelForm): private_key = forms.CharField(widget=forms.Textarea) public_key = forms.CharField(widget=forms.Textarea) class Meta: model = UserProfile fields = ("xsede_username", "public_key", "activation_key", "password_reset_key", "reset_expires")
from django.contrib.auth.models import User from django import forms from account.models import UserProfile attributes = {"class": "required"} class RegistrationForm(forms.Form): username = forms.RegexField(regex=r'^[\w.@+-]+$', max_length=30, widget=forms.TextInput(attrs=attributes), label="Username", error_message={'invalid': "This value may contain only letters, numbers and @.+- characters."} ) email = forms.EmailField() def clean_username(self): username = self.cleaned_data["username"] existing = User.objects.filter(username__iexact=username) if existing.exists(): raise forms.ValidationError("A user with that username already exists.") else: return self.cleaned_data["username"] class SettingsForm(forms.Form): email = forms.EmailField() xsede_username = forms.CharField(max_length=50, required=False, label="XSEDE Username") new_ssh_keypair = forms.BooleanField(required=False) def clean(self): if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError("The two password fields did not match.") return self.cleaned_data class UserProfileForm(forms.ModelForm): private_key = forms.CharField(widget=forms.Textarea) public_key = forms.CharField(widget=forms.Textarea) class Meta: model = UserProfile fields = ("xsede_username", "public_key", "activation_key", "password_reset_key", "reset_expires")
Use prop-types package in vulcan-voting
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { performVoteClient } from '../modules/vote.js'; import { VoteableCollections } from '../modules/make_voteable.js'; export const withVote = component => { return graphql(gql` mutation vote($documentId: String, $voteType: String, $collectionName: String, $voteId: String) { vote(documentId: $documentId, voteType: $voteType, collectionName: $collectionName, voteId: $voteId) { ${VoteableCollections.map(collection => ` ... on ${collection.typeName} { __typename _id currentUserVotes{ _id voteType power } baseScore score } `).join('\n')} } } `, { props: ({ownProps, mutate}) => ({ vote: ({document, voteType, collection, currentUser, voteId = Random.id()}) => { const newDocument = performVoteClient({collection, document, user: currentUser, voteType, voteId}); return mutate({ variables: { documentId: document._id, voteType, collectionName: collection.options.collectionName, voteId, }, optimisticResponse: { __typename: 'Mutation', vote: newDocument, } }) } }), })(component); }
import React, { PropTypes, Component } from 'react'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { performVoteClient } from '../modules/vote.js'; import { VoteableCollections } from '../modules/make_voteable.js'; export const withVote = component => { return graphql(gql` mutation vote($documentId: String, $voteType: String, $collectionName: String, $voteId: String) { vote(documentId: $documentId, voteType: $voteType, collectionName: $collectionName, voteId: $voteId) { ${VoteableCollections.map(collection => ` ... on ${collection.typeName} { __typename _id currentUserVotes{ _id voteType power } baseScore score } `).join('\n')} } } `, { props: ({ownProps, mutate}) => ({ vote: ({document, voteType, collection, currentUser, voteId = Random.id()}) => { const newDocument = performVoteClient({collection, document, user: currentUser, voteType, voteId}); return mutate({ variables: { documentId: document._id, voteType, collectionName: collection.options.collectionName, voteId, }, optimisticResponse: { __typename: 'Mutation', vote: newDocument, } }) } }), })(component); }
Fix path to static files
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { dist: { files: { 'src/scripts/dist/<%%= pkg.name %>.js': [ 'src/scripts/**/*.js', ] } } }, watch: { options: { livereload: true }, scripts: { files: ['src/scripts/**/*.js'], tasks: ['concat'] }, styles: { files: ['src/styles/screen.scss'], tasks: ['sass:dev'] } }, sass: { dist: { options: { style: 'compressed' }, files: { 'src/styles/dist/<%%= pkg.name %>.css': 'src/styles/screen.scss' } }, dev: { options: { style: 'expanded' }, files: { 'src/styles/dist/<%%= pkg.name %>.css': 'src/styles/screen.scss' } }, }, concat: { scripts: { files: { 'src/styles/dist/<%%= pkg.name %>.css': 'src/styles/screen.scss' } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.registerTask('default', ['sass:dist', 'uglify']); };
module.exports = function (grunt) { 'use strict'; grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), uglify: { dist: { files: { 'static/scripts/dist/<%%= pkg.name %>.js': [ 'static/scripts/**/*.js', ] } } }, watch: { options: { livereload: true }, scripts: { files: ['static/scripts/**/*.js'], tasks: ['concat'] }, styles: { files: ['static/styles/screen.scss'], tasks: ['sass:dev'] } }, sass: { dist: { options: { style: 'compressed' }, files: { 'static/styles/dist/<%%= pkg.name %>.css': 'static/styles/screen.scss' } }, dev: { options: { style: 'expanded' }, files: { 'static/styles/dist/<%%= pkg.name %>.css': 'static/styles/screen.scss' } }, }, concat: { scripts: { files: { 'static/styles/dist/<%%= pkg.name %>.css': 'static/styles/screen.scss' } } } }); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.registerTask('default', ['sass:dist', 'uglify']); };
Return an error in ChannelRequest library
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID; Promise = require('bluebird'); refreshProviderObject = null; ChannelRequest = (function() { function ChannelRequest(channelName1, callback1) { this.channelName = channelName1; this.callback = callback1; this.stopLongPolling = false; if (this.channelName == null) { throw new Error('Channel request needs of a channelName'); } if (typeof this.callback !== 'function') { throw new Error('Channel request needs of a callback function'); } } var startRefreshProvider = function(channelName, callback) { return new Promise(function(resolve, reject) { return callback(channelName, function(err) { if (err) { reject(new Error(err)); } return resolve(); }); }); }; ChannelRequest.prototype.startLongPolling = function(miliseconds) { if (!!this.stopLongPolling) { clearTimeout(timeoutID); return; } var self = this; refreshProviderObject = startRefreshProvider(this.channelName, this.callback); return refreshProviderObject.then(function() { timeoutID = setTimeout(function() { return self.startLongPolling(miliseconds); }, miliseconds); if (!!self.stopLongPolling) { clearTimeout(timeoutID); return; } }).catch(function(err) { return err; }); }; return ChannelRequest; })(); export default ChannelRequest;
var ChannelRequest, Promise, refreshProviderObject, stopLongPolling, timeoutID; Promise = require('bluebird'); refreshProviderObject = null; ChannelRequest = (function() { function ChannelRequest(channelName1, callback1) { this.channelName = channelName1; this.callback = callback1; this.stopLongPolling = false; if (this.channelName == null) { throw new Error('Channel request needs of a channelName'); } if (typeof this.callback !== 'function') { throw new Error('Channel request needs of a callback function'); } } var startRefreshProvider = function(channelName, callback) { return new Promise(function(resolve, reject) { return callback(channelName, function(err) { if (err) { reject(err); } return resolve(); }); }); }; ChannelRequest.prototype.startLongPolling = function(miliseconds) { if (!!this.stopLongPolling) { clearTimeout(timeoutID); return; } var self = this; refreshProviderObject = startRefreshProvider(this.channelName, this.callback); return refreshProviderObject.then(function() { timeoutID = setTimeout(function() { return self.startLongPolling(miliseconds); }, miliseconds); if (!!self.stopLongPolling) { clearTimeout(timeoutID); return; } }).catch(function(err) { return console.error(err); }); }; return ChannelRequest; })(); export default ChannelRequest;
[NodeBundle] Set correct typehints on methods and properties
<?php namespace Kunstmaan\NodeBundle\Event; use Kunstmaan\AdminBundle\Event\BcEvent; use Kunstmaan\NodeBundle\Entity\HasNodeInterface; use Kunstmaan\NodeBundle\Entity\Node; use Kunstmaan\NodeBundle\Entity\NodeTranslation; use Symfony\Component\HttpFoundation\Request; final class SlugSecurityEvent extends BcEvent { /** @var Node|null */ private $node; /** @var NodeTranslation|null */ private $nodeTranslation; /** @var HasNodeInterface|null */ private $entity; /** @var Request|null */ private $request; /** * @return Node|null */ public function getNode() { return $this->node; } /** * @param Node $node */ public function setNode($node) { $this->node = $node; return $this; } /** * @return NodeTranslation|null */ public function getNodeTranslation() { return $this->nodeTranslation; } /** * @param NodeTranslation $nodeTranslation */ public function setNodeTranslation($nodeTranslation) { $this->nodeTranslation = $nodeTranslation; return $this; } /** * @return HasNodeInterface|null */ public function getEntity() { return $this->entity; } /** * @param HasNodeInterface $entity */ public function setEntity($entity) { $this->entity = $entity; return $this; } /** * @return Request|null */ public function getRequest() { return $this->request; } /** * @param Request $request */ public function setRequest($request) { $this->request = $request; return $this; } }
<?php namespace Kunstmaan\NodeBundle\Event; use Kunstmaan\AdminBundle\Event\BcEvent; final class SlugSecurityEvent extends BcEvent { private $node; private $nodeTranslation; private $entity; private $request; /** * @return mixed */ public function getNode() { return $this->node; } /** * @param mixed $node */ public function setNode($node) { $this->node = $node; return $this; } /** * @return mixed */ public function getNodeTranslation() { return $this->nodeTranslation; } /** * @param mixed $nodeTranslation */ public function setNodeTranslation($nodeTranslation) { $this->nodeTranslation = $nodeTranslation; return $this; } /** * @return mixed */ public function getEntity() { return $this->entity; } /** * @param mixed $entity */ public function setEntity($entity) { $this->entity = $entity; return $this; } /** * @return mixed */ public function getRequest() { return $this->request; } /** * @param mixed $request */ public function setRequest($request) { $this->request = $request; return $this; } }
Fix module controller view instantiation example.
define([ 'spoon', './{{name}}View' ], function (spoon, {{name}}View) { 'use strict'; return spoon.Controller.extend({ $name: '{{name}}Controller', /*_defaultState: 'index', _states: { 'index': '_indexState' }*/ _view: null, //////////////////////////////////////////////////////////// /** * Constructor. * * @param {Element} element The element in which the module will work on */ initialize: function (element) { this.$super(); this._view = this._link(new {{name}}View()); this._view .appendTo(element) .render(); }, /** * Some state handler. * * @param {Object} state The state parameter bag */ /*_someState: function (state) { // The index state implementation goes here // The state might instantiate another module or simply a view // See the default ApplicationController implementation for more insight },*/ /** * {@inheritDoc} */ _onDestroy: function () { if (this._view) { this._view.destroy(); this._view = null; } this.$super(); } }); });
define([ 'spoon', './{{name}}View' ], function (spoon, {{name}}View) { 'use strict'; return spoon.Controller.extend({ $name: '{{name}}Controller', /*_defaultState: 'index', _states: { 'index': '_indexState' }*/ _view: null, //////////////////////////////////////////////////////////// /** * Constructor. */ initialize: function () { this.$super(); this._view = this._link(new {{name}}View()); this._view.render(); }, /** * Some state handler. * * @param {Object} state The state parameter bag */ /*_someState: function (state) { // The index state implementation goes here // The state might instantiate another module or simply a view // See the default ApplicationController implementation for more insight },*/ /** * {@inheritDoc} */ _onDestroy: function () { if (this._view) { this._view.destroy(); this._view = null; } this.$super(); } }); });
Add suppressing warnings for preferences activity. Change-Id: I7808e8bbc080b65017dc273e423db51c9151d9f7
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.libreoffice.impressremote.activity; import android.os.Bundle; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.actionbarsherlock.view.MenuItem; import org.libreoffice.impressremote.R; public class SettingsActivity extends SherlockPreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setUpHomeButton(); setUpPreferences(); } private void setUpHomeButton() { getSupportActionBar().setHomeButtonEnabled(true); } @SuppressWarnings("deprecation") private void setUpPreferences() { // This action is deprecated // but we still need to target pre-Honeycomb devices. addPreferencesFromResource(R.xml.preferences); } @Override public boolean onOptionsItemSelected(MenuItem aMenuItem) { switch (aMenuItem.getItemId()) { case android.R.id.home: navigateUp(); return true; default: return super.onOptionsItemSelected(aMenuItem); } } private void navigateUp() { finish(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.libreoffice.impressremote.activity; import android.os.Bundle; import com.actionbarsherlock.app.SherlockPreferenceActivity; import com.actionbarsherlock.view.MenuItem; import org.libreoffice.impressremote.R; public class SettingsActivity extends SherlockPreferenceActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setUpHomeButton(); setUpPreferences(); } private void setUpHomeButton() { getSupportActionBar().setHomeButtonEnabled(true); } private void setUpPreferences() { // This action is deprecated // but we still need to target pre-Honeycomb devices addPreferencesFromResource(R.xml.preferences); } @Override public boolean onOptionsItemSelected(MenuItem aMenuItem) { switch (aMenuItem.getItemId()) { case android.R.id.home: navigateUp(); return true; default: return super.onOptionsItemSelected(aMenuItem); } } private void navigateUp() { finish(); } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
Edit grunt command: Add --url parameter
module.exports = function (grunt) { var url = grunt.option('url') || 'http://localhost:3000'; // Project configuration. grunt.initConfig({ bowercopy: { options: { clean: true }, js: { options: { destPrefix: 'js/vendor' }, files: { 'jquery.min.js': 'jquery/dist/jquery.min.js', 'bootstrap.min.js': 'bootstrap/dist/js/bootstrap.min.js', 'easeljs-0.7.1.min.js': 'easeljs/lib/easeljs-0.7.1.min.js' } }, css: { options: { destPrefix: 'css/vendor' }, files: { 'bootstrap.min.css': 'bootstrap/dist/css/bootstrap.min.css', 'bootstrap.css.map': 'bootstrap/dist/css/bootstrap.css.map' } } }, 'string-replace': { dist: { files: { './': ['index.html', 'js/ui.js'] }, options: { replacements: [{ pattern: /http:\/\/\s*(.+?)\s*:3000/, replacement: url }] } } } }); grunt.loadNpmTasks('grunt-bowercopy'); grunt.loadNpmTasks('grunt-string-replace'); grunt.registerTask('default', ['bowercopy', 'string-replace']); };
module.exports = function (grunt) { var url = grunt.option('url') || 'http://localhost:3000'; // Project configuration. grunt.initConfig({ bowercopy: { options: { clean: false }, js: { options: { destPrefix: 'js/vendor' }, files: { 'jquery.min.js': 'jquery/dist/jquery.min.js', 'bootstrap.min.js': 'bootstrap/dist/js/bootstrap.min.js', 'easeljs-0.7.1.min.js': 'easeljs/lib/easeljs-0.7.1.min.js' } }, css: { options: { destPrefix: 'css/vendor' }, files: { 'bootstrap.min.css': 'bootstrap/dist/css/bootstrap.min.css', 'bootstrap.css.map': 'bootstrap/dist/css/bootstrap.css.map' } } }, 'string-replace': { dist: { files: { './': ['index.html', 'js/ui.js'] }, options: { replacements: [{ pattern: /http:\/\/\s*(.+?)\s*:3000/, replacement: url }] } } } }); grunt.loadNpmTasks('grunt-bowercopy'); grunt.loadNpmTasks('grunt-string-replace'); grunt.registerTask('default', ['bowercopy', 'string-replace']); };
Change count item per page
<?php namespace stepancher\content\widgets; use stepancher\content\models\Content; use yii\base\Widget; use yii\data\ActiveDataProvider; use yii\helpers\Html; /** * Class ContentOutput * отображает созданные ContentModule статьи двумя способами, * если $onlyLinks задан true то отображаются только ссылки на статьи * если false топревью статей * @package stepancher\content\widgets */ class ContentOutput extends Widget { public $onlyLinks = false; public function init() { parent::init(); } public function run() { /** @var Content $model */ $model = \Yii::$app->getModule("content")->model("Content"); $dataProvider = new ActiveDataProvider( [ 'query' => $model::find()->where('EXTRACT(epoch from date_hide) > :time or date_hide is null', ['time' => time()]) ->andWhere('EXTRACT(epoch from date_show) < :time or date_show is null', ['time' => time()]) ->andWhere('visible = true') ->orderBy('sort'), 'pagination' => [ 'pageSize' => 20, ], ] ); if ($this->onlyLinks) { return $this->render('links', ['dataProvider' => $dataProvider]); } else { return $this->render('preview', ['dataProvider' => $dataProvider]); } } }
<?php namespace stepancher\content\widgets; use stepancher\content\models\Content; use yii\base\Widget; use yii\data\ActiveDataProvider; use yii\helpers\Html; /** * Class ContentOutput * отображает созданные ContentModule статьи двумя способами, * если $onlyLinks задан true то отображаются только ссылки на статьи * если false топревью статей * @package stepancher\content\widgets */ class ContentOutput extends Widget { public $onlyLinks = false; public function init() { parent::init(); } public function run() { /** @var Content $model */ $model = \Yii::$app->getModule("content")->model("Content"); $dataProvider = new ActiveDataProvider( [ 'query' => $model::find()->where('EXTRACT(epoch from date_hide) > :time or date_hide is null', ['time' => time()]) ->andWhere('EXTRACT(epoch from date_show) < :time or date_show is null', ['time' => time()]) ->andWhere('visible = true') ->orderBy('sort'), 'pagination' => [ 'pageSize' => 2, ], ] ); if ($this->onlyLinks) { return $this->render('links', ['dataProvider' => $dataProvider]); } else { return $this->render('preview', ['dataProvider' => $dataProvider]); } } }
Add explicit reasoning for session sniff From https://vip.wordpress.com/documentation/code-review-what-we-look-for/#session_start-and-other-session-related-functions, linked in #75
<?php /** * WordPress_Sniffs_VIP_SessionVariableUsageSniff * * Discourages the use of the session variable. * Creating a session writes a file to the server and is unreliable in a multi-server environment. * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf <[email protected]> * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_VARIABLE, ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * * @todo Allow T_CONSTANT_ENCAPSED_STRING? * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) { $phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr); } }//end process() }//end class
<?php /** * WordPress_Sniffs_VIP_SessionVariableUsageSniff * * Discourages the use of the session variable * * @category PHP * @package PHP_CodeSniffer * @author Shady Sharaf <[email protected]> * @link https://github.com/WordPress-Coding-Standards/WordPress-Coding-Standards/issues/75 */ class WordPress_Sniffs_VIP_SessionVariableUsageSniff extends Generic_Sniffs_PHP_ForbiddenFunctionsSniff { /** * Returns an array of tokens this test wants to listen for. * * @return array */ public function register() { return array( T_VARIABLE, ); }//end register() /** * Processes this test, when one of its tokens is encountered. * * @param PHP_CodeSniffer_File $phpcsFile The file being scanned. * @param int $stackPtr The position of the current token * in the stack passed in $tokens. * * @todo Allow T_CONSTANT_ENCAPSED_STRING? * * @return void */ public function process(PHP_CodeSniffer_File $phpcsFile, $stackPtr) { $tokens = $phpcsFile->getTokens(); if ( $tokens[$stackPtr]['content'] == '$_SESSION' ) { $phpcsFile->addError('Usage of $_SESSION variable is prohibited.', $stackPtr); } }//end process() }//end class
Handle the --cocorico-url command line option.
# -*- coding: utf-8 -*- from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * import requests class AddCocoricoVoteVisitor(AbstractVisitor): def __init__(self, args): self.url = args.cocorico_url if not self.url: self.url = 'https://cocorico.cc' r = requests.post( self.url + '/api/oauth/token', auth=(args.cocorico_app_id, args.cocorico_secret), data={ 'grant_type': 'client_credentials' }, verify=self.url != 'https://local.cocorico.cc' ) self.access_token = r.json()['access_token'] super(AddCocoricoVoteVisitor, self).__init__() def visit_node(self, node): if not self.access_token: return # if on root node if 'parent' not in node and 'type' not in node: r = requests.post( self.url + '/api/vote', headers={'Authorization': 'Bearer ' + self.access_token}, data={ 'title': 'test de vote', 'description': 'ceci est un test', 'url': 'https://legilibre.fr/?test=49' }, verify=self.url != 'https://local.cocorico.cc' ) node['cocoricoVote'] = r.json()['vote']['id']
# -*- coding: utf-8 -*- from AbstractVisitor import AbstractVisitor from duralex.alinea_parser import * import requests class AddCocoricoVoteVisitor(AbstractVisitor): def __init__(self, args): self.url = 'https://local.cocorico.cc' r = requests.post( self.url + '/api/oauth/token', auth=(args.cocorico_app_id, args.cocorico_secret), data={ 'grant_type': 'client_credentials' }, verify=self.url != 'https://local.cocorico.cc' ) self.access_token = r.json()['access_token'] super(AddCocoricoVoteVisitor, self).__init__() def visit_node(self, node): if not self.access_token: return # if on root node if 'parent' not in node and 'type' not in node: r = requests.post( self.url + '/api/vote', headers={'Authorization': 'Bearer ' + self.access_token}, data={ 'title': 'test de vote', 'description': 'ceci est un test', 'url': 'https://legilibre.fr/?test=49' }, verify=self.url != 'https://local.cocorico.cc' ) node['cocoricoVote'] = r.json()['vote']['id']
Tweak comment about 202 response
"""Implement a server to check if a contribution is covered by a CLA(s).""" from aiohttp import web from . import abc from . import ContribHost from . import ServerHost from . import CLAHost class Handler: """Handle requests from the contribution host.""" def __init__(self, server: ServerHost, cla_records: CLAHost): self.server = server self.cla_records = cla_records async def respond(request: web.Request) -> web.StreamResponse: # XXX untested """Handle a webhook trigger from the contribution host.""" try: contribution = ContribHost.process(request) usernames = await contribution.usernames() # XXX not implemented cla_status = await self.cla_records.check(usernames) # XXX not implemented # With a work queue, one could make the updating of the # contribution a work item and return an HTTP 202 response. return (await contribution.update(cla_status)) # XXX not implemented except abc.ResponseExit as exc: return exc.response except Exception as exc: self.server.log(exc) return web.Response( status=http.HTTPStatus.INTERNAL_SERVER_ERROR.value) if __name__ == '__main__': server = ServerHost() cla_records = CLAHost() handler = Handler(server, cla_records) app = web.Application() app.router.add_route(*ContribHost.route, handler.respond) web.run_app(app, port=server.port())
"""Implement a server to check if a contribution is covered by a CLA(s).""" from aiohttp import web from . import abc from . import ContribHost from . import ServerHost from . import CLAHost class Handler: """Handle requests from the contribution host.""" def __init__(self, server: ServerHost, cla_records: CLAHost): self.server = server self.cla_records = cla_records async def respond(request: web.Request) -> web.StreamResponse: # XXX untested """Handle a webhook trigger from the contribution host.""" try: contribution = ContribHost.process(request) usernames = await contribution.usernames() # XXX not implemented cla_status = await self.cla_records.check(usernames) # XXX not implemented # With a background queue, one could add the update as a work item # and return an HTTP 202 response. return (await contribution.update(cla_status)) # XXX not implemented except abc.ResponseExit as exc: return exc.response except Exception as exc: self.server.log(exc) return web.Response( status=http.HTTPStatus.INTERNAL_SERVER_ERROR.value) if __name__ == '__main__': server = ServerHost() cla_records = CLAHost() handler = Handler(server, cla_records) app = web.Application() app.router.add_route(*ContribHost.route, handler.respond) web.run_app(app, port=server.port())
Set up dummy bot response
<?php namespace App\Http\Controllers; use App\Http\Middleware\EventsMiddleware; use GuzzleHttp\Client; use Illuminate\Http\Request; use Storage; class BotController extends Controller { /** * Ensures the app has been verified and the token is correct */ function __construct() { $this->middleware(EventsMiddleware::class); } /** * Handles events received from Slack */ public function receive(Request $request) { response('', 200); $text=$request->input('event.text'); if (parseText($text)['type']=='add') { $data['text'] = "Done! See all your team's links here. :blush:"; $data['channel'] = $request->input('event'.channel'); $data['response_type'] = "saved"; respond($data); } } /** * Posts responses to Slack */ public function respond(array $data) { //if ($data['response_type'] == 'saved') $client=new Client(); $client->request('GET', 'https://slack.com/api/chat.postMessage', ['query' => [ 'token' => Storage::get('bot_token.dat'), 'channel'=> $data['channel'], 'text' => $data['text']]]); } public function parseText($text) { $tokens=explode(' ', $text); if($tokens[0]=="@linxer") { if($tokens[1]=="add" || $tokens[1]=="save") { return array( 'type' => 'add', 'link' => $tokens[2], 'tags' => array_slice($tokens, 3)); } else if ($tokens[1]=="find" || $tokens[1]=="search") { return array( 'type' => 'search' 'query_terms' => array_slice($tokens, 2)); } } } }
<?php namespace App\Http\Controllers; use App\Http\Middleware\EventsMiddleware; use Illuminate\Http\Request; class BotController extends Controller { /** * Ensures the app has been verified and the token is correct */ function __construct() { $this->middleware(EventsMiddleware::class); } /** * Handles events received from Slack */ public function receive() { } /** * Posts responses to Slack */ public function respond() { } public function parseText($text) { $tokens=explode(' ', $text); if($tokens[0]=="@linxer") { if($tokens[1]=="add" || $tokens[1]=="save") { return array( 'type' => 'add', 'link' => $tokens[2], 'tags' => array_slice($tokens, 3)); } else if ($tokens[1]=="find" || $tokens[1]=="search") { return array( 'type' => 'search' 'query_terms' => array_slice($tokens, 2)); } } } }
Use fancy spelling of resume
<?php Loader::load('controller', '/PageController'); abstract class DefaultPageController extends PageController { public function __construct() { parent::__construct(); $this->add_css('reset'); $this->add_css('portfolio'); } protected function set_body_data() { $this->set_body('header_data', [ 'menu' => $this->get_menu(), 'home_link' => Loader::getRootURL(), ]); $this->set_body('activity_array', $this->get_recent_activity()); $this->set_body_view('Page'); } protected function get_menu() { $menu = [ [ 'name' => 'About', 'link' => Loader::getRootURL(), ], [ 'name' => 'Projects', 'link' => Loader::getRootURL() . 'projects/', ], [ 'name' => 'Résumé', 'link' => Loader::getRootURL() . 'resume/', ], [ 'name' => 'Contact', 'link' => Loader::getRootURL() . 'contact/', ], ]; if (!URLDecode::getPiece(1)) { $active_page = 'About'; } else { $active_page = ucfirst(URLDecode::getPiece(1)); } return array_map(function ($row) use ($active_page) { $row = (object) $row; $row->active = ($row->name == $active_page); return $row; }, $menu); } }
<?php Loader::load('controller', '/PageController'); abstract class DefaultPageController extends PageController { public function __construct() { parent::__construct(); $this->add_css('reset'); $this->add_css('portfolio'); } protected function set_body_data() { $this->set_body('header_data', [ 'menu' => $this->get_menu(), 'home_link' => Loader::getRootURL(), ]); $this->set_body('activity_array', $this->get_recent_activity()); $this->set_body_view('Page'); } protected function get_menu() { $menu = [ [ 'name' => 'About', 'link' => Loader::getRootURL(), ], [ 'name' => 'Projects', 'link' => Loader::getRootURL() . 'projects/', ], [ 'name' => 'Resume', 'link' => Loader::getRootURL() . 'resume/', ], [ 'name' => 'Contact', 'link' => Loader::getRootURL() . 'contact/', ], ]; if (!URLDecode::getPiece(1)) { $active_page = 'About'; } else { $active_page = ucfirst(URLDecode::getPiece(1)); } return array_map(function ($row) use ($active_page) { $row = (object) $row; $row->active = ($row->name == $active_page); return $row; }, $menu); } }
Fix typo in template definition
function maReferenceManyField(ReferenceRefresher) { 'use strict'; return { scope: { 'field': '&', 'value': '=', 'entry': '=?', 'datastore': '&?' }, restrict: 'E', link: function(scope) { var field = scope.field(); scope.name = field.name(); scope.v = field.validation(); scope.choices = []; function refresh(search) { return ReferenceRefresher.refresh(field, scope.value, search) .then(formattedResults => { scope.$broadcast('choices:update', { choices: formattedResults }); }); } // if value is set, we should retrieve references label from server if (scope.value && scope.value.length) { ReferenceRefresher.getInitialChoices(field, scope.value) .then(options => { scope.$broadcast('choices:update', { choices: options }); if (field.remoteComplete()) { scope.refresh = refresh; } else { refresh(); } }); } else { if (field.remoteComplete()) { scope.refresh = refresh; } else { refresh(); } } }, template: `<ma-choices-field field="field()" datastore="datastore()" refresh="refresh($search)" value="value"> </ma-choices-field>` }; } maReferenceManyField.$inject = ['ReferenceRefresher']; module.exports = maReferenceManyField;
function maReferenceManyField(ReferenceRefresher) { 'use strict'; return { scope: { 'field': '&', 'value': '=', 'entry': '=?', 'datastore': '&?' }, restrict: 'E', link: function(scope) { var field = scope.field(); scope.name = field.name(); scope.v = field.validation(); scope.choices = []; function refresh(search) { return ReferenceRefresher.refresh(field, scope.value, search) .then(formattedResults => { scope.$broadcast('choices:update', { choices: formattedResults }); }); } // if value is set, we should retrieve references label from server if (scope.value && scope.value.length) { ReferenceRefresher.getInitialChoices(field, scope.value) .then(options => { scope.$broadcast('choices:update', { choices: options }); if (field.remoteComplete()) { scope.refresh = refresh; } else { refresh(); } }); } else { if (field.remoteComplete()) { scope.refresh = refresh; } else { refresh(); } } }, template: `<ma-choices-field field="field()" datastore="datastore()" refresh="refresh($search)" value="value"> </ma-choice-field>` }; } maReferenceManyField.$inject = ['ReferenceRefresher']; module.exports = maReferenceManyField;
Add environment support and tuneup Finder
<?php namespace Knp\RadBundle\DataFixtures\ORM; use Knp\RadBundle\DataFixtures\AbstractFixture; use Symfony\Component\Finder\Finder; use Doctrine\Common\Persistence\ObjectManager; use Nelmio\Alice\Fixtures; class LoadAliceFixtures extends AbstractFixture { public function load(ObjectManager $manager) { $env = $this->continaer->getParameter('kernel.environment'); $bundles = $this->container->getParameter('kernel.bundles'); if (!isset($bundles['App'])) { return; } $refl = new \ReflectionClass($bundles['App']); if (class_exists($refl->getNamespaceName().'\\DataFixtures\\ORM\\LoadAliceFixtures')) { return; } $path = dirname($refl->getFileName()).DIRECTORY_SEPARATOR.'Resources'. DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'orm'; foreach ($this->getAliceFiles($path, $env) as $file) { Fixtures::load($file, $manager, $this->getAliceOptions()); } } protected function getAliceFiles($path, $environment) { $paths = array(); if (is_dir($path)) { $paths[] = $path; } if (is_dir($path.DIRECTORY_SEPARATOR.$environment)) { $paths[] = $path.DIRECTORY_SEPARATOR.$environment; } if (0 == count($paths)) { return array(); } return Finder::create() ->files() ->name('*.yml') ->depth(1) ->sortByName() ->in($paths) ; } protected function getAliceOptions() { return array('providers' => array($this)); } }
<?php namespace Knp\RadBundle\DataFixtures\ORM; use Knp\RadBundle\DataFixtures\AbstractFixture; use Symfony\Component\Finder\Finder; use Doctrine\Common\Persistence\ObjectManager; use Nelmio\Alice\Fixtures; class LoadAliceFixtures extends AbstractFixture { public function load(ObjectManager $manager) { $bundles = $this->container->getParameter('kernel.bundles'); if (!isset($bundles['App'])) { return; } $refl = new \ReflectionClass($bundles['App']); if (class_exists($refl->getNamespaceName().'\\DataFixtures\\ORM\\LoadAliceFixtures')) { return; } $path = dirname($refl->getFileName()).DIRECTORY_SEPARATOR.'Resources'. DIRECTORY_SEPARATOR.'fixtures'.DIRECTORY_SEPARATOR.'orm'; foreach ($this->getAliceFiles($path) as $file) { Fixtures::load($file, $manager, $this->getAliceOptions()); } } protected function getAliceFiles($path) { if (!is_dir($path)) { return array(); } return Finder::create()->files()->name('*.yml')->in($path); } protected function getAliceOptions() { return array('providers' => array($this)); } }
Remove upper case Not Present
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
from django import forms from datasets.models import DatasetRelease, CategoryComment class DatasetReleaseForm(forms.ModelForm): max_number_of_sounds = forms.IntegerField(required=False) class Meta: model = DatasetRelease fields = ['release_tag', 'type'] class PresentNotPresentUnsureForm(forms.Form): vote = forms.ChoiceField( required=True, widget=forms.RadioSelect, choices=( ('1', 'Present and predominant',), ('0.5', 'Present but not predominant',), ('-1', 'Not Present',), ('0', 'Unsure',), ), ) annotation_id = forms.IntegerField( required=True, widget=forms.HiddenInput, ) visited_sound = forms.BooleanField( required=False, initial=False, widget=forms.HiddenInput, ) class CategoryCommentForm(forms.ModelForm): class Meta: model = CategoryComment fields = ['comment', 'category_id', 'dataset'] widgets = { 'comment': forms.Textarea(attrs={ 'cols': 80, 'rows': 3, 'placeholder': 'Add here any general comments you want to make about this category'}), 'category_id': forms.HiddenInput, 'dataset_id': forms.HiddenInput, }
Update task 5.3 lesson 1
package ru.spoddubnyak; public class ArrayRemovingDuplicates { public String[] sourceArray; public ArrayRemovingDuplicates(String[] sourceArray){ this.sourceArray = sourceArray; } public int removeDuplicates () { int countDuplication = 0; for (int i = 0; i < this.sourceArray.length - 1; i++) { if (null != this.sourceArray[i]) { for (int j = 1 + i; j < this.sourceArray.length; j++) { if (this.sourceArray[i].equals(this.sourceArray[j])) { this.sourceArray[j] = null; countDuplication++; } } } } return countDuplication; } public String[] createResultArray(int inCountDuplication) { String[] resultArray = new String[this.sourceArray.length - inCountDuplication]; int j = 0; for (int i = 0; i < this.sourceArray.length; i++) { if (null != sourceArray[i]) { resultArray[j] = this.sourceArray[i]; j++; } } return resultArray; } }
package ru.spoddubnyak; public class ArrayRemovingDuplicates { public String[] sourceArray; public ArrayRemovingDuplicates(String[] sourceArray){ this.sourceArray = sourceArray; } public int removeDuplicates () { int countDuplication = 0; for (int i = 0; i < this.sourceArray.length - 1; i++) { if (null != this.sourceArray[i]) { for (int j = 1 + i; j < this.sourceArray.length; j++) { if (this.sourceArray[i] == this.sourceArray[j]) { this.sourceArray[j] = null; countDuplication++; } } } } return countDuplication; } public String[] createResultArray(int inCountDuplication) { String[] resultArray = new String[this.sourceArray.length - inCountDuplication]; int j = 0; for (int i = 0; i < this.sourceArray.length; i++) { if (null != sourceArray[i]) { resultArray[j] = this.sourceArray[i]; j++; } } return resultArray; } }
Fix template path getter syntax Test #1208 git-svn-id: 28fe03dfd74dd77dcc8ecfe99fabcec8eed81bba@3763 8555b757-d854-4b86-925a-82fd84c90ff4
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="<?php echo Lang::getCode() ?>" xml:lang="<?php echo Lang::getCode() ?>"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo htmlspecialchars(Config::get('site_name')); ?></title> <?php GUI::includeStylesheets() ?> <?php GUI::includeFavicon() ?> <?php GUI::includeScripts() ?> <script type="text/javascript" src="{path:filesender-config.js.php}"></script> <script type="text/javascript" src="{path:rest.php/lang?callback=lang.setTranslations}"></script> <meta name="robots" content="noindex, nofollow" /> <meta name="auth" content="noindex, nofollow" /> </head> <body data-security-token="<?php echo Utilities::getSecurityToken() ?>" data-auth-type="<?php echo Auth::type() ?>"> <div id="wrap"> <div id="header"> <a href="<?php echo GUI::path() ?>"> <?php GUI::includeLogo() ?> <?php if(Config::get('site_name_in_header')) { ?> <div class="site_name"><?php echo Config::get('site_name') ?></div> <div class="site_baseline"><?php echo Config::get('site_baseline') ?></div> <?php } ?> </a> </div>
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" lang="<?php echo Lang::getCode() ?>" xml:lang="<?php echo Lang::getCode() ?>"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title><?php echo htmlspecialchars(Config::get('site_name')); ?></title> <?php GUI::includeStylesheets() ?> <?php GUI::includeFavicon() ?> <?php GUI::includeScripts() ?> <script type="text/javascript" src="<?php echo GUI::path('filesender-config.js.php') ?>?v=<?php echo Utilities::runningInstanceUID() ?>"></script> <script type="text/javascript" src="<?php echo GUI::path('rest.php/lang') ?>?callback=lang.setTranslations&amp;v=<?php echo Utilities::runningInstanceUID() ?>"></script> <meta name="robots" content="noindex, nofollow" /> <meta name="auth" content="noindex, nofollow" /> </head> <body data-security-token="<?php echo Utilities::getSecurityToken() ?>" data-auth-type="<?php echo Auth::type() ?>"> <div id="wrap"> <div id="header"> <a href="<?php echo GUI::path() ?>"> <?php GUI::includeLogo() ?> <?php if(Config::get('site_name_in_header')) { ?> <div class="site_name"><?php echo Config::get('site_name') ?></div> <div class="site_baseline"><?php echo Config::get('site_baseline') ?></div> <?php } ?> </a> </div>
Fix imports for the ListMessagesFiltered example.
import com.messagebird.MessageBirdClient; import com.messagebird.MessageBirdService; import com.messagebird.MessageBirdServiceImpl; import com.messagebird.exceptions.GeneralException; import com.messagebird.exceptions.UnauthorizedException; import com.messagebird.objects.MessageList; import java.util.LinkedHashMap; import java.util.Map; public class ExampleListMessagesFiltered { public static void main(String[] args) { if (args.length == 0) { System.out.println("Please specify your access key example : java -jar <this jar file> test_accesskey"); return; } // First create your service object final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); // Add the service to the client final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { // Get list of messages with offset and limit System.out.println("Retrieving message list"); // Create filters Map<String, Object> filters = new LinkedHashMap<>(); filters.put("status", "scheduled"); final MessageList messageList = messageBirdClient.listMessagesFiltered(3, null, filters); // Display messages System.out.println(messageList.toString()); } catch (UnauthorizedException | GeneralException exception) { if (exception.getErrors() != null) { System.out.println(exception.getErrors().toString()); } exception.printStackTrace(); } } }
import com.messagebird.MessageBirdClient; import com.messagebird.MessageBirdService; import com.messagebird.MessageBirdServiceImpl; import com.messagebird.exceptions.GeneralException; import com.messagebird.exceptions.UnauthorizedException; import com.messagebird.objects.MessageList; public class ExampleListMessagesFiltered { public static void main(String[] args) { if (args.length == 0) { System.out.println("Please specify your access key example : java -jar <this jar file> test_accesskey"); return; } // First create your service object final MessageBirdService wsr = new MessageBirdServiceImpl(args[0]); // Add the service to the client final MessageBirdClient messageBirdClient = new MessageBirdClient(wsr); try { // Get list of messages with offset and limit System.out.println("Retrieving message list"); // Create filters Map<String, Object> filters = new LinkedHashMap<>(); filters.put("status", "scheduled"); final MessageList messageList = messageBirdClient.listMessagesFiltered(3, null, filters); // Display messages System.out.println(messageList.toString()); } catch (UnauthorizedException | GeneralException exception) { if (exception.getErrors() != null) { System.out.println(exception.getErrors().toString()); } exception.printStackTrace(); } } }
Put .tabs__panels on correct element
import React, { Component, PropTypes } from 'react'; import Panel from './Panel'; import idSafeName from '../helpers/idSafeName'; class Panels extends Component { render () { const { data, selectedIndex } = this.props; if (!data.length) { return null; } return ( <div className="tabs__panels"> {data.map((panel, index) => { const id = idSafeName(panel.label, index); return ( <Panel key={id} content={panel.content} id={id} index={index} selectedIndex={selectedIndex} /> ); })} </div> ); } } Panels.propTypes = { data: PropTypes.array, selectedIndex: PropTypes.number }; export default Panels;
import React, { Component, PropTypes } from 'react'; import Panel from './Panel'; import idSafeName from '../helpers/idSafeName'; class Panels extends Component { render () { const { data, selectedIndex } = this.props; if (!data.length) { return null; } return ( <div> {data.map((panel, index) => { const id = idSafeName(panel.label, index); return ( <Panel key={id} className="tabs__panels" content={panel.content} id={id} index={index} selectedIndex={selectedIndex} /> ); })} </div> ); } } Panels.propTypes = { data: PropTypes.array, selectedIndex: PropTypes.number }; export default Panels;
Add all javascript sources to server-watcher.
module.exports = function(grunt) { "use strict"; // Project configuration. grunt.initConfig({ pkg: '<json:package.json>', test: { files: ['test/**/*.js'] }, lint: { files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'default' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, es5: true }, globals: { exports: true } }, server: { app: { src: './lib/server.js', port: 8000, watch: './lib/**/*.js' } } }); grunt.loadNpmTasks('grunt-hustler'); // Default task. grunt.registerTask('default', 'lint test'); grunt.registerTask('dev', 'lint test watch'); };
module.exports = function(grunt) { "use strict"; // Project configuration. grunt.initConfig({ pkg: '<json:package.json>', test: { files: ['test/**/*.js'] }, lint: { files: ['grunt.js', 'lib/**/*.js', 'test/**/*.js'] }, watch: { files: '<config:lint.files>', tasks: 'default' }, jshint: { options: { curly: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, node: true, es5: true }, globals: { exports: true } }, server: { app: { src: './lib/server.js', port: 8000, watch: './lib/letternode.js' } } }); grunt.loadNpmTasks('grunt-hustler'); // Default task. grunt.registerTask('default', 'lint test'); grunt.registerTask('dev', 'lint test watch'); };
Use actual value in queries rather than object-cast-to-string
<?php namespace OpenConext\EngineBlockBundle\Authentication\Repository; use Doctrine\ORM\EntityRepository; use OpenConext\EngineBlock\Authentication\Value\CollabPersonId; use OpenConext\EngineBlockBundle\Authentication\Entity\User; /** * */ class UserRepository extends EntityRepository { /** * @param User $user */ public function save(User $user) { $this->getEntityManager()->persist($user); $this->getEntityManager()->flush(); } /** * @param CollabPersonId $collabPersonId * @return null|User * @throws \Doctrine\ORM\NonUniqueResultException */ public function findByCollabPersonId(CollabPersonId $collabPersonId) { return $this ->createQueryBuilder('u') ->where('u.collabPersonId = :collabPersonId') ->setParameter('collabPersonId', $collabPersonId->getCollabPersonId()) ->getQuery() ->getOneOrNullResult(); } /** * @param CollabPersonId $collabPersonId */ public function deleteUserWithCollabPersonId(CollabPersonId $collabPersonId) { $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $queryBuilder ->delete($this->_entityName, 'u') ->where('u.collabPersonId = :collabPersonId') ->setParameter('collabPersonId', $collabPersonId->getCollabPersonId()) ->getQuery() ->execute(); $this->getEntityManager()->flush(); } }
<?php namespace OpenConext\EngineBlockBundle\Authentication\Repository; use Doctrine\ORM\EntityRepository; use OpenConext\EngineBlock\Authentication\Value\CollabPersonId; use OpenConext\EngineBlockBundle\Authentication\Entity\User; /** * */ class UserRepository extends EntityRepository { /** * @param User $user */ public function save(User $user) { $this->getEntityManager()->persist($user); $this->getEntityManager()->flush(); } /** * @param CollabPersonId $collabPersonId * @return null|User * @throws \Doctrine\ORM\NonUniqueResultException */ public function findByCollabPersonId(CollabPersonId $collabPersonId) { return $this ->createQueryBuilder('u') ->where('u.collabPersonId = :collabPersonId') ->setParameter('collabPersonId', $collabPersonId) ->getQuery() ->getOneOrNullResult(); } /** * @param CollabPersonId $collabPersonId */ public function deleteUserWithCollabPersonId(CollabPersonId $collabPersonId) { $queryBuilder = $this->getEntityManager()->createQueryBuilder(); $queryBuilder ->delete($this->_entityName, 'u') ->where('u.collabPersonId = :collabPersonId') ->setParameter('collabPersonId', $collabPersonId) ->getQuery() ->execute(); $this->getEntityManager()->flush(); } }
Add handling for multi-tenancy in sitemap.xml
from django.contrib.sitemaps import Sitemap from django.contrib.sites.models import Site from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.sites import current_site_id from mezzanine.utils.urls import home_slug blog_installed = "mezzanine.blog" in settings.INSTALLED_APPS if blog_installed: from mezzanine.blog.models import BlogPost class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``, excluding those that point to external sites. """ # Fake homepage object. home = Displayable() setattr(home, "get_absolute_url", home_slug) items = {home.get_absolute_url(): home} for model in get_models(): if issubclass(model, Displayable): for item in (model.objects.published() .exclude(slug__startswith="http://") .exclude(slug__startswith="https://")): items[item.get_absolute_url()] = item return items.values() def lastmod(self, obj): if blog_installed and isinstance(obj, BlogPost): return obj.publish_date def get_urls(self, **kwargs): """ Ensure the correct host by injecting the current site. """ kwargs["site"] = Site.objects.get(id=current_site_id()) return super(DisplayableSitemap, self).get_urls(**kwargs)
from django.contrib.sitemaps import Sitemap from django.db.models import get_models from mezzanine.conf import settings from mezzanine.core.models import Displayable from mezzanine.utils.urls import home_slug blog_installed = "mezzanine.blog" in settings.INSTALLED_APPS if blog_installed: from mezzanine.blog.models import BlogPost class DisplayableSitemap(Sitemap): """ Sitemap class for Django's sitemaps framework that returns all published items for models that subclass ``Displayable``. """ def items(self): """ Return all published items for models that subclass ``Displayable``, excluding those that point to external sites. """ # Fake homepage object. home = Displayable() setattr(home, "get_absolute_url", home_slug) items = {home.get_absolute_url(): home} for model in get_models(): if issubclass(model, Displayable): for item in (model.objects.published() .exclude(slug__startswith="http://") .exclude(slug__startswith="https://")): items[item.get_absolute_url()] = item return items.values() def lastmod(self, obj): if blog_installed and isinstance(obj, BlogPost): return obj.publish_date
Simplify existing day 1 loop
package day01; import common.BaseSolution; import common.InputReader; public class Solution extends BaseSolution implements common.Solution { public static void main(String[] args) { new Solution().run(); } class BaseFuelCalculator { public int calculateFuel() { int mass, totalFuel = 0; InputReader reader = getInputReader(); String line = reader.next(); while (line != null) { mass = Integer.parseInt(line); totalFuel += getFuel(mass); line = reader.next(); } return totalFuel; } protected int getFuelForMass(int mass) { return mass / 3 - 2; } protected int getFuel(int mass) { return 0; } } class Part1FuelCalculator extends BaseFuelCalculator { protected int getFuel(int mass) { return getFuelForMass(mass); } } class Part2FuelCalculator extends BaseFuelCalculator { protected int getFuel(int mass) { int fuel = 0; int fuelPiece = getFuelForMass(mass); while (fuelPiece > 0) { fuel += fuelPiece; fuelPiece = getFuelForMass(fuelPiece); } return fuel; } } public String part1() { return String.valueOf(new Part1FuelCalculator().calculateFuel()); } public String part2() { return String.valueOf(new Part2FuelCalculator().calculateFuel()); } }
package day01; import common.BaseSolution; import common.InputReader; public class Solution extends BaseSolution implements common.Solution { public static void main(String[] args) { new Solution().run(); } class BaseFuelCalculator { public int calculateFuel() { int mass, totalFuel = 0; InputReader reader = getInputReader(); String line = reader.next(); while (line != null) { mass = Integer.parseInt(line); totalFuel += getFuel(mass); line = reader.next(); } return totalFuel; } protected int getFuelForMass(int mass) { return mass / 3 - 2; } protected int getFuel(int mass) { return 0; } } class Part1FuelCalculator extends BaseFuelCalculator { protected int getFuel(int mass) { return getFuelForMass(mass); } } class Part2FuelCalculator extends BaseFuelCalculator { protected int getFuel(int mass) { int fuel = 0; int fuelPiece = mass; do { fuelPiece = getFuelForMass(fuelPiece); if (fuelPiece > 0) { fuel += fuelPiece; } } while (fuelPiece > 0); return fuel; } } public String part1() { return String.valueOf(new Part1FuelCalculator().calculateFuel()); } public String part2() { return String.valueOf(new Part2FuelCalculator().calculateFuel()); } }
Make stories a little more consistent
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { checkA11y } from 'storybook-addon-a11y'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, boolean } from '@storybook/addon-knobs/react'; import styles from '@sambego/storybook-styles'; import { Store, State } from '@sambego/storybook-state'; import { RadioGroup, RadioButton } from '../components'; import { baseStyles, centerStyles } from '../.storybook/styles'; const sizes = ['small', 'medium', 'large']; const store = new Store({ value: 'small', }); const updateState = value => { store.set({ value }); action(`Selected: ${value}`)(); }; storiesOf('Radio', module) .addDecorator((story, context) => withInfo('common info')(story)(context)) .addDecorator(checkA11y) .addDecorator(withKnobs) .addDecorator(styles({ ...baseStyles, ...centerStyles })) .add('Sizes', () => ( <State store={store}> <RadioGroup name="stringValue" onChange={updateState}> {sizes.map((size, key) => ( <RadioButton key={key} size={size} marginVertical={3} label={`I'm a ${size} radio`} value={size} disabled={boolean('Disabled', false)} /> ))} </RadioGroup> </State> ));
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { checkA11y } from 'storybook-addon-a11y'; import { withInfo } from '@storybook/addon-info'; import { withKnobs, boolean } from '@storybook/addon-knobs/react'; import styles from '@sambego/storybook-styles'; import { Store, State } from '@sambego/storybook-state'; import { RadioGroup, RadioButton } from '../components'; import { baseStyles, centerStyles } from '../.storybook/styles'; const sizes = ['small', 'medium', 'large']; const store = new Store({ value: 'option1', }); const updateState = value => { store.set({ value }); action(`Selected: ${value}`)(); }; storiesOf('Radio', module) .addDecorator((story, context) => withInfo('common info')(story)(context)) .addDecorator(checkA11y) .addDecorator(withKnobs) .addDecorator(styles({ ...baseStyles, ...centerStyles })) .add('Sizes', () => ( <State store={store}> <RadioGroup name="stringValue" onChange={updateState}> {sizes.map((size, key) => ( <RadioButton key={key} size={size} marginVertical={3} label={`Option ${key+1}`} value={`option${key+1}`} disabled={boolean('Disabled', false)} /> ))} </RadioGroup> </State> ));
Enable debug logging via server.log(tags,...) when NODE_ENV=dev
'use strict'; const Config = require('./config'); // Glue manifest module.exports = { server: { app: { config: Config } }, connections: [ { host: Config.server.boilerplateApi.host, port: Config.server.boilerplateApi.port, labels: 'boilerplate-api', routes: { cors: true } } ], registrations: [ { plugin: { register: 'dogwater', options: Config.dogwater } }, { plugin: { register: 'poop', options: Config.poop } }, { plugin: { register: 'bassmaster', options: { batchEndpoint: '/', tags: ['bassmaster'] } } }, { plugin: { register: './boilerplate-swagger' } }, { plugin: { register: '../lib' }, options: { select: 'boilerplate-api' } } ] }; if( process.env.NODE_ENV == 'dev' ){ module.exports.server.debug = { log: ['error', 'implementation', 'internal'], request: ['error', 'implementation', 'internal'] }; }
'use strict'; const Config = require('./config'); // Glue manifest module.exports = { server: { app: { config: Config } }, connections: [ { host: Config.server.boilerplateApi.host, port: Config.server.boilerplateApi.port, labels: 'boilerplate-api', routes: { cors: true } } ], registrations: [ { plugin: { register: 'dogwater', options: Config.dogwater } }, { plugin: { register: 'poop', options: Config.poop } }, { plugin: { register: 'bassmaster', options: { batchEndpoint: '/', tags: ['bassmaster'] } } }, { plugin: { register: './boilerplate-swagger' } }, { plugin: { register: '../lib' }, options: { select: 'boilerplate-api' } } ] };
Make version format PEP 440 compatible
import collections import re import sys __version__ = '0.1.2' version = __version__ + ' , Python ' + sys.version VersionInfo = collections.namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'c': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError("Invalid package version {}".format(ver)) version_info = _parse_version(__version__) from .server import RESTServer from .request import Request, Response from .errors import RESTError, JsonDecodeError, JsonLoadError # make pyflakes happy (RESTServer, Request, Response, RESTError, JsonDecodeError, JsonLoadError)
import collections import re import sys __version__ = '0.1.2' version = __version__ + ' , Python ' + sys.version VersionInfo = collections.namedtuple('VersionInfo', 'major minor micro releaselevel serial') def _parse_version(ver): RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.' '(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$') match = re.match(RE, ver) try: major = int(match.group('major')) minor = int(match.group('minor')) micro = int(match.group('micro')) levels = {'rc': 'candidate', 'a': 'alpha', 'b': 'beta', None: 'final'} releaselevel = levels[match.group('releaselevel')] serial = int(match.group('serial')) if match.group('serial') else 0 return VersionInfo(major, minor, micro, releaselevel, serial) except Exception: raise ImportError("Invalid package version {}".format(ver)) version_info = _parse_version(__version__) from .server import RESTServer from .request import Request, Response from .errors import RESTError, JsonDecodeError, JsonLoadError # make pyflakes happy (RESTServer, Request, Response, RESTError, JsonDecodeError, JsonLoadError)
[caps] Mark CAPA= as None instead of True
#!/usr/bin/env python3 # Written by Daniel Oaks <[email protected]> # Released under the ISC license from .utils import CaseInsensitiveDict, CaseInsensitiveList class Capabilities: """Ingests sets of client capabilities and provides access to them.""" def __init__(self, wanted=[]): self.available = CaseInsensitiveDict() self.wanted = CaseInsensitiveList(wanted) self.enabled = CaseInsensitiveList() def ingest(self, cmd, parameters): cmd = cmd.casefold() if cmd == 'ls': caps = parameters[0].split(' ') for cap in caps: # strip first initial =/~ if cap.startswith('=') or cap.startswith('~'): cap = cap[1:] if '=' in cap: cap, value = cap.rsplit('=', 1) if value = '': value = None else: value = True self.available[cap] = value @property def to_enable(self): l = [] for cap in self.wanted: if cap in self.available and cap not in self.enabled: l.append(cap) return l def get(self, key, default=None): return self._dict.get(key, default)
#!/usr/bin/env python3 # Written by Daniel Oaks <[email protected]> # Released under the ISC license from .utils import CaseInsensitiveDict, CaseInsensitiveList class Capabilities: """Ingests sets of client capabilities and provides access to them.""" def __init__(self, wanted=[]): self.available = CaseInsensitiveDict() self.wanted = CaseInsensitiveList(wanted) self.enabled = CaseInsensitiveList() def ingest(self, cmd, parameters): cmd = cmd.casefold() if cmd == 'ls': caps = parameters[0].split(' ') for cap in caps: # strip first initial =/~ if cap.startswith('=') or cap.startswith('~'): cap = cap[1:] if '=' in cap: cap, value = cap.rsplit('=', 1) else: value = True self.available[cap] = value @property def to_enable(self): l = [] for cap in self.wanted: if cap in self.available and cap not in self.enabled: l.append(cap) return l def get(self, key, default=None): return self._dict.get(key, default)
Use Facade to access method instead of creating a new instance.
<?php namespace DvK\Laravel\Vat; use Illuminate\Contracts\Container\Container; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator as RequestValidator; use DvK\Laravel\Vat\Facades\Validator as ValidatorFacade; class VatServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { RequestValidator::extend('vat_number', function($attribute, $value, $parameters, $validator ) { return ValidatorFacade::validate( $value ); }); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton( Validator::class, function (Container $app) { return new Validator(); }); $this->app->singleton( Rates::class, function (Container $app) { $defaultCacheDriver = $app['cache']->getDefaultDriver(); $cacheDriver = $app['cache']->driver( $defaultCacheDriver ); return new Rates( $cacheDriver ); }); } /** * Get the services provided by the provider. * * @return string[] */ public function provides() { return [ 'DvK\Laravel\Vat\Validator', 'DvK\Laravel\Vat\Rates', ]; } }
<?php namespace DvK\Laravel\Vat; use Illuminate\Contracts\Container\Container; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Validator as RequestValidator; class VatServiceProvider extends ServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { RequestValidator::extend('vat_number', function($attribute, $value, $parameters, $validator ) { $vatValidator = new Validator(); $data = $validator->getData(); $country = isset( $data['country'] ) ? $data['country'] : ''; return $vatValidator->check( $value, $country ); }); } /** * Register the service provider. * * @return void */ public function register() { $this->app->singleton( Validator::class, function (Container $app) { return new Validator(); }); $this->app->singleton( Rates::class, function (Container $app) { $defaultCacheDriver = $app['cache']->getDefaultDriver(); $cacheDriver = $app['cache']->driver( $defaultCacheDriver ); return new Rates( $cacheDriver ); }); } /** * Get the services provided by the provider. * * @return string[] */ public function provides() { return [ 'DvK\Laravel\Vat\Validator', 'DvK\Laravel\Vat\Rates', ]; } }
Make watcher a class rule to shutdown cluster after class fail.
package org.apache.mesos.elasticsearch.systemtest.base; import com.containersol.minimesos.MesosCluster; import com.containersol.minimesos.mesos.MesosClusterConfig; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.mesos.elasticsearch.systemtest.Configuration; import org.apache.mesos.elasticsearch.systemtest.Main; import org.apache.mesos.elasticsearch.systemtest.util.DockerUtil; import org.junit.AfterClass; import org.junit.ClassRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; /** * Base test class which launches Mesos CLUSTER */ @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD") public abstract class TestBase { private static final Configuration TEST_CONFIG = new Configuration(); @ClassRule public static final MesosCluster CLUSTER = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(Main.MESOS_IMAGE_TAG) .slaveResources(TEST_CONFIG.getPortRanges()) .build() ); @ClassRule public static final TestWatcher WATCHER = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { CLUSTER.stop(); } }; @AfterClass public static void killAllContainers() { CLUSTER.stop(); new DockerUtil(CLUSTER.getConfig().dockerClient).killAllExecutors(); } public static Configuration getTestConfig() { return TEST_CONFIG; } }
package org.apache.mesos.elasticsearch.systemtest.base; import com.containersol.minimesos.MesosCluster; import com.containersol.minimesos.mesos.MesosClusterConfig; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.mesos.elasticsearch.systemtest.Configuration; import org.apache.mesos.elasticsearch.systemtest.Main; import org.apache.mesos.elasticsearch.systemtest.util.DockerUtil; import org.junit.AfterClass; import org.junit.ClassRule; import org.junit.Rule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; /** * Base test class which launches Mesos CLUSTER */ @SuppressFBWarnings("URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD") public abstract class TestBase { private static final Configuration TEST_CONFIG = new Configuration(); @ClassRule public static final MesosCluster CLUSTER = new MesosCluster( MesosClusterConfig.builder() .mesosImageTag(Main.MESOS_IMAGE_TAG) .slaveResources(TEST_CONFIG.getPortRanges()) .build() ); @Rule public TestWatcher watchman = new TestWatcher() { @Override protected void failed(Throwable e, Description description) { CLUSTER.stop(); } }; @AfterClass public static void killAllContainers() { CLUSTER.stop(); new DockerUtil(CLUSTER.getConfig().dockerClient).killAllExecutors(); } public static Configuration getTestConfig() { return TEST_CONFIG; } }
Use regex instead of replace for Mako template preprocess
""" Module providing standard output classes """ import re from abc import ABCMeta, abstractmethod from mako.template import Template from mako.lookup import TemplateLookup class Output(object): """ Abstract class base for output classes """ __metaclass__ = ABCMeta @abstractmethod def render(self, data): """ Render passed data """ pass class HTMLOutput(Output): """ HTML output renderer, using Mako templates """ def _preprocess(self, text, data): """ Preprocess mako template, to automatically access data dictionary as we cannot unpack data in render_unicode directly using ** operator because unpacking is accessing individual items via __getitem__ advantages of LazyDict Because of this preprocessing you can write in mako template e.g.: ${tweet_count_total} Instead of: ${data['tweet_count_total']} """ regex_str = '' for key in data.keys(): regex_str += r'\b' + key + r'\b|' regex_str = r'((?:' + regex_str[:-1] + r')+)' regex = re.compile(regex_str) text = regex.sub(r"data['\1']", text) return text def render(self, data): """ Render HTML file """ template_lookup = TemplateLookup(directories=['templates/'], module_directory='tmp/', preprocessor=lambda text: self._preprocess(text, data)) mako_template = template_lookup.get_template('html_template.mako') return mako_template.render_unicode(data=data)
""" Module providing standard output classes """ from abc import ABCMeta, abstractmethod from mako.template import Template from mako.lookup import TemplateLookup class Output(object): """ Abstract class base for output classes """ __metaclass__ = ABCMeta @abstractmethod def render(self, data): """ Render passed data """ pass class HTMLOutput(Output): """ HTML output renderer, using Mako templates """ def _preprocess(self, text, data): """ Preprocess mako template, to automatically access data dictionary as we cannot unpack data in render_unicode directly using ** operator because unpacking is accessing individual items via __getitem__ advantages of LazyDict Because of this preprocessing you can write in mako template e.g.: ${tweet_count_total} Instead of: ${data['tweet_count_total']} """ for key in data.keys(): text = text.replace(key, 'data[\'' + key + '\']') return text def render(self, data): """ Render HTML file """ template_lookup = TemplateLookup(directories=['templates/'], module_directory='tmp/', preprocessor=lambda text: self._preprocess(text, data)) mako_template = template_lookup.get_template('html_template.mako') return mako_template.render_unicode(data=data)
Change a couple of defaults
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,5)], "filter2": True, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
class GenomeException(Exception): pass class Genome(object): def __init__(self, name): defaults = { "name": name, "use_openings_book": True, # Search params "max_depth": 6, "max_depth_boost": 0, "mmpdl": 9, "narrowing": 0, "chokes": [(4,2)], "filter2": False, # Utility function "capture_score_base": 300, "take_score_base": 100, "threat_score_base": 20, "captures_scale": [0, 1, 1, 1, 1, 1], "length_factor": 27, "move_factor": 30, "blindness": 0, "sub": True, } super(Genome, self).__setattr__("__dict__", defaults) def __setattr__(self, attr_name, val): if not hasattr(self, attr_name): raise GenomeException("Cannot set attribute %s" % attr_name) super(Genome, self).__setattr__(attr_name, val) def key(self): return self.name
Enhance Business Unit Test coverage Separate tests responsibilities
<?php use App\Business; use App\Presenters\BusinessPresenter; use Illuminate\Foundation\Testing\DatabaseTransactions; class BusinessUnitTest extends TestCase { use DatabaseTransactions; /** * @covers \App\Business::__construct */ public function testCreateBusiness() { $business = factory(Business::class)->create(); return $business; } /** * @covers \App\Business::__construct * @covers \App\Business::save */ public function testCreateAndSeeBusinessStoredInDatabase() { $business = factory(Business::class)->create(); $this->seeInDatabase('businesses', ['slug' => $business->slug]); return $business; } /** * @covers \App\Business::getPresenter * @depends testCreateBusiness */ public function testBusinessGetPresenter(Business $business) { $businessPresenter = $business->getPresenter(); $this->assertInstanceOf(BusinessPresenter::class, $businessPresenter); } /** * @covers \App\Business::setPhoneAttribute * @depends testCreateBusiness */ public function testSetEmptyPhoneAttributeGetsNull(Business $business) { $business->phone = ''; $this->assertNull($business->phone); } /** * @covers \App\Business::setPostalAddressAttribute * @depends testCreateBusiness */ public function testSetEmptyPostalAddressAttributeGetsNull(Business $business) { $business->postal_address = ''; $this->assertNull($business->postal_address); } }
<?php use App\Business; use App\Presenters\BusinessPresenter; use Illuminate\Foundation\Testing\DatabaseTransactions; class BusinessUnitTest extends TestCase { use DatabaseTransactions; /** * @covers \App\Business::create */ public function testCreatedBusinessGetsStoredInDatabase() { $business = factory(Business::class)->create(); $this->seeInDatabase('businesses', ['slug' => $business->slug]); } /** * @covers \App\Business::getPresenter */ public function testBusinessGetPresenter() { $business = factory(Business::class)->create(); $businessPresenter = $business->getPresenter(); $this->assertInstanceOf(BusinessPresenter::class, $businessPresenter); } /** * @covers \App\Business::setPhoneAttribute */ public function testSetEmptyPhoneAttributeGetsNull() { $business = factory(Business::class)->create(); $business->phone = ''; $this->assertNull($business->phone); } /** * @covers \App\Business::setPostalAddressAttribute */ public function testSetEmptyPostalAddressAttributeGetsNull() { $business = factory(Business::class)->create(); $business->postal_address = ''; $this->assertNull($business->postal_address); } }
Fix crash in FAB background tint Caused by moving the base class to AppCompatImageButton. That class's functionality interferes with FAB. BUG: 25302006 Change-Id: I283508caa8ddf5664a5b15209cfff06c464ec187
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.design.widget; import android.content.Context; import android.util.AttributeSet; import android.widget.ImageButton; class VisibilityAwareImageButton extends ImageButton { private int mUserSetVisibility; public VisibilityAwareImageButton(Context context) { this(context, null); } public VisibilityAwareImageButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mUserSetVisibility = getVisibility(); } @Override public void setVisibility(int visibility) { internalSetVisibility(visibility, true); } final void internalSetVisibility(int visibility, boolean fromUser) { super.setVisibility(visibility); if (fromUser) { mUserSetVisibility = visibility; } } final int getUserSetVisibility() { return mUserSetVisibility; } }
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.design.widget; import android.content.Context; import android.support.v7.widget.AppCompatImageButton; import android.util.AttributeSet; class VisibilityAwareImageButton extends AppCompatImageButton { private int mUserSetVisibility; public VisibilityAwareImageButton(Context context) { this(context, null); } public VisibilityAwareImageButton(Context context, AttributeSet attrs) { this(context, attrs, 0); } public VisibilityAwareImageButton(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); mUserSetVisibility = getVisibility(); } @Override public void setVisibility(int visibility) { internalSetVisibility(visibility, true); } final void internalSetVisibility(int visibility, boolean fromUser) { super.setVisibility(visibility); if (fromUser) { mUserSetVisibility = visibility; } } final int getUserSetVisibility() { return mUserSetVisibility; } }
Add "batched" flag to config
<?php namespace Ftrrtf\RollbarBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('ftrrtf_rollbar'); $rootNode ->children() ->arrayNode('notifier') ->children() ->scalarNode('batched')->defaultFalse()->end() ->scalarNode('access_token')->isRequired()->end() ->arrayNode('transport') ->addDefaultsIfNotSet() ->children() ->scalarNode('type')->defaultValue('curl')->end() ->end() ->end() ->end() ->end() ->arrayNode('environment') ->children() // ->scalarNode('host')->defaultNull()->end() ->scalarNode('branch')->defaultValue('master')->end() ->scalarNode('root_dir')->defaultValue('')->end() ->scalarNode('environment')->defaultValue('unknown')->end() ->scalarNode('framework')->end() ->end() ->end() ->end(); return $treeBuilder; } }
<?php namespace Ftrrtf\RollbarBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * @return \Symfony\Component\Config\Definition\Builder\TreeBuilder */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('ftrrtf_rollbar'); $rootNode ->children() ->arrayNode('notifier') ->children() ->scalarNode('access_token')->isRequired()->end() ->arrayNode('transport') ->addDefaultsIfNotSet() ->children() ->scalarNode('type')->defaultValue('curl')->end() ->end() ->end() ->end() ->end() ->arrayNode('environment') ->children() // ->scalarNode('host')->defaultNull()->end() ->scalarNode('branch')->defaultValue('master')->end() ->scalarNode('root_dir')->defaultValue('')->end() ->scalarNode('environment')->defaultValue('unknown')->end() ->scalarNode('framework')->end() ->end() ->end() ->end(); return $treeBuilder; } }
Fix register syntax. Also, prepare to implement the Firebase utility functions.
var React = require('react'); var firebaseUtils = require('../../utils/firebaseUtils'); var Router = require('react-router'); var Register = React.createClass({ mixins: [ Router.Navigation ], render: function(){ return ( <div className="col-sm-6 col-sm-offset-3"> <form onSubmit={this.handleSubmit}> <div className="form-group"> <label> Email </label> <input className="form-control" ref="email" placeholder="Email"/> </div> <div className="form-group"> <label>Password</label> <input ref="pw" type="password" className="form-control" placeholder="Password" /> </div> <button type="submit" className="btn btn-primary">Login</button> </form> </div> ) }, handleSubmit: function(e) { //prevents some default action. e.preventDefault(); //grabs the email and password from the refs in the render method: var email = this.refs.email.getDOMNode().value; var pw = this.refs.pw.getDOMNode().value; //method's parameters are object, and callback: firebaseUtils.createUser({email: email, password: pw}, function(result){ if(result) { //result is truthy, so take to home route. this.replaceWith('home'); } }.bind(this)); } }); module.exports = Register;
var React = require('react'); var firebaseUtils = require('../../utils/firebaseUtils'); var Router = require('react-router'); var Register = React.createClass({ mixins: [ Router.Navigation ], render: function(){ return ( <div className="col-sm-6 col-sm-offset-3"> <form onSubmit={this.handleSubmit}> <div className="form-group"> <label> Email </label> <input className="form-control" ref="email" placeholder="Email"/> </div> <div className="form-group"> <label>Password</label> <input ref="pw" type="password" className="form-control" placeholder="Password" /> </div> <button type="submit" className="btn btn-primary">Login</button> </form> </div> ) }, handleSubmit: function(e) { //prevents some default action. e.preventDefault(); //grabs the email and password from the refs in the render method: var email = this.refs.email.getDomNode().value; var pw = this.refs.pw.getDomNode().value; //method's parameters are object, and callback: firebaseUtils.createUser({email: email, password: pw}, function(result){ if(result) { //result is truthy, so take to home route. thisreplaceWith('home'); } }.bind(this)); } }); module.exports = Register;
Change ucldc-iiif back to barbara's repo
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = "UCLDC Deep Harvester", version = "0.0.3", description = ("deep harvester code for the UCLDC project"), long_description=read('README.md'), author='Barbara Hui', author_email='[email protected]', dependency_links=[ 'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux', 'https://github.com/mredar/jsonpath/archive/master.zip#egg=jsonpath', 'https://github.com/barbarahui/ucldc-iiif/archive/master.zip#egg=ucldc-iiif' ], install_requires=[ 'argparse', 'boto', 'pynux', 'python-magic', 'couchdb', 'jsonpath', 'akara', 'ucldc-iiif' ], packages=['deepharvest', 's3stash'], test_suite='tests' ) ### note: dpla-ingestion code is a dependency ###pip_main(['install', ### 'git+ssh://[email protected]/mredar/dpla-ingestion.git@ucldc'])
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() # allow setup.py to be run from any path os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir))) setup( name = "UCLDC Deep Harvester", version = "0.0.3", description = ("deep harvester code for the UCLDC project"), long_description=read('README.md'), author='Barbara Hui', author_email='[email protected]', dependency_links=[ 'https://github.com/ucldc/pynux/archive/master.zip#egg=pynux', 'https://github.com/mredar/jsonpath/archive/master.zip#egg=jsonpath', 'https://github.com/mredar/ucldc-iiif/archive/master.zip#egg=ucldc-iiif' ], install_requires=[ 'argparse', 'boto', 'pynux', 'python-magic', 'couchdb', 'jsonpath', 'akara', 'ucldc-iiif' ], packages=['deepharvest', 's3stash'], test_suite='tests' ) ### note: dpla-ingestion code is a dependency ###pip_main(['install', ### 'git+ssh://[email protected]/mredar/dpla-ingestion.git@ucldc'])
Fix failing reconnects; add quit IRC command
from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): """ Usage: quit - Tell the bot to disconnect from the server. """ self.bot.intended_disconnect = True self.bot.exit()
from p1tr.helpers import clean_string from p1tr.plugin import * @meta_plugin class Irc(Plugin): """Provides commands for basic IRC operations.""" @command @require_master def nick(self, server, channel, nick, params): """Usage: nick NEW_NICKNAME - changes the bot's nickname.""" if len(params) < 1: return clean_string(self.nick.__doc__) self.bot.client.send('NICK', params[0]) @command @require_master def join(self, server, channel, nick, params): """ Usage: join #CHANNEL [PASSWORD] - the bot will enter the specified channel. A password may be provided optionally, if it is required. """ if len(params) < 1: return clean_string(self.join.__doc__) password = '' if len(params) > 1: password = params[0] self.bot.client.send('JOIN', params[0], password) @command @require_op def part(self, server, channel, nick, params): """ Usage: part [#CHANNEL] - asks the bot to leave the current channel. Optionally, a channel may be specified if it should be left instead of the current one. """ if len(params) > 0: channel = params[0] self.bot.client.send('PART', channel) @command @require_master def quit(self, server, channel, nick, params): self.blot.intended_disconnect = True
Allow to access id through
<?php namespace Gitlab\Model; use Gitlab\Client; /** * Class Note * * @property-read User $author * @property-read string $body * @property-read string $created_at * @property-read string $updated_at * @property-read string $parent_type * @property-read Issue|MergeRequest $parent * @property-read string $attachment */ class Note extends AbstractModel { /** * @var array */ protected static $properties = array( 'id', 'author', 'body', 'created_at', 'updated_at', 'parent_type', 'parent', 'attachment' ); /** * @param Client $client * @param Noteable $type * @param array $data * @return mixed */ public static function fromArray(Client $client, Noteable $type, array $data) { $comment = new static($type, $client); if (isset($data['author'])) { $data['author'] = User::fromArray($client, $data['author']); } return $comment->hydrate($data); } /** * @param Noteable $type * @param Client $client */ public function __construct(Noteable $type, Client $client = null) { $this->setClient($client); $this->setData('parent_type', get_class($type)); $this->setData('parent', $type); } }
<?php namespace Gitlab\Model; use Gitlab\Client; /** * Class Note * * @property-read User $author * @property-read string $body * @property-read string $created_at * @property-read string $updated_at * @property-read string $parent_type * @property-read Issue|MergeRequest $parent * @property-read string $attachment */ class Note extends AbstractModel { /** * @var array */ protected static $properties = array( 'author', 'body', 'created_at', 'updated_at', 'parent_type', 'parent', 'attachment' ); /** * @param Client $client * @param Noteable $type * @param array $data * @return mixed */ public static function fromArray(Client $client, Noteable $type, array $data) { $comment = new static($type, $client); if (isset($data['author'])) { $data['author'] = User::fromArray($client, $data['author']); } return $comment->hydrate($data); } /** * @param Noteable $type * @param Client $client */ public function __construct(Noteable $type, Client $client = null) { $this->setClient($client); $this->setData('parent_type', get_class($type)); $this->setData('parent', $type); } }
Build fix for syntax error in test files.
import unittest from nose.tools import (assert_is_not_none, assert_false, assert_raises, assert_equal) import numpy as np from sknn.mlp import MultiLayerPerceptronRegressor as MLPR class TestLearningRules(unittest.TestCase): def test_default(self): self._run(MLPR(layers=[("Linear",)], learning_rule='default')) def test_momentum(self): self._run(MLPR(layers=[("Linear",)], learning_rule='momentum')) def test_rmsprop(self): self._run(MLPR(layers=[("Linear",)], learning_rule='rmsprop')) def test_rmsprop(self): self._run(MLPR(layers=[("Linear",)], dropout=True)) def test_unknown(self): assert_raises(NotImplementedError, MLPR, layers=[], learning_rule='unknown') def _run(self, nn): a_in, a_out = np.zeros((8,16)), np.zeros((8,4)) nn.fit(a_in, a_out) a_test = nn.predict(a_in) assert_equal(type(a_out), type(a_test))
import unittest from nose.tools import (assert_is_not_none, assert_false, assert_raises, assert_equal) import numpy as np from sknn.mlp import MultiLayerPerceptronRegressor as MLPR class TestLearningRules(unittest.TestCase): def test_default(self): self._run(MLPR(layers=[("Linear",)], learning_rule='default')) def test_momentum(self): self._run(MLPR(layers=[("Linear",)], learning_rule='momentum')) def test_rmsprop(self): self._run(MLPR(layers=[("Linear",)], learning_rule='rmsprop')) def test_rmsprop(self): self._run(MLPR(layers=[("Linear",)], dropout=True) def test_unknown(self): assert_raises(NotImplementedError, MLPR, layers=[], learning_rule='unknown') def _run(self, nn): a_in, a_out = np.zeros((8,16)), np.zeros((8,4)) nn.fit(a_in, a_out) a_test = nn.predict(a_in) assert_equal(type(a_out), type(a_test))
Correct a typo in a describe block title
/* global angular */ describe('ng-json2js preprocessor', function () { 'use strict'; beforeEach(module('test/fixtures/empty.json')); beforeEach(module('test/fixtures/complex.json')); it('should work on an empty object', function () { var testFixturesEmpty; inject(function (_testFixturesEmpty_) { testFixturesEmpty = _testFixturesEmpty_; }); expect(testFixturesEmpty).toEqual({}); }); var checkComplexObject = function (testFixturesComplex) { expect(testFixturesComplex).toEqual({ field: 'property', subObject: [ 'arrayElem1', 'arrayElem2', ], anotherSubObject: { subSubObject: { field: 'property', }, }, }); }; it('should work on a complex object', function () { var testFixturesComplex; inject(function (_testFixturesComplex_) { testFixturesComplex = _testFixturesComplex_; }); checkComplexObject(testFixturesComplex); }); it('should allow accessing the json during configuration phase', function () { var injectedDuringConfig; angular.module('testModule', ['test/fixtures/complex.json']).config(function (_testFixturesComplex_) { injectedDuringConfig = _testFixturesComplex_; }); inject(module('testModule')); checkComplexObject(injectedDuringConfig); }); });
/* global angular */ describe('json2j preprocessor', function () { 'use strict'; beforeEach(module('test/fixtures/empty.json')); beforeEach(module('test/fixtures/complex.json')); it('should work on an empty object', function () { var testFixturesEmpty; inject(function (_testFixturesEmpty_) { testFixturesEmpty = _testFixturesEmpty_; }); expect(testFixturesEmpty).toEqual({}); }); var checkComplexObject = function (testFixturesComplex) { expect(testFixturesComplex).toEqual({ field: 'property', subObject: [ 'arrayElem1', 'arrayElem2', ], anotherSubObject: { subSubObject: { field: 'property', }, }, }); }; it('should work on a complex object', function () { var testFixturesComplex; inject(function (_testFixturesComplex_) { testFixturesComplex = _testFixturesComplex_; }); checkComplexObject(testFixturesComplex); }); it('should allow accessing the json during configuration phase', function () { var injectedDuringConfig; angular.module('testModule', ['test/fixtures/complex.json']).config(function (_testFixturesComplex_) { injectedDuringConfig = _testFixturesComplex_; }); inject(module('testModule')); checkComplexObject(injectedDuringConfig); }); });
Disable SSL warnings by default.
# As a hack, disable SSL warnings. import urllib3 urllib3.disable_warnings() import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
import sys def format_cols(cols): widths = [0] * len(cols[0]) for i in cols: for idx, val in enumerate(i): widths[idx] = max(len(val), widths[idx]) f = "" t = [] for i in widths: t.append("%%-0%ds" % (i,)) return " ".join(t) def column_report(title, fields, cols): l = [] l.append("[" + title + "]") l.append("") f = format_cols([fields] + cols) header = f % tuple(fields) l.append(header) l.append("-" * len(header)) for i in cols: l.append(f % tuple(i)) l.append("") l.append("") return "\n".join(l) def basename(uri): return uri.rstrip("/").split("/")[-1] def step(desc): print desc print "=" * len(desc) print def end_step(): raw_input("Press enter to run the next step.") print print def check_response(r, expected_statuses=None): if expected_statuses == None: expected_statuses = [200] ok = False for i in expected_statuses: if r.status_code == i: ok = True break if not ok: print "Request failed to succeed:" print "Status: %s" % (r.status_code,) print r.content sys.exit(1)
BAP-11410: Add CRUD controller for Language entity - cr updates
<?php namespace Oro\Bundle\TranslationBundle\EventListener\Datagrid; use Oro\Bundle\DataGridBundle\Datasource\ResultRecord; use Oro\Bundle\DataGridBundle\Event\OrmResultAfter; use Oro\Bundle\TranslationBundle\Provider\TranslationStatisticProvider; class LanguageListener { const DATA_NAME = 'translationCompleteness'; /** @var TranslationStatisticProvider */ protected $translationStatisticProvider; /** * @param TranslationStatisticProvider $translationStatisticProvider */ public function __construct(TranslationStatisticProvider $translationStatisticProvider) { $this->translationStatisticProvider = $translationStatisticProvider; } /** * @param OrmResultAfter $event */ public function onResultAfter(OrmResultAfter $event) { $stats = $this->getStatistic(); /** @var ResultRecord[] $records */ $records = $event->getRecords(); foreach ($records as $record) { $code = $record->getValue('code'); $record->setValue(self::DATA_NAME, isset($stats[$code]) ? (int)$stats[$code] : null); } } /** * @return array */ protected function getStatistic() { $stats = $this->translationStatisticProvider->get(); $result = []; foreach ($stats as $stat) { $result[$stat['code']] = $stat['translationStatus']; } // TODO: should be fixed in https://magecore.atlassian.net/browse/BAP-10608 $result['en'] = 100; return $result; } }
<?php namespace Oro\Bundle\TranslationBundle\EventListener\Datagrid; use Oro\Bundle\DataGridBundle\Datasource\ResultRecord; use Oro\Bundle\DataGridBundle\Event\OrmResultAfter; use Oro\Bundle\TranslationBundle\Provider\TranslationStatisticProvider; class LanguageListener { const DATA_NAME = 'translationCompleteness'; /** @var TranslationStatisticProvider */ protected $translationStatisticProvider; /** * @param TranslationStatisticProvider $translationStatisticProvider */ public function __construct(TranslationStatisticProvider $translationStatisticProvider) { $this->translationStatisticProvider = $translationStatisticProvider; } /** * @param OrmResultAfter $event */ public function onResultAfter(OrmResultAfter $event) { $stats = $this->getStatistic(); /** @var ResultRecord[] $records */ $records = $event->getRecords(); foreach ($records as $record) { $code = $record->getValue('code'); $record->setValue(self::DATA_NAME, isset($stats[$code]) ? (int)$stats[$code] : 0); } } /** * @return array */ protected function getStatistic() { $stats = $this->translationStatisticProvider->get(); $result = []; foreach ($stats as $stat) { $result[$stat['code']] = $stat['translationStatus']; } return $result; } }
Update auth token form layout
@extends('layouts.app') @section('content') <div class="container"> <div class="row justify-content-center"> <div class="col-md-8"> <div class="card"> <div class="card-header">@lang('twofactor-auth::twofactor-auth.title')</div> <div class="card-body"> <form class="form-horizontal" role="form" method="POST" action="{{ route('auth.token') }}"> @csrf <div class="form-group row"> <label for="token" class="col-md-4 col-form-label text-md-right">@lang('twofactor-auth::twofactor-auth.label')</label> <div class="col-md-6"> <input id="token" type="text" class="form-control{{ $errors->has('token') ? ' is-invalid' : '' }}" name="token" value="{{ old('token') }}" required autofocus> @if ($errors->has('token')) <span class="invalid-feedback" role="alert"> <strong>{{ $errors->first('token') }}</strong> </span> @endif </div> </div> <div class="form-group row mb-0"> <div class="col-md-8 offset-md-4"> <button type="submit" class="btn btn-primary"> @lang('twofactor-auth::twofactor-auth.send') </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
@extends('layouts.app') @section('content') <div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <div class="panel panel-default"> <div class="panel-heading">@lang('twofactor-auth::twofactor-auth.title')</div> <div class="panel-body"> <form class="form-horizontal" role="form" method="POST" action="{{ route('auth.token') }}"> {{ csrf_field() }} <div class="form-group{{ $errors->has('token') ? ' has-error' : '' }}"> <label for="token" class="col-md-4 control-label">@lang('twofactor-auth::twofactor-auth.label')</label> <div class="col-md-6"> <input id="token" type="text" class="form-control" name="token" value="{{ old('token') }}" required autofocus> @if ($errors->has('token')) <span class="help-block"> <strong>{{ $errors->first('token') }}</strong> </span> @endif </div> </div> <div class="form-group"> <div class="col-md-8 col-md-offset-4"> <button type="submit" class="btn btn-primary"> @lang('twofactor-auth::twofactor-auth.send') </button> </div> </div> </form> </div> </div> </div> </div> </div> @endsection
Update class docs and renamed dump() to dumpFiles()
<?php /* * \Moharrum\LaravelGeoIPWorldCities for Laravel 5 * * Copyright (c) 2015 - 2016 LaravelGeoIPWorldCities * * @copyright Copyright (c) 2015 - 2016 \Moharrum\LaravelGeoIPWorldCities * * @license http://opensource.org/licenses/MIT MIT license */ use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Moharrum\LaravelGeoIPWorldCities\Helpers\Config; /** * @author Khalid Moharrum <[email protected]> */ class CitiesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { foreach($this->dumpFiles() as $dumpPart) { $query = "LOAD DATA LOCAL INFILE '" . $dumpPart . "' INTO TABLE `" . Config::citiesTableName() . "` FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (country, city_ascii, city, region, population, latitude, longitude )"; DB::connection()->getpdo()->exec($query); } } /** * Returns an array containing the full path to each dump file. * * @return array */ private function dumpFiles() { $files = []; foreach(File::allFiles(Config::dumpPath()) as $dumpFile) { $files[] = $dumpFile->getRealpath(); } sort($files); return $files; } }
<?php use Illuminate\Database\Seeder; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\File; use Moharrum\LaravelGeoIPWorldCities\Helpers\Config; class CitiesTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { foreach($this->dump() as $dumpPart) { $query = "LOAD DATA LOCAL INFILE '" . $dumpPart . "' INTO TABLE `" . Config::citiesTableName() . "` FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES (country, city_ascii, city, region, population, latitude, longitude )"; DB::connection()->getpdo()->exec($query); } } /** * Returns an array containing the full path to each dump file. * * @return array */ protected function dump() { $files = []; foreach(File::allFiles(Config::dumpPath()) as $dumpFile) { $files[] = $dumpFile->getRealpath(); } sort($files); return $files; } }
Add options attribute to pass a complete options list to directive The option attribute must contains an object with the additional options you want to pass to the justgage object. Normal option are still use but will be overload by object if declared twice. Here's a sample to use levelColors and levelGradiant. All justgage option are now available for the directive. <just-gage id="demo" class="" min=0 max=100 value="92" title="Demo" options="{ levelColors: ['#CE1B21', '#D0532A', '#FFC414', '#85A137'] ,levelGradiant: false } "> </just-gage>
angular.module("ngJustGage", []) .directive('justGage', ['$timeout', function ($timeout) { return { restrict: 'EA', scope: { id: '@', class: '@', min: '=', max: '=', title: '@', value: '=', options: '=' }, template: '<div id="{{id}}-justgage" class="{{class}}"></div>', link: function (scope,element,attrs) { $timeout(function () { var options = { id: scope.id + '-justgage', min: scope.min, max: scope.max, title: scope.title, value: scope.value } if ( scope.options ) { for (var key in scope.options) { options[key]=scope.options[key]; } } var graph = new JustGage(options); scope.$watch('max', function (updatedMax) { if (updatedMax) { graph.refresh(scope.value, updatedMax); } }, true); scope.$watch('value', function (updatedValue) { if (updatedValue) { graph.refresh(updatedValue); } }, true); }); } }; }]);
angular.module("ngJustGage", []) .directive('justGage', ['$timeout', function ($timeout) { return { restrict: 'EA', scope: { id: '@', class: '@', min: '=', max: '=', title: '@', value: '=' }, template: '<div id="{{id}}-justgage" class="{{class}}"></div>', link: function (scope) { $timeout(function () { var graph = new JustGage({ id: scope.id + '-justgage', min: scope.min, max: scope.max, title: scope.title, value: scope.value }); scope.$watch('max', function (updatedMax) { if (updatedMax) { graph.refresh(scope.value, updatedMax); } }, true); scope.$watch('value', function (updatedValue) { if (updatedValue) { graph.refresh(updatedValue); } }, true); }); } }; }]);
Add anchor tag props for transferring
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var React = require('react/addons'), NavLink, navigateAction = require('../actions/navigate'), debug = require('debug')('NavLink'); NavLink = React.createClass({ propTypes: { context: React.PropTypes.object.isRequired }, dispatchNavAction: function (e) { var context = this.props.context; debug('dispatchNavAction: action=NAVIGATE path=' + this.props.href + ' params=' + JSON.stringify(this.props.navParams)); if (context) { e.preventDefault(); e.stopPropagation(); context.executeAction(navigateAction, { type: 'click', path: this.props.href, params: this.props.navParams }); } else { console.warn('NavLink.dispatchNavAction: missing dispatcher, will load from server'); } }, render: function() { var context = this.props.context, routeName = this.props.routeName; if (!this.props.href && routeName && context && context.makePath) { this.props.href = context.makePath(routeName, this.props.navParams); } return React.createElement( 'a', { onClick: this.dispatchNavAction, href: this.props.href, id: this.props.id, className: this.props.className, title: this.props.title, target: this.props.target, rel: this.props.rel }, this.props.children ); } }); module.exports = NavLink;
/** * Copyright 2014, Yahoo! Inc. * Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ 'use strict'; var React = require('react/addons'), NavLink, navigateAction = require('../actions/navigate'), debug = require('debug')('NavLink'); NavLink = React.createClass({ propTypes: { context: React.PropTypes.object.isRequired }, dispatchNavAction: function (e) { var context = this.props.context; debug('dispatchNavAction: action=NAVIGATE path=' + this.props.href + ' params=' + JSON.stringify(this.props.navParams)); if (context) { e.preventDefault(); e.stopPropagation(); context.executeAction(navigateAction, { type: 'click', path: this.props.href, params: this.props.navParams }); } else { console.warn('NavLink.dispatchNavAction: missing dispatcher, will load from server'); } }, render: function() { var context = this.props.context, routeName = this.props.routeName; if (!this.props.href && routeName && context && context.makePath) { this.props.href = context.makePath(routeName, this.props.navParams); } return React.createElement( 'a', {onClick:this.dispatchNavAction, href:this.props.href}, this.props.children ); } }); module.exports = NavLink;
Add option to Button messages to hide buttons on click
<?php namespace actsmart\actsmart\Actuators\WebChat; class WebChatButtonMessage extends WebChatMessage { protected $messageType = 'button'; /** The message buttons. @var WebChatButton[] */ private $buttons = []; private $clearAfterInteraction = true; /** * @param $clearAfterInteraction * @return $this */ public function setClearAfterInteraction($clearAfterInteraction) { $this->clearAfterInteraction = $clearAfterInteraction; return $this; } /** * @return bool */ public function getClearAfterInteraction() { return $this->clearAfterInteraction; } /** * @param WebChatButton $button * @return $this */ public function addButton(WebChatButton $button) { $this->buttons[] = $button; return $this; } /** * @return array */ public function getButtons() { return $this->buttons; } /** * @return array */ public function getData() { return parent::getData() + [ 'buttons' => $this->getButtonsArray(), 'clear_after_interaction' => $this->getClearAfterInteraction() ]; } /** * @return array */ public function getButtonsArray() { $buttons = []; foreach ($this->buttons as $button) { $buttons[] = [ 'text' => $button->getText(), 'callback_id' => $button->getCallbackId(), 'value' => $button->getValue() ]; } return $buttons; } }
<?php namespace actsmart\actsmart\Actuators\WebChat; class WebChatButtonMessage extends WebChatMessage { protected $messageType = 'button'; /** The message buttons. @var WebChatButton[] */ private $buttons = []; /** * @param WebChatButton $button * @return $this */ public function addButton(WebChatButton $button) { $this->buttons[] = $button; return $this; } /** * @return array */ public function getButtons() { return $this->buttons; } /** * @return array */ public function getData() { return parent::getData() + [ 'buttons' => $this->getButtonsArray() ]; } /** * @return array */ public function getButtonsArray() { $buttons = []; foreach ($this->buttons as $button) { $buttons[] = [ 'text' => $button->getText(), 'callback_id' => $button->getCallbackId(), 'value' => $button->getValue() ]; } return $buttons; } }
Add 'no cover' pragma to hide bogus missing code coverage
try: from txampext import axiomtypes; axiomtypes from axiom import attributes except ImportError: # pragma: no cover axiomtypes = None from twisted.protocols import amp from twisted.trial import unittest class TypeForTests(unittest.TestCase): skip = axiomtypes is None def _test_typeFor(self, attr, expectedType, **kwargs): asAMP = axiomtypes.typeFor(attr, **kwargs) self.assertTrue(isinstance(asAMP, expectedType)) return asAMP def test_optional(self): asAMP = axiomtypes.typeFor(attributes.text(), optional=True) self.assertTrue(asAMP.optional) def test_text(self): self._test_typeFor(attributes.text(), amp.Unicode) def test_bytes(self): self._test_typeFor(attributes.bytes(), amp.String) def test_integer(self): self._test_typeFor(attributes.integer(), amp.Integer) def test_decimals(self): for precision in range(1, 11): attr = getattr(attributes, "point{}decimal".format(precision)) self._test_typeFor(attr(), amp.Decimal) self._test_typeFor(attributes.money(), amp.Decimal) def test_float(self): self._test_typeFor(attributes.ieee754_double(), amp.Float) def test_timestamp(self): self._test_typeFor(attributes.timestamp(), amp.DateTime)
try: from txampext import axiomtypes; axiomtypes from axiom import attributes except ImportError: axiomtypes = None from twisted.protocols import amp from twisted.trial import unittest class TypeForTests(unittest.TestCase): skip = axiomtypes is None def _test_typeFor(self, attr, expectedType, **kwargs): asAMP = axiomtypes.typeFor(attr, **kwargs) self.assertTrue(isinstance(asAMP, expectedType)) return asAMP def test_optional(self): asAMP = axiomtypes.typeFor(attributes.text(), optional=True) self.assertTrue(asAMP.optional) def test_text(self): self._test_typeFor(attributes.text(), amp.Unicode) def test_bytes(self): self._test_typeFor(attributes.bytes(), amp.String) def test_integer(self): self._test_typeFor(attributes.integer(), amp.Integer) def test_decimals(self): for precision in range(1, 11): attr = getattr(attributes, "point{}decimal".format(precision)) self._test_typeFor(attr(), amp.Decimal) self._test_typeFor(attributes.money(), amp.Decimal) def test_float(self): self._test_typeFor(attributes.ieee754_double(), amp.Float) def test_timestamp(self): self._test_typeFor(attributes.timestamp(), amp.DateTime)
Swap order of commonjs and resolve
import commonjs from '@rollup/plugin-commonjs'; import glslify from 'rollup-plugin-glslify'; import resolve from '@rollup/plugin-node-resolve'; import copy from "rollup-plugin-copy"; export default { input: ['source/gltf-sample-viewer.js'], output: [ { file: 'dist/gltf-viewer.js', format: 'cjs', sourcemap: true }, { file: 'dist/gltf-viewer.module.js', format: 'esm', sourcemap: true, } ], plugins: [ glslify(), commonjs(), resolve({ browser: true, preferBuiltins: false }), copy({ targets: [ { src: [ "assets/images/lut_charlie.png", "assets/images/lut_ggx.png", "assets/images/lut_sheen_E.png", ], dest: "dist/assets" }, { src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" } ] }) ] };
import commonjs from '@rollup/plugin-commonjs'; import glslify from 'rollup-plugin-glslify'; import resolve from '@rollup/plugin-node-resolve'; import copy from "rollup-plugin-copy"; export default { input: ['source/gltf-sample-viewer.js'], output: [ { file: 'dist/gltf-viewer.js', format: 'cjs', sourcemap: true }, { file: 'dist/gltf-viewer.module.js', format: 'esm', sourcemap: true, } ], plugins: [ glslify(), resolve({ browser: true, preferBuiltins: false }), commonjs(), copy({ targets: [ { src: [ "assets/images/lut_charlie.png", "assets/images/lut_ggx.png", "assets/images/lut_sheen_E.png", ], dest: "dist/assets" }, { src: ["source/libs/*", "!source/libs/hdrpng.js"], dest: "dist/libs" } ] }) ] };
Add execute hook to allow wrapping handler calls
from cgi import parse_header import json from django.http import HttpResponse, Http404 RPC_MARKER = '_rpc' class Resource(object): def __init__(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs @classmethod def as_view(cls): def view(request, *args, **kwargs): self = cls(request, *args, **kwargs) return self.dispatch(request) return view def dispatch(self, request): method = request.META['HTTP_X_RPC_ACTION'] func = getattr(self, method, None) if not getattr(func, RPC_MARKER, True): raise Http404 data = self.get_request_data(request) resp = self.execute(func, data) return HttpResponse(json.dumps(resp), content_type='application/json') def execute(self, handler, data): '''Helpful hook to ease wrapping the handler''' return handler(**data) def get_request_data(self, default=None): '''Retrieve data from request''' c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', '')) if c_type in ['application/json', 'text/json']: if not self.request.body: return default return self.loads(self.request.body) if self.request.method == 'GET': return self.request.GET return self.request.POST def rpc(view): '''Mark a view as accessible via RPC''' setattr(view, '_rpc', True) return view
from cgi import parse_header import json from django.http import HttpResponse, Http404 RPC_MARKER = '_rpc' class Resource(object): def __init__(self, request, *args, **kwargs): self.request = request self.args = args self.kwargs = kwargs @classmethod def as_view(cls): def view(request, *args, **kwargs): self = cls(request, *args, **kwargs) return self.dispatch(request) return view def dispatch(self, request): method = request.META['HTTP_X_RPC_ACTION'] func = getattr(self, method, None) if not getattr(func, RPC_MARKER, True): raise Http404 data = self.get_request_data(request) resp = func(data) return HttpResponse(json.dumps(resp), content_type='application/json') def get_request_data(self, default=None): '''Retrieve data from request''' c_type, _ = parse_header(self.request.META.get('CONTENT_TYPE', '')) if c_type in ['application/json', 'text/json']: if not self.request.body: return default return self.loads(self.request.body) if self.request.method == 'GET': return self.request.GET return self.request.POST def rpc(view): '''Mark a view as accessible via RPC''' setattr(view, '_rpc', True) return view
Improve phrasing of note and wrap at 80 chars
<?php namespace Sil\SilAuth\saml; class User { public static function convertToSamlFieldNames( string $employeeId, string $firstName, string $lastName, string $username, string $email, string $uuid, string $idpDomainName, $passwordExpirationDate, array $mfa ) { return [ 'eduPersonPrincipalName' => [ $username . '@' . $idpDomainName, ], /** * Misspelled version of eduPersonTargetedID. * @deprecated */ 'eduPersonTargetID' => (array)$uuid, // Incorrect, deprecated /** * NOTE: Do NOT include eduPersonTargetedID. If you need it, use the * core:TargetedID module (at the Hub, if using one) to generate an * eduPersonTargetedID. */ 'sn' => (array)$lastName, 'givenName' => (array)$firstName, 'mail' => (array)$email, 'employeeNumber' => (array)$employeeId, 'cn' => (array)$username, 'schacExpiryDate' => (array)$passwordExpirationDate, 'mfa' => $mfa, 'uuid' => (array)$uuid, ]; } }
<?php namespace Sil\SilAuth\saml; class User { public static function convertToSamlFieldNames( string $employeeId, string $firstName, string $lastName, string $username, string $email, string $uuid, string $idpDomainName, $passwordExpirationDate, array $mfa ) { return [ 'eduPersonPrincipalName' => [ $username . '@' . $idpDomainName, ], /** * Misspelled version of eduPersonTargetedID. * @deprecated */ 'eduPersonTargetID' => (array)$uuid, // Incorrect, deprecated /** * NOTE: Do NOT include eduPersonTargetedID. If you need it, use the core:TargetedID module, ideally at the * Hub, to generate an eduPersonTargetedID. */ 'sn' => (array)$lastName, 'givenName' => (array)$firstName, 'mail' => (array)$email, 'employeeNumber' => (array)$employeeId, 'cn' => (array)$username, 'schacExpiryDate' => (array)$passwordExpirationDate, 'mfa' => $mfa, 'uuid' => (array)$uuid, ]; } }
Fix undefined quotes causing error
// @flow import React, { Component } from 'react'; import Quote from './Quote'; type Props = { quotes: Array<Object>, approve: number => Promise<*>, deleteQuote: number => Promise<*>, unapprove: number => Promise<*>, actionGrant: Array<string>, currentUser: any, loggedIn: boolean, comments: Object }; type State = { displayAdminId: number }; export default class QuoteList extends Component<Props, State> { state = { displayAdminId: -1 }; componentWillReceiveProps(newProps: Object) { this.setState({ displayAdminId: -1 }); } setDisplayAdmin = (id: number) => { this.setState(state => ({ displayAdminId: state.displayAdminId === id ? -1 : id })); }; render() { const { quotes, actionGrant, approve, unapprove, deleteQuote, currentUser, loggedIn, comments } = this.props; return ( <ul> {quotes .filter(Boolean) .map(quote => ( <Quote actionGrant={actionGrant} approve={approve} unapprove={unapprove} deleteQuote={deleteQuote} quote={quote} key={quote.id} setDisplayAdmin={this.setDisplayAdmin} displayAdmin={quote.id === this.state.displayAdminId} currentUser={currentUser} loggedIn={loggedIn} comments={comments} /> ))} </ul> ); } }
// @flow import React, { Component } from 'react'; import Quote from './Quote'; type Props = { quotes: Array<Object>, approve: number => Promise<*>, deleteQuote: number => Promise<*>, unapprove: number => Promise<*>, actionGrant: Array<string>, currentUser: any, loggedIn: boolean, comments: Object }; type State = { displayAdminId: number }; export default class QuoteList extends Component<Props, State> { state = { displayAdminId: -1 }; componentWillReceiveProps(newProps: Object) { this.setState({ displayAdminId: -1 }); } setDisplayAdmin = (id: number) => { this.setState(state => ({ displayAdminId: state.displayAdminId === id ? -1 : id })); }; render() { const { quotes, actionGrant, approve, unapprove, deleteQuote, currentUser, loggedIn, comments } = this.props; return ( <ul> {quotes.map(quote => ( <Quote actionGrant={actionGrant} approve={approve} unapprove={unapprove} deleteQuote={deleteQuote} quote={quote} key={quote.id} setDisplayAdmin={this.setDisplayAdmin} displayAdmin={quote.id === this.state.displayAdminId} currentUser={currentUser} loggedIn={loggedIn} comments={comments} /> ))} </ul> ); } }
Allow grunt-jekyll to build drafts
module.exports = function (grunt) { // load all grunt tasks matching the `grunt-*` pattern require('load-grunt-tasks')(grunt); grunt.initConfig({ autoprefixer: { build: { src: 'public/css/style.css' } }, csscomb: { options: { config: 'public/css/.csscomb.json' }, build: { src: 'public/css/style.css', dest: 'public/css/style.css' } }, jekyll: { options: { drafts: true }, serve: { dest: '_site' } }, watch: { jekyllSources: { files: [ '*.html', '*.md', '*.yml', 'public/**', '_posts/**', '_projects/**', '_includes/**', '_layouts/**', '_drafts/**', 'atom.xml' ], tasks: ['build'] } }, browserSync: { serve: { bsFiles: { src: ['_site/**'] }, options: { watchTask: true, server: { baseDir: '_site' } } } } }); grunt.registerTask('clean', [ 'autoprefixer:build', 'csscomb:build' ]); // jekyll build task grunt.registerTask('build', ['jekyll']); // livereload task grunt.registerTask('serve', ['browserSync', 'watch']); // default task grunt.registerTask('default', 'clean'); }
module.exports = function (grunt) { // load all grunt tasks matching the `grunt-*` pattern require('load-grunt-tasks')(grunt); grunt.initConfig({ autoprefixer: { build: { src: 'public/css/style.css' } }, csscomb: { options: { config: 'public/css/.csscomb.json' }, build: { src: 'public/css/style.css', dest: 'public/css/style.css' } }, jekyll: { serve: { dest: '_site' } }, watch: { jekyllSources: { files: [ '*.html', '*.md', '*.yml', 'public/**', '_posts/**', '_projects/**', '_includes/**', '_layouts/**', '_drafts/**', 'atom.xml' ], tasks: ['build'] } }, browserSync: { serve: { bsFiles: { src: ['_site/**'] }, options: { watchTask: true, server: { baseDir: '_site' } } } } }); grunt.registerTask('clean', [ 'autoprefixer:build', 'csscomb:build' ]); // jekyll build task grunt.registerTask('build', ['jekyll']); // livereload task grunt.registerTask('serve', ['browserSync', 'watch']); // default task grunt.registerTask('default', 'clean'); }
Remove default config path (development.ini) Towards #1
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import argparse import os import sys from . import commands, utils DEFAULTS = { } def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser(description='DB Migrator') parser.add_argument('--migrations-directory') parser.add_argument('--config') parser.add_argument('--db-connection-string', help='a psycopg2 db connection string') subparsers = parser.add_subparsers(help='commands') commands.load_cli(subparsers) args = parser.parse_args(argv) args = vars(args) if os.path.exists(args['config']): utils.get_settings_from_config(args['config'], [ 'migrations-directory', 'db-connection-string', ], args) utils.get_settings_from_entry_points(args) for name, value in DEFAULTS.items(): if not args.get(name): args[name] = value if 'cmmd' not in args: parser.print_help() return parser.error('command missing') args['migrations_directory'] = os.path.relpath( args['migrations_directory']) return args['cmmd'](**args)
# -*- coding: utf-8 -*- # ### # Copyright (c) 2015, Rice University # This software is subject to the provisions of the GNU Affero General # Public License version 3 (AGPLv3). # See LICENCE.txt for details. # ### import argparse import os import sys from . import commands, utils DEFAULTS = { 'migrations_directory': 'migrations', } DEFAULT_CONFIG_PATH = 'development.ini' def main(argv=sys.argv[1:]): parser = argparse.ArgumentParser(description='DB Migrator') parser.add_argument('--migrations-directory') parser.add_argument('--config', default=DEFAULT_CONFIG_PATH) parser.add_argument('--db-connection-string', help='a psycopg2 db connection string') subparsers = parser.add_subparsers(help='commands') commands.load_cli(subparsers) args = parser.parse_args(argv) args = vars(args) if os.path.exists(args['config']): utils.get_settings_from_config(args['config'], [ 'migrations-directory', 'db-connection-string', ], args) utils.get_settings_from_entry_points(args) for name, value in DEFAULTS.items(): if not args.get(name): args[name] = value if 'cmmd' not in args: parser.print_help() return parser.error('command missing') args['migrations_directory'] = os.path.relpath( args['migrations_directory']) return args['cmmd'](**args)
Revert "keep .java on mainFile"
/* * Run the code contained in the file manager, by compiling everything and * executing the main class, then display the result. */ /* global FileManager */ function runCodeCheerp() { // Get the main class's actual name.. // drop the .java extension var mainName = FileManager.getMainFile().name.replace(/\.[^/.]+$/, ""); // Get the file's package name var pkgReg = /package\s+([\w\.]+)\s*;/; var packageName = pkgReg.exec(FileManager.getMainFile().contents); // Add the package name to the class's name if (packageName === null || packageName.length < 2) { packageName = ["package", "default"]; } // Prepare the request to run the code // Set up the request body for a compile-run request var body = { version: 1, compile: { version: 1, mainClass: packageName[1] + "." + mainName, mainFile: mainName, sourceFiles: [] }, data: { version: 1, dataFiles: [] }, "test-type": "run" }; var root = FileManager.getRootFolder(); // Add the files in the global file manager to the request body. addAllSourceFiles(root, body.compile.sourceFiles, true); // Add data files to the request addAllDataFiles(root, body.data.dataFiles); let newWindow = window.open('./cheerpjConsole.html'); newWindow.compileData = body; }
/* * Run the code contained in the file manager, by compiling everything and * executing the main class, then display the result. */ /* global FileManager */ function runCodeCheerp() { // Get the main class's actual name.. // drop the .java extension var mainFile = FileManager.getMainFile().name; var mainName = mainFile.replace(/\.[^/.]+$/, ""); // Get the file's package name var pkgReg = /package\s+([\w\.]+)\s*;/; var packageName = pkgReg.exec(FileManager.getMainFile().contents); // Add the package name to the class's name if (packageName === null || packageName.length < 2) { packageName = ["package", "default"]; } // Prepare the request to run the code // Set up the request body for a compile-run request var body = { version: 1, compile: { version: 1, mainClass: packageName[1] + "." + mainName, mainFile: mainFile, sourceFiles: [] }, data: { version: 1, dataFiles: [] }, "test-type": "run" }; var root = FileManager.getRootFolder(); // Add the files in the global file manager to the request body. addAllSourceFiles(root, body.compile.sourceFiles, true); // Add data files to the request addAllDataFiles(root, body.data.dataFiles); let newWindow = window.open('./cheerpjConsole.html'); newWindow.compileData = body; }
Use Config constructor instead of deprecated named one
<?php $config = new PhpCsFixer\Config(); return $config ->setRiskyAllowed(true) ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, 'array_syntax' => [ 'syntax' => 'short' ], 'combine_consecutive_unsets' => true, 'heredoc_to_nowdoc' => true, 'no_extra_blank_lines' => [ 'tokens' => [ 'break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block' ], ], 'no_unreachable_default_argument_value' => true, 'no_useless_else' => true, 'no_useless_return' => true, 'ordered_class_elements' => true, 'ordered_imports' => true, 'php_unit_strict' => true, 'phpdoc_order' => true, // 'psr_autoloading' => true, 'strict_comparison' => true, 'strict_param' => true, 'concat_space' => [ 'spacing' => 'one' ], ]) ->setFinder( PhpCsFixer\Finder::create() ->exclude([ 'node_modules', 'vendor', 'var', 'web' ]) ->in(__DIR__) ) ->setCacheFile('.php-cs-fixer.cache') ;
<?php return PhpCsFixer\Config::create() ->setRiskyAllowed(true) ->setRules([ '@Symfony' => true, '@Symfony:risky' => true, 'array_syntax' => [ 'syntax' => 'short' ], 'combine_consecutive_unsets' => true, 'heredoc_to_nowdoc' => true, 'no_extra_blank_lines' => [ 'tokens' => [ 'break', 'continue', 'extra', 'return', 'throw', 'use', 'parenthesis_brace_block', 'square_brace_block', 'curly_brace_block' ], ], 'no_unreachable_default_argument_value' => true, 'no_useless_else' => true, 'no_useless_return' => true, 'ordered_class_elements' => true, 'ordered_imports' => true, 'php_unit_strict' => true, 'phpdoc_order' => true, // 'psr_autoloading' => true, 'strict_comparison' => true, 'strict_param' => true, 'concat_space' => [ 'spacing' => 'one' ], ]) ->setFinder( PhpCsFixer\Finder::create() ->exclude([ 'node_modules', 'vendor', 'var', 'web' ]) ->in(__DIR__) ) ->setCacheFile('.php-cs-fixer.cache') ;
Remove implementation of final method Related to #4
<?php namespace Bolt\Extension\royallthefourth\CodeHighlightBolt; use Bolt\Asset\File\JavaScript; use Bolt\Asset\Snippet\Snippet; use Bolt\Asset\File\Stylesheet; use Bolt\Asset\Target; use Bolt\Extension\SimpleExtension; /** * CodeHighlightBolt extension class. * * @author Royall Spence <[email protected]> */ class CodeHighlightBoltExtension extends SimpleExtension { /** * {@inheritdoc} */ protected function registerAssets() { $config = $this->getConfig(); $theme = $config['theme']; $jsInit = new Snippet(); $jsInit->setCallback([$this, 'jsInitSnippet']) ->setLocation(Target::AFTER_JS) ->setPriority(99) ; return [ new JavaScript('assets/highlightjs/highlight.pack.min.js'), new Stylesheet("assets/highlightjs/styles/{$theme}.css"), $jsInit, ]; } public function jsInitSnippet() { return '<script>hljs.initHighlightingOnLoad();</script>'; } /** * {@inheritdoc} */ protected function getDefaultConfig() { return [ 'theme' => 'monokai' ]; } }
<?php namespace Bolt\Extension\royallthefourth\CodeHighlightBolt; use Bolt\Asset\File\JavaScript; use Bolt\Asset\Snippet\Snippet; use Bolt\Asset\File\Stylesheet; use Bolt\Asset\Target; use Bolt\Extension\SimpleExtension; /** * CodeHighlightBolt extension class. * * @author Royall Spence <[email protected]> */ class CodeHighlightBoltExtension extends SimpleExtension { public function getName() { return "Code Highlight"; } /** * {@inheritdoc} */ protected function registerAssets() { $config = $this->getConfig(); $theme = $config['theme']; $jsInit = new Snippet(); $jsInit->setCallback([$this, 'jsInitSnippet']) ->setLocation(Target::AFTER_JS) ->setPriority(99) ; return [ new JavaScript('assets/highlightjs/highlight.pack.min.js'), new Stylesheet("assets/highlightjs/styles/{$theme}.css"), $jsInit, ]; } public function jsInitSnippet() { return '<script>hljs.initHighlightingOnLoad();</script>'; } /** * {@inheritdoc} */ protected function getDefaultConfig() { return [ 'theme' => 'monokai' ]; } }
Fix buglet in compact testing
"""Tests for the PythonPoint tool. """ import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): "Some very crude tests on PythonPoint." def test0(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath rlDir = abspath(dirname(reportlab.__file__)) from reportlab.tools.pythonpoint import pythonpoint from reportlab.lib.utils import isCompactDistro, open_for_read ppDir = dirname(pythonpoint.__file__) xml = join(ppDir, 'demos', 'pythonpoint.xml') datafilename = 'pythonpoint.pdf' outDir = outputfile('') if isCompactDistro(): cwd = None xml = open_for_read(xml) else: cwd = os.getcwd() os.chdir(join(ppDir, 'demos')) pdf = join(outDir, datafilename) if isfile(pdf): os.remove(pdf) pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename) if cwd: os.chdir(cwd) assert os.path.exists(pdf) def makeSuite(): return makeSuiteForClasses(PythonPointTestCase) #noruntests if __name__ == "__main__": unittest.TextTestRunner().run(makeSuite())
"""Tests for the PythonPoint tool. """ import os, sys, string from reportlab.test import unittest from reportlab.test.utils import makeSuiteForClasses, outputfile import reportlab class PythonPointTestCase(unittest.TestCase): "Some very crude tests on PythonPoint." def test0(self): "Test if pythonpoint.pdf can be created from pythonpoint.xml." join, dirname, isfile, abspath = os.path.join, os.path.dirname, os.path.isfile, os.path.abspath rlDir = abspath(dirname(reportlab.__file__)) from reportlab.tools.pythonpoint import pythonpoint from reportlab.lib.utils import isCompactDistro, open_for_read ppDir = dirname(pythonpoint.__file__) xml = join(ppDir, 'demos', 'pythonpoint.xml') datafilename = 'pythonpoint.pdf' outdir = outputfile('') if isCompactDistro(): cwd = None xml = open_for_read(xml) else: outDir = join(rlDir, 'test') cwd = os.getcwd() os.chdir(join(ppDir, 'demos')) pdf = join(outDir, datafilename) if isfile(pdf): os.remove(pdf) pythonpoint.process(xml, outDir=outDir, verbose=0, datafilename=datafilename) if cwd: os.chdir(cwd) assert os.path.exists(pdf) os.remove(pdf) def makeSuite(): return makeSuiteForClasses(PythonPointTestCase) #noruntests if __name__ == "__main__": unittest.TextTestRunner().run(makeSuite())
Add 'host_node' and 'host_cluster' properties to container profile Add 'host_node' and 'host_cluster' properties to container profile, in a container profile, either 'host_node' or 'host_cluster' will be assigned a value for a container node creation or a container cluster creation. blueprint container-profile-support Change-Id: Ief464375bf651ebe1770c3fcf0488f29b25a94f4
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin.common.i18n import _ from senlin.common import schema from senlin.profiles import base class DockerProfile(base.Profile): """Profile for a docker container.""" KEYS = ( CONTEXT, IMAGE, NAME, COMMAND, HOST_NODE, HOST_CLUSTER ) = ( 'context', 'image', 'name', 'command', 'host_node', 'host_cluster', ) properties_schema = { CONTEXT: schema.Map( _('Customized security context for operationg containers.') ), IMAGE: schema.String( _('The image used to create a container') ), NAME: schema.String( _('The name of the container.') ), COMMAND: schema.String( _('The command to run when container is started.') ), HOST_NODE: schema.String( _('The node on which container will be launched.') ), HOST_CLUSTER: schema.String( _('The cluster on which container cluster will be launched.') ), } def __init__(self, type_name, name, **kwargs): super(DockerProfile, self).__init__(type_name, name, **kwargs) self._dockerclient = None
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from senlin.common.i18n import _ from senlin.common import schema from senlin.profiles import base class DockerProfile(base.Profile): """Profile for a docker container.""" KEYS = ( CONTEXT, IMAGE, NAME, COMMAND, ) = ( 'context', 'image', 'name', 'command', ) properties_schema = { CONTEXT: schema.Map( _('Customized security context for operationg containers.') ), IMAGE: schema.String( _('The image used to create a container') ), NAME: schema.String( _('The name of the container.') ), COMMAND: schema.String( _('The command to run when container is started.') ), } def __init__(self, type_name, name, **kwargs): super(DockerProfile, self).__init__(type_name, name, **kwargs) self._dockerclient = None
Update URL to github repository.
from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-MusicBox-Webclient', version=get_version('mopidy_musicbox_webclient/__init__.py'), url='https://github.com/pimusicbox/mopidy-musicbox-webclient', license='Apache License, Version 2.0', author='Wouter van Wijk', author_email='[email protected]', description='Mopidy MusicBox web extension', long_description=open('README.rst').read(), packages=find_packages(exclude=['tests', 'tests.*']), zip_safe=False, include_package_data=True, install_requires=[ 'setuptools', 'Mopidy >= 1.1.0', ], entry_points={ 'mopidy.ext': [ 'musicbox_webclient = mopidy_musicbox_webclient:Extension', ], }, classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia :: Sound/Audio :: Players', ], )
from __future__ import unicode_literals import re from setuptools import find_packages, setup def get_version(filename): content = open(filename).read() metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", content)) return metadata['version'] setup( name='Mopidy-MusicBox-Webclient', version=get_version('mopidy_musicbox_webclient/__init__.py'), url='https://github.com/woutervanwijk/mopidy-musicbox-webclient', license='Apache License, Version 2.0', author='Wouter van Wijk', author_email='[email protected]', description='Mopidy MusicBox web extension', long_description=open('README.rst').read(), packages=find_packages(exclude=['tests', 'tests.*']), zip_safe=False, include_package_data=True, install_requires=[ 'setuptools', 'Mopidy >= 1.1.0', ], entry_points={ 'mopidy.ext': [ 'musicbox_webclient = mopidy_musicbox_webclient:Extension', ], }, classifiers=[ 'Environment :: No Input/Output (Daemon)', 'Intended Audience :: End Users/Desktop', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Topic :: Multimedia :: Sound/Audio :: Players', ], )
Fix return types for update and remove
import { NativeModules } from 'react-native'; const NativeRnRecord = NativeModules.RnRecord; export default class RnRecord { id: Number; save(): Promise<Number> { return NativeRnRecord.save(this.constructor.name, this._getProperties()).then(id => { this.id = id; return id; }); } update(): Promise<Boolean> { return NativeRnRecord.update(this.constructor.name, this._getProperties()).then(res => res != -1); } remove(): Promise<Boolean> { return NativeRnRecord.remove(this.constructor.name, this._getProperties()).then(res => res != -1); } static findAll(): Promise<Array> { return NativeRnRecord.findAll(this.name).then(records => records.map(rec => this._transformResultObj(this.name, rec))); } static find(query: Object): Promise<Array> { return NativeRnRecord.find(this.name, query).then(records => records.map(rec => this._transformResultObj(this.name, rec))); } static _transformResultObj(className: String, obj: Object) { const inst = new this(); Object.getOwnPropertyNames(obj).forEach(k => { inst[k] = obj[k]; }); return inst; } _getProperties(): Object { const propNames = Object.getOwnPropertyNames(this); return propNames.reduce( (obj, name) => { obj[name] = this[name] return obj; }, {}); } }
import { NativeModules } from 'react-native'; const NativeRnRecord = NativeModules.RnRecord; export default class RnRecord { id: Number; save(): Promise<Number> { return NativeRnRecord.save(this.constructor.name, this._getProperties()); } update(): Promise<Boolean> { return NativeRnRecord.update(this.constructor.name, this._getProperties()); } remove(): Promise<Boolean> { return NativeRnRecord.remove(this.constructor.name, this._getProperties()); } static findAll(): Promise<Array> { return NativeRnRecord.findAll(this.name).then(records => records.map(rec => this._transformResultObj(this.name, rec))); } static find(query: Object): Promise<Array> { return NativeRnRecord.find(this.name, query).then(records => records.map(rec => this._transformResultObj(this.name, rec))); } static _transformResultObj(className: String, obj: Object) { const inst = new this(); Object.getOwnPropertyNames(obj).forEach(k => { inst[k] = obj[k]; }); return inst; } _getProperties(): Object { const propNames = Object.getOwnPropertyNames(this); return propNames.reduce( (obj, name) => { obj[name] = this[name] return obj; }, {}); } }
:bug: Change id_lvrs_internt to string. Test if there's only one created
import unittest from flask import current_app, url_for, get_flashed_messages from app import create_app, db from app.models import * class TestCreateAdmissionView(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True) self.valid_admission_form = { 'id_lvrs_intern': 1, } def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_duplicate_id_lvrs_intern(self): a = Admission(id_lvrs_intern=1) db.session.add(a) db.session.commit() data = { 'id_lvrs_intern': '1', 'samples-0-collection_date': '12/12/2012', 'samples-0-admission_date': '13/12/2012', } duplicate_id_lvrs_intern = 'Número Interno já cadastrado!' response = self.client.post( url_for('main.create_admission'), data=data, follow_redirects=True) self.assertTrue( duplicate_id_lvrs_intern in response.get_data(as_text=True)) self.assertTrue( len(Admission.query.filter_by(id_lvrs_intern='1').all()), 1)
import unittest from flask import current_app, url_for, get_flashed_messages from app import create_app, db from app.models import * class TestCreateAdmissionView(unittest.TestCase): def setUp(self): self.app = create_app('testing') self.app_context = self.app.app_context() self.app_context.push() db.create_all() self.client = self.app.test_client(use_cookies=True) self.valid_admission_form = { 'id_lvrs_intern': 1, } def tearDown(self): db.session.remove() db.drop_all() self.app_context.pop() def test_duplicate_id_lvrs_intern(self): a = Admission(id_lvrs_intern=1) db.session.add(a) db.session.commit() data = { 'id_lvrs_intern': 1, 'samples-0-collection_date': '12/12/2012', 'samples-0-admission_date': '13/12/2012', } duplicate_id_lvrs_intern = 'Número Interno já cadastrado!' response = self.client.post( url_for('main.create_admission'), data=data, follow_redirects=True) self.assertTrue( duplicate_id_lvrs_intern in response.get_data(as_text=True))
fix: Add x-frigg-worker-token header to hq requests This will in time be to remove the FRIGG_WORKER_TOKEN header.
# -*- coding: utf-8 -*- import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-token': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
# -*- coding: utf-8 -*- import logging import socket import requests logger = logging.getLogger(__name__) class APIWrapper(object): def __init__(self, options): self.token = options['hq_token'] self.url = options['hq_url'] @property def headers(self): return { 'content-type': 'application/json', 'FRIGG_WORKER_TOKEN': self.token, 'x-frigg-worker-host': socket.getfqdn() } def get(self, url): return requests.post(url, headers=self.headers) def post(self, url, data): return requests.post(url, data=data, headers=self.headers) def report_run(self, endpoint, build_id, build): response = self.post(self.url, data=build) logger.info('Reported build to hq, hq response status-code: {0}, data:\n{1}'.format( response.status_code, build )) if response.status_code != 200: logger.error('Report of build failed, response status-code: {0}, data:\n{1}'.format( response.status_code, build )) with open('build-{0}-hq-response.html'.format(build_id), 'w') as f: f.write(response.text) return response
Reset prefs that are not explicitly passed into setPrefs git-svn-id: 6772fbf0389af6646c0263f7120f2a1d688953ed@5182 e969d3be-0e28-0410-a27f-dd5c76401a8b
/* See license.txt for terms of usage */ var Format = {}; Components.utils.import("resource://fireformat/formatters.jsm", Format); var Firebug = FW.Firebug; var FBTestFireformat = { PrefHandler: function(prefs) { var original = [], globals = {}; for (var i = 0; i < prefs.length; i++) { original.push(Firebug.getPref(Firebug.prefDomain, prefs[i])); } return { setGlobal: function(pref, value) { if (!globals.hasOwnProperty(pref)) { globals[pref] = Firebug.getPref(Firebug.prefDomain, pref); } Firebug.setPref(Firebug.prefDomain, pref, value); }, setPrefs: function() { for (var i = 0; i < arguments.length; i++) { Firebug.setPref(Firebug.prefDomain, prefs[i], arguments[i]); } for (; i < prefs.length; i++) { Firebug.setPref(Firebug.prefDomain, prefs[i], original[i]); } }, reset: function() { this.setPrefs.apply(this, original); for (var x in globals) { if (globals.hasOwnProperty(x)) { Firebug.setPref(Firebug.prefDomain, x, globals[x]); } } globals = {}; } }; } };
/* See license.txt for terms of usage */ var Format = {}; Components.utils.import("resource://fireformat/formatters.jsm", Format); var Firebug = FW.Firebug; var FBTestFireformat = { PrefHandler: function(prefs) { var original = [], globals = {}; for (var i = 0; i < prefs.length; i++) { original.push(Firebug.getPref(Firebug.prefDomain, prefs[i])); } return { setGlobal: function(pref, value) { if (!globals.hasOwnProperty(pref)) { globals[pref] = Firebug.getPref(Firebug.prefDomain, pref); } Firebug.setPref(Firebug.prefDomain, pref, value); }, setPrefs: function() { for (var i = 0; i < arguments.length; i++) { Firebug.setPref(Firebug.prefDomain, prefs[i], arguments[i]); } }, reset: function() { this.setPrefs.apply(this, original); for (var x in globals) { if (globals.hasOwnProperty(x)) { Firebug.setPref(Firebug.prefDomain, x, globals[x]); } } globals = {}; } }; } };
Remove "sh" command from script execution
package x1125io.initdlight; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootReceiver extends BroadcastReceiver { final String TAG = "initdlight"; @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { for (String file: context.getFilesDir().list()) { ProcessRunner pr = new ProcessRunner(); String fullFilePath = context.getFilesDir().toString() + "/" + file; int exitCode = pr.Run(new String[] { "su", "-c", fullFilePath }); if (exitCode == 0) { Log.d(TAG, "started " + file); } else { Log.d(TAG, String.format( "error starting %s; exit code: %d; stdout: %s; stderr: %s", file, exitCode, pr.getStdout(), pr.getStderr() )); } } } } }
package x1125io.initdlight; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootReceiver extends BroadcastReceiver { final String TAG = "initdlight"; @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { for (String file: context.getFilesDir().list()) { ProcessRunner pr = new ProcessRunner(); String fullFilePath = context.getFilesDir().toString() + "/" + file; int exitCode = pr.Run(new String[] { "su", "-c", "sh " + fullFilePath }); if (exitCode == 0) { Log.d(TAG, "started " + file); } else { Log.d(TAG, String.format( "error starting %s; exit code: %d; stdout: %s; stderr: %s", file, exitCode, pr.getStdout(), pr.getStderr() )); } } } } }
Use getShortCode() instead of enum name()
package com.alexstyl.specialdates.events.namedays; import android.support.annotation.RawRes; import com.alexstyl.specialdates.R; import com.novoda.notils.exception.DeveloperError; public enum NamedayLocale { GREEK("gr", true, R.raw.gr_namedays), ROMANIAN("ro", false, R.raw.ro_namedays), RUSSIAN("ru", false, R.raw.ru_namedays), LATVIAN("lv", false, R.raw.lv_namedays), SLOVAK("sk", false, R.raw.sk_namedays), CZECH("cs", false, R.raw.cs_namedays); private final String shortCode; private final boolean soundCompared; private final int rawResId; NamedayLocale(String shortCode, boolean soundCompared, @RawRes int rawResId) { this.shortCode = shortCode; this.soundCompared = soundCompared; this.rawResId = rawResId; } public static NamedayLocale from(String displayLanguage) { for (NamedayLocale locale : values()) { if (locale.getShortCode().equalsIgnoreCase(displayLanguage)) { return locale; } } throw new DeveloperError("No NamedayLocale found for [%s]", displayLanguage); } public int getRawResId() { return rawResId; } public boolean isComparedBySound() { return soundCompared; } public String getShortCode() { return shortCode; } }
package com.alexstyl.specialdates.events.namedays; import android.support.annotation.RawRes; import com.alexstyl.specialdates.R; import com.novoda.notils.exception.DeveloperError; public enum NamedayLocale { GREEK("gr", true, R.raw.gr_namedays), ROMANIAN("ro", false, R.raw.ro_namedays), RUSSIAN("ru", false, R.raw.ru_namedays), LATVIAN("lv", false, R.raw.lv_namedays), SLOVAK("sk", false, R.raw.sk_namedays), CZECH("cs", false, R.raw.cs_namedays); private final String shortCode; private final boolean soundCompared; private final int rawResId; NamedayLocale(String shortCode, boolean soundCompared, @RawRes int rawResId) { this.shortCode = shortCode; this.soundCompared = soundCompared; this.rawResId = rawResId; } public static NamedayLocale from(String displayLanguage) { for (NamedayLocale locale : values()) { if (locale.name().equalsIgnoreCase(displayLanguage)) { return locale; } } throw new DeveloperError("No NamedayLocale found for [%s]", displayLanguage); } public int getRawResId() { return rawResId; } public boolean isComparedBySound() { return soundCompared; } public String getShortCode() { return shortCode; } }
Allow space,dash,apostrophe in name searches
'use strict'; let content = require('./content.js'); function validateInputs(err, obj) { err.items = []; let errCount = 0; if (obj.forename && !isString(obj.forename)) { err.items[errCount++] = {forename: 'Correct the forename'}; } if (obj.forename2 && !isString(obj.forename2)) { err.items[errCount++] = {forename2: 'Correct the middle name'}; } if (obj.surname && !isString(obj.surname)) { err.items[errCount++] = {surname: 'Correct the surname'}; } return errCount; } module.exports = { validate: function(obj, callback) { let err = { title: content.errMsg.CANNOT_SUBMIT, items: [{forename: 'Enter forename'}, {forename2: 'Enter middle name'}, {surname: 'Enter surname'}], desc: content.errMsg.ATLEAST_ONE_REQUIRED }; if (!obj.forename && !obj.forename2 && !obj.surname) { return callback(err); } let errCount = validateInputs(err, obj); if (errCount > 0) { return callback(err); } return callback(null); } }; function isString(v) { return /^[\sA-Za-z%_'-]+$/.test(v); }
'use strict'; let content = require('./content.js'); function validateInputs(err, obj) { err.items = []; let errCount = 0; if (obj.forename && !isString(obj.forename)) { err.items[errCount++] = {forename: 'Correct the forename'}; } if (obj.forename2 && !isString(obj.forename2)) { err.items[errCount++] = {forename2: 'Correct the middle name'}; } if (obj.surname && !isString(obj.surname)) { err.items[errCount++] = {surname: 'Correct the surname'}; } return errCount; } module.exports = { validate: function(obj, callback) { let err = { title: content.errMsg.CANNOT_SUBMIT, items: [{forename: 'Enter forename'}, {forename2: 'Enter middle name'}, {surname: 'Enter surname'}], desc: content.errMsg.ATLEAST_ONE_REQUIRED }; if (!obj.forename && !obj.forename2 && !obj.surname) { return callback(err); } let errCount = validateInputs(err, obj); if (errCount > 0) { return callback(err); } return callback(null); } }; function isString(v) { return /^[A-Za-z%_]+$/.test(v); }
Make blockArrayList static Make setBlockArray static method
package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; blockIndex = -1; } public Line(String input,int index, boolean whiteSpace) { content = input; blockIndex = index; isWhitespace = whiteSpace; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public static void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } }
package model; import java.util.ArrayList; /** * Created by ano on 2016. 5. 18.. */ public class Line { private String content;//이 라인이 가지고 있는 컨텐츠 private int blockIndex; // 이 라인이 속해있는 블럭의 index. -1이면 속하는 블럭이 없다는 것 private boolean isWhitespace;//compare로 생긴 공백 줄이면 true; private static ArrayList<Block> blockArrayList;//블럭을 가지고 있는 arraylist public Line(String input) { content = input; } public String getLine(boolean isLastLine) //마지막 줄이면 개행을 없이 그것이 아니면 개행 있이 content를 반환합니다 { if(isLastLine) return content; else return content + "\n"; } public enum Highlight//하이라이트 객체 { unHilighted, whitespace, isDifferent,selected } public Highlight getHighlight() { if(blockIndex == -1) return Highlight.unHilighted; else if(isWhitespace) return Highlight.whitespace; else if(blockArrayList.get(blockIndex).getSelected()) return Highlight.selected; else return Highlight.isDifferent; } public void setBlockArray(ArrayList<Block> inArrayList) { blockArrayList = inArrayList; } }
Add file-loader for image resources
const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const webpack = require('webpack'); module.exports = { entry: { vendor: './src/vendor/index.js', mb: './src/mb/index.jsx' }, output: { filename: 'assets/js/[name].js', chunkFilename: 'assets/js/chunk.[id].js', path: path.resolve(__dirname, 'public'), publicPath: '/' }, devServer: { contentBase: path.resolve(__dirname, 'public'), }, resolve: { extensions: ['.js', '.jsx'], alias: { 'normalize.css': path.resolve(__dirname, './node_modules/normalize.css/normalize.css') } }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'less-loader'] }) }, { test: /\.jpg$/, loader: 'url-loader?limit=10240' }, { test: /\.png$/, loader: 'url-loader?limit=10240' }, { test: /\.html$/, use: [ 'file-loader?name=[name].html', 'extract-loader', 'html-loader' ] } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: 'vendor' }), new ExtractTextPlugin('assets/css/[name].css') ] };
const path = require('path'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const webpack = require('webpack'); module.exports = { entry: { vendor: './src/vendor.js', mb: './src/mb/index.jsx' }, output: { filename: 'assets/js/[name].js', chunkFilename: 'assets/js/chunk.[id].js', path: path.resolve(__dirname, 'public'), publicPath: '/' }, devServer: { contentBase: path.resolve(__dirname, 'public'), }, resolve: { extensions: ['.js', '.jsx'], alias: { 'normalize.css': path.resolve(__dirname, './node_modules/normalize.css/normalize.css') } }, module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader' }, { test: /\.less$/, loader: ExtractTextPlugin.extract({ fallback: 'style-loader', use: ['css-loader', 'less-loader'] }) }, { test: /\.html$/, loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader' } ] }, plugins: [ new webpack.optimize.CommonsChunkPlugin({ names: 'vendor' }), new ExtractTextPlugin('assets/css/[name].css') ] };
Add a demo for wwpp
test = { 'name': 'Question 1', 'points': 3, 'suites': [ { 'type': 'concept', 'cases': [ { 'answer': 'Domain is numbers. Range is numbers', 'choices': [ 'Domain is numbers. Range is numbers', 'Domain is numbers. Range is strings', 'Domain is strings. Range is numbers', 'Domain is strings. Range is strings' ], 'hidden': False, 'question': 'What is the domain and range of the square function?' } ], }, { 'type': 'wwpp', 'cases': [ { 'code': r""" >>> square(3) 9 >>> square(5) 25 """ }, { 'code': r""" >>> print(print(square(4))) 16 None """ } ], }, { 'cases': [ { 'code': r""" >>> square(3) 9 """, 'hidden': False }, { 'code': r""" >>> square(2) 4 # explanation: Squaring a negative number """, 'hidden': True }, { 'code': r""" >>> square(0) 0 # explanation: Squaring zero """, 'hidden': True }, { 'code': r""" >>> 1 / square(0) ZeroDivisionError """, 'hidden': True } ], 'scored': True, 'setup': r""" >>> from hw1 import * """, 'teardown': r""" >>> print('Teardown code') """, 'type': 'doctest' } ] }
test = { 'name': 'Question 1', 'points': 3, 'suites': [ { 'cases': [ { 'answer': 'Domain is numbers. Range is numbers', 'choices': [ 'Domain is numbers. Range is numbers', 'Domain is numbers. Range is strings', 'Domain is strings. Range is numbers', 'Domain is strings. Range is strings' ], 'hidden': False, 'question': 'What is the domain and range of the square function?' } ], 'scored': False, 'type': 'concept' }, { 'cases': [ { 'code': r""" >>> square(3) 9 """, 'hidden': False }, { 'code': r""" >>> square(2) 4 # explanation: Squaring a negative number """, 'hidden': True }, { 'code': r""" >>> square(0) 0 # explanation: Squaring zero """, 'hidden': True }, { 'code': r""" >>> 1 / square(0) ZeroDivisionError """, 'hidden': True } ], 'scored': True, 'setup': r""" >>> from hw1 import * """, 'teardown': r""" >>> print('Teardown code') """, 'type': 'doctest' } ] }
Correct argparse dependency - argparse already is a part of base python as of 2.7 and 3.2.
import os from setuptools import setup install_requires = [ 'mysql-python>=1.2.3', 'psycopg2>=2.4.2', 'pyyaml>=3.10.0', 'pytz', ] if os.name == 'posix': install_requires.append('termcolor>=1.1.0') if version < (2,7) or (3,0) <= version <= (3,1): install_requires += ['argparse'] setup( name='py-mysql2pgsql', version='0.1.6', description='Tool for migrating/converting from mysql to postgresql.', long_description=open('README.rst').read(), license='MIT License', author='Philip Southam', author_email='[email protected]', url='https://github.com/philipsoutham/py-mysql2pgsql', zip_safe=False, packages=['mysql2pgsql', 'mysql2pgsql.lib'], scripts=['bin/py-mysql2pgsql'], platforms='any', install_requires=install_requires, classifiers=[ 'License :: OSI Approved :: MIT License', 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: System Administrators', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Utilities' ], keywords = 'mysql postgres postgresql pgsql psql migration', )
import os from setuptools import setup install_requires = [ 'mysql-python>=1.2.3', 'psycopg2>=2.4.2', 'pyyaml>=3.10.0', 'argparse', 'pytz', ] if os.name == 'posix': install_requires.append('termcolor>=1.1.0') setup( name='py-mysql2pgsql', version='0.1.6', description='Tool for migrating/converting from mysql to postgresql.', long_description=open('README.rst').read(), license='MIT License', author='Philip Southam', author_email='[email protected]', url='https://github.com/philipsoutham/py-mysql2pgsql', zip_safe=False, packages=['mysql2pgsql', 'mysql2pgsql.lib'], scripts=['bin/py-mysql2pgsql'], platforms='any', install_requires=install_requires, classifiers=[ 'License :: OSI Approved :: MIT License', 'Development Status :: 3 - Alpha', 'Environment :: Console', 'Intended Audience :: System Administrators', 'Intended Audience :: Developers', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Topic :: Database', 'Topic :: Utilities' ], keywords = 'mysql postgres postgresql pgsql psql migration', )
Fix export_csv_response function to take generator
from django.utils import six from django.http import StreamingHttpResponse def export_csv_response(generator, name='export.csv'): response = StreamingHttpResponse(generator, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % name return response class FakeFile(object): # unicodecsv doesn't return values # so temp store them in here def write(self, string): self._last_string = string if six.PY3: self._last_string = self._last_string.encode('utf-8') def export_csv(queryset, fields): if six.PY3: import csv else: import unicodecsv as csv f = FakeFile() writer = csv.DictWriter(f, fields) writer.writeheader() yield f._last_string for obj in queryset: if hasattr(obj, 'get_dict'): d = obj.get_dict(fields) else: d = {} for field in fields: value = getattr(obj, field, '') if value is None: d[field] = "" else: d[field] = six.text_type(value) writer.writerow(d) yield f._last_string def export_csv_bytes(generator): return six.binary_type().join(generator)
from django.utils import six from django.http import StreamingHttpResponse def export_csv_response(queryset, fields, name='export.csv'): response = StreamingHttpResponse(export_csv(queryset, fields), content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="%s"' % name return response class FakeFile(object): # unicodecsv doesn't return values # so temp store them in here def write(self, string): self._last_string = string if six.PY3: self._last_string = self._last_string.encode('utf-8') def export_csv(queryset, fields): if six.PY3: import csv else: import unicodecsv as csv f = FakeFile() writer = csv.DictWriter(f, fields) writer.writeheader() yield f._last_string for obj in queryset: if hasattr(obj, 'get_dict'): d = obj.get_dict(fields) else: d = {} for field in fields: value = getattr(obj, field, '') if value is None: d[field] = "" else: d[field] = six.text_type(value) writer.writerow(d) yield f._last_string def export_csv_bytes(generator): return six.binary_type().join(generator)
Remove window refernece in UMD build
var webpack = require("webpack"); var libraryName = require("./package.json").name; var withLocalesSuffix = "-i18n"; const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { mode: "production", entry: { [libraryName]: "./src/cronstrue.ts", [libraryName + ".min"]: "./src/cronstrue.ts", [libraryName + withLocalesSuffix]: "./src/cronstrue-i18n.ts", [libraryName + withLocalesSuffix + ".min"]: "./src/cronstrue-i18n.ts" }, output: { path: __dirname + "/dist", filename: "[name].js", library: libraryName, libraryTarget: "umd", // Workaround for webpack 4 umd bug (Ref: https://github.com/webpack/webpack/issues/6522) globalObject: "typeof self !== 'undefined' ? self : this" }, resolve: { extensions: [".js", ".ts"] }, module: { /* * Each loader needs an associated Regex test that goes through each * of the files you've included (or in this case, all files but the * ones in the excluded directories) and finds all files that pass * the test. Then it will apply the loader to that file. I haven't * installed ts-loader yet, but will do that shortly. */ rules: [ { test: /\.ts$/, loader: "ts-loader", options: { compilerOptions: { outDir: "../dist", declaration: true, sourceMap: false } } } ] } };
var webpack = require("webpack"); var libraryName = require("./package.json").name; var withLocalesSuffix = "-i18n"; const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); module.exports = { mode: "production", entry: { [libraryName]: "./src/cronstrue.ts", [libraryName + ".min"]: "./src/cronstrue.ts", [libraryName + withLocalesSuffix]: "./src/cronstrue-i18n.ts", [libraryName + withLocalesSuffix + ".min"]: "./src/cronstrue-i18n.ts" }, output: { path: __dirname + "/dist", filename: "[name].js", library: libraryName, libraryTarget: "umd" }, resolve: { extensions: [".js", ".ts"] }, module: { /* * Each loader needs an associated Regex test that goes through each * of the files you've included (or in this case, all files but the * ones in the excluded directories) and finds all files that pass * the test. Then it will apply the loader to that file. I haven't * installed ts-loader yet, but will do that shortly. */ rules: [ { test: /\.ts$/, loader: "ts-loader", options: { compilerOptions: { outDir: "../dist", declaration: true, sourceMap: false } } } ] } };
Allow iterable in tag helper
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Tags; use Becklyn\RadBundle\Exception\TagNormalizationException; class TagHelper { /** * @param iterable<string|TagInterface|mixed> $tags * * @return string[] */ public static function getTagLabels (iterable $tags) : array { $labels = []; foreach ($tags as $tag) { if (null === $tag) { continue; } if ($tag instanceof TagInterface) { $labels[] = $tag->getTagLabel(); continue; } if (\is_string($tag)) { $labels[] = $tag; continue; } throw new TagNormalizationException(\sprintf( "Can't transform value of type '%s'.", \is_object($tag) ? \get_class($tag) : \gettype($tag) )); } return $labels; } }
<?php declare(strict_types=1); namespace Becklyn\RadBundle\Tags; use Becklyn\RadBundle\Exception\TagNormalizationException; class TagHelper { /** * @param array<string|TagInterface|mixed> $tags * * @return string[] */ public static function getTagLabels (array $tags) : array { $labels = []; foreach ($tags as $tag) { if (null === $tag) { continue; } if ($tag instanceof TagInterface) { $labels[] = $tag->getTagLabel(); continue; } if (\is_string($tag)) { $labels[] = $tag; continue; } throw new TagNormalizationException(\sprintf( "Can't transform value of type '%s'.", \is_object($tag) ? \get_class($tag) : \gettype($tag) )); } return $labels; } }
[Mailer] Fix SmtpEnvelope renaming to Envelope
<?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\Mailer\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mime\RawMessage; /** * Allows the transformation of a Message and the Envelope before the email is sent. * * @author Fabien Potencier <[email protected]> */ final class MessageEvent extends Event { private $message; private $envelope; private $transport; private $queued; public function __construct(RawMessage $message, Envelope $envelope, string $transport, bool $queued = false) { $this->message = $message; $this->envelope = $envelope; $this->transport = $transport; $this->queued = $queued; } public function getMessage(): RawMessage { return $this->message; } public function setMessage(RawMessage $message): void { $this->message = $message; } public function getEnvelope(): Envelope { return $this->envelope; } public function setEnvelope(Envelope $envelope): void { $this->envelope = $envelope; } public function getTransport(): string { return $this->transport; } public function isQueued(): bool { return $this->queued; } }
<?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\Mailer\Event; use Symfony\Component\EventDispatcher\Event; use Symfony\Component\Mailer\Envelope; use Symfony\Component\Mime\RawMessage; /** * Allows the transformation of a Message and the SMTP Envelope before the email is sent. * * @author Fabien Potencier <[email protected]> */ final class MessageEvent extends Event { private $message; private $envelope; private $transport; private $queued; public function __construct(RawMessage $message, Envelope $envelope, string $transport, bool $queued = false) { $this->message = $message; $this->envelope = $envelope; $this->transport = $transport; $this->queued = $queued; } public function getMessage(): RawMessage { return $this->message; } public function setMessage(RawMessage $message): void { $this->message = $message; } public function getEnvelope(): SmtpEnvelope { return $this->envelope; } public function setEnvelope(SmtpEnvelope $envelope): void { $this->envelope = $envelope; } public function getTransport(): string { return $this->transport; } public function isQueued(): bool { return $this->queued; } }
Use environment variable for URL base
import React from "react"; // eslint-disable-line no-unused-vars class CountryMap extends React.Component { constructor(props) { super(props); this.state = { SVG: "" }; } componentWillMount() { let component = this; // TODO move to country-specific bucket or at least folder fetch(process.env.REACT_APP_ASSETS_URL + this.props.countrycode + ".svg") .then(function(response) { return response.text(); }) .then(function(SVGtext) { let svg = '<svg class="country-map" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><style type="text/css"><![CDATA[.country-map path {stroke: none;fill: #d8382c;}]]></style></defs>' + SVGtext + "</svg>"; component.setState({ SVG: svg }); }); } render() { return ( <div> <div dangerouslySetInnerHTML={{ __html: this.state.SVG }} /> {this.props.city ? <p className="case-location"> {this.props.city}, {this.props.countrycode} </p> : <p className="case-location">{this.props.countrycode}</p>} </div> ); } } export default CountryMap;
import React from "react"; // eslint-disable-line no-unused-vars class CountryMap extends React.Component { constructor(props) { super(props); this.state = { SVG: "" }; } componentWillMount() { let component = this; // TODO move to country-specific bucket or at least folder fetch( "https://s3.amazonaws.com/assets.participedia.xyz/" + this.props.countrycode + ".svg" ) .then(function(response) { return response.text(); }) .then(function(SVGtext) { let svg = '<svg class="country-map" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs><style type="text/css"><![CDATA[.country-map path {stroke: none;fill: #d8382c;}]]></style></defs>' + SVGtext + "</svg>"; component.setState({ SVG: svg }); }); } render() { return ( <div> <div dangerouslySetInnerHTML={{ __html: this.state.SVG }} /> {this.props.city ? <p className="case-location"> {this.props.city}, {this.props.countrycode} </p> : <p className="case-location">{this.props.countrycode}</p>} </div> ); } } export default CountryMap;
CBPS-186: Fix condition for FTS stats collection Currently, stats collection for processes such as indexer and cbq-engine is disabled due to a wrong "if" statement. The "settings object" always has "fts_server" attribute. We should check its boolean value instead. Change-Id: I017f4758f3603e674f094af27b6293716796418a Reviewed-on: http://review.couchbase.org/67781 Tested-by: buildbot <[email protected]> Reviewed-by: Pavel Paulau <[email protected]>
from cbagent.collectors import Collector from cbagent.collectors.libstats.psstats import PSStats class PS(Collector): COLLECTOR = "atop" # Legacy KNOWN_PROCESSES = ("beam.smp", "memcached", "indexer", "projector", "cbq-engine") def __init__(self, settings): super(PS, self).__init__(settings) self.nodes = settings.hostnames or list(self.get_nodes()) if hasattr(settings, "monitor_clients") and settings.monitor_clients\ and settings.master_node in settings.monitor_clients: self.nodes = settings.monitor_clients self.KNOWN_PROCESSES = ("backup", "cbbackupwrapper", ) if hasattr(settings, "fts_server") and settings.fts_server: self.KNOWN_PROCESSES = ("beam.smp", "memcached", "cbft",) self.ps = PSStats(hosts=self.nodes, user=self.ssh_username, password=self.ssh_password) def update_metadata(self): self.mc.add_cluster() for node in self.nodes: self.mc.add_server(node) def sample(self): for process in self.KNOWN_PROCESSES: for node, stats in self.ps.get_samples(process).items(): if stats: self.update_metric_metadata(stats.keys(), server=node) self.store.append(stats, cluster=self.cluster, server=node, collector=self.COLLECTOR)
from cbagent.collectors import Collector from cbagent.collectors.libstats.psstats import PSStats class PS(Collector): COLLECTOR = "atop" # Legacy KNOWN_PROCESSES = ("beam.smp", "memcached", "indexer", "projector", "cbq-engine") def __init__(self, settings): super(PS, self).__init__(settings) self.nodes = settings.hostnames or list(self.get_nodes()) if hasattr(settings, "monitor_clients") and settings.monitor_clients\ and settings.master_node in settings.monitor_clients: self.nodes = settings.monitor_clients self.KNOWN_PROCESSES = ("backup", "cbbackupwrapper", ) if hasattr(settings, "fts_server"): self.KNOWN_PROCESSES = ("beam.smp", "memcached", "cbft",) self.ps = PSStats(hosts=self.nodes, user=self.ssh_username, password=self.ssh_password) def update_metadata(self): self.mc.add_cluster() for node in self.nodes: self.mc.add_server(node) def sample(self): for process in self.KNOWN_PROCESSES: for node, stats in self.ps.get_samples(process).items(): if stats: self.update_metric_metadata(stats.keys(), server=node) self.store.append(stats, cluster=self.cluster, server=node, collector=self.COLLECTOR)
Handle error bags as well as single messaged errors
<?php declare(strict_types=1); namespace Cortex\Foundation\Http\Middleware; use Closure; use Illuminate\Support\ViewErrorBag; use Krucas\Notification\Middleware\NotificationMiddleware as Middleware; class NotificationMiddleware extends Middleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { $containers = $this->session->get($this->key, []); if (count($containers) > 0) { foreach ($containers as $name => $messages) { /** @var \Krucas\Notification\Message $message */ foreach ($messages as $message) { $this->notification->container($name)->add($message->getType(), $message, false); } } } foreach (config('notification.default_types') as $type) { if ($request->session()->has($type)) { $message = $request->session()->get($type); if ($message instanceof ViewErrorBag) { foreach ($message->messages() as $key => $values) { $message = $values[0]; } } $this->notification->container(null)->add($type, $message, false); } } $this->session->forget($this->key); return $next($request); } }
<?php declare(strict_types=1); namespace Cortex\Foundation\Http\Middleware; use Closure; use Krucas\Notification\Middleware\NotificationMiddleware as Middleware; class NotificationMiddleware extends Middleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { $containers = $this->session->get($this->key, []); if (count($containers) > 0) { foreach ($containers as $name => $messages) { /** @var \Krucas\Notification\Message $message */ foreach ($messages as $message) { $this->notification->container($name)->add($message->getType(), $message, false); } } } foreach (config('notification.default_types') as $type) { if ($request->session()->has($type)) { $message = $request->session()->get($type); $this->notification->container(null)->add($type, $message, false); } } $this->session->forget($this->key); return $next($request); } }
Install Python Markdown when installing cmsplugin-simple-markdown.
from setuptools import setup setup( name='cmsplugin-simple-markdown', version=".".join(map(str, __import__('cmsplugin_simple_markdown').__version__)), packages=['cmsplugin_simple_markdown', 'cmsplugin_simple_markdown.migrations'], package_dir={'cmsplugin_simple_markdown': 'cmsplugin_simple_markdown'}, package_data={'cmsplugin_simple_markdown': ['templates/*/*']}, install_requires=['markdown'], url='https://www.github.com/Alir3z4/cmsplugin-simple-markdown', license=open('LICENSE').read(), author='Alireza Savand', author_email='[email protected]', description='A plugin for django-cms that provides just a markdown plugin and nothing more.', long_description=open('README.rst').read(), keywords=[ 'django', 'django-cms', 'web', 'cms', 'cmsplugin', 'plugin', ], platforms='OS Independent', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Framework :: Django', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development' ], )
from distutils.core import setup setup( name='cmsplugin-simple-markdown', version=".".join(map(str, __import__('cmsplugin_simple_markdown').__version__)), packages=['cmsplugin_simple_markdown', 'cmsplugin_simple_markdown.migrations'], package_dir={'cmsplugin_simple_markdown': 'cmsplugin_simple_markdown'}, package_data={'cmsplugin_simple_markdown': ['templates/*/*']}, url='https://www.github.com/Alir3z4/cmsplugin-simple-markdown', license=open('LICENSE').read(), author='Alireza Savand', author_email='[email protected]', description='A plugin for django-cms that provides just a markdown plugin and nothing more.', long_description=open('README.rst').read(), keywords=[ 'django', 'django-cms', 'web', 'cms', 'cmsplugin', 'plugin', ], platforms='OS Independent', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Programming Language :: Python', 'Framework :: Django', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Software Development' ], )
Fix issue with startup of admin-web
package io.fundrequest.platform.admin; import io.fundrequest.common.FundRequestCommon; import io.fundrequest.common.infrastructure.IgnoreDuringComponentScan; import io.fundrequest.core.FundRequestCore; import io.fundrequest.platform.github.FundRequestGithub; import io.fundrequest.platform.keycloak.FundRequestKeycloak; import io.fundrequest.platform.profile.ProfileApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( basePackageClasses = { AdminApplication.class, FundRequestKeycloak.class, FundRequestGithub.class, FundRequestCommon.class, FundRequestCore.class, ProfileApplication.class, }, excludeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class), @ComponentScan.Filter(IgnoreDuringComponentScan.class)}) public class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); } }
package io.fundrequest.platform.admin; import io.fundrequest.common.infrastructure.IgnoreDuringComponentScan; import io.fundrequest.core.FundRequestCore; import io.fundrequest.platform.github.FundRequestGithub; import io.fundrequest.platform.keycloak.FundRequestKeycloak; import io.fundrequest.platform.profile.ProfileApplication; import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringBootConfiguration; import org.springframework.boot.autoconfigure.AutoConfigurationExcludeFilter; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.context.TypeExcludeFilter; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.FilterType; @SpringBootConfiguration @EnableAutoConfiguration @ComponentScan( basePackageClasses = { AdminApplication.class, FundRequestKeycloak.class, FundRequestGithub.class, FundRequestCore.class, ProfileApplication.class, }, excludeFilters = { @ComponentScan.Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class), @ComponentScan.Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class), @ComponentScan.Filter(IgnoreDuringComponentScan.class)}) public class AdminApplication { public static void main(String[] args) { SpringApplication.run(AdminApplication.class, args); } }
[TASK] Fix cache commands for old Magento CE 1.4
<?php namespace N98\Magento\Command\Cache; use N98\Magento\Command\AbstractMagentoCommand; class AbstractCacheCommand extends AbstractMagentoCommand { /** * @return Mage_Core_Model_Cache * @throws \Exception */ protected function _getCacheModel() { if ($this->_magentoMajorVersion == AbstractMagentoCommand::MAGENTO_MAJOR_VERSION_2) { throw new \Exception('There global Mage class was removed from Magento 2. What should we do here?'); return \Mage::getModel('Mage_Core_Model_Cache'); } else { return \Mage::app()->getCacheInstance(); } } /** * Ban cache usage before cleanup to get the latest values. * * @see https://github.com/netz98/n98-magerun/issues/483 */ protected function banUseCache() { if (!is_callable('\Mage_Core_Model_App', 'baseInit')) { return; } $config = $this->getApplication()->getConfig(); if (empty($config['init']['options'])) { $config['init']['options'] = array('global_ban_use_cache' => true); $this->getApplication()->setConfig($config); } } protected function reinitCache() { if (!is_callable('\Mage_Core_Model_App', 'baseInit')) { return; } \Mage::getConfig()->getOptions()->setData('global_ban_use_cache', false); \Mage::app()->baseInit(array()); // Re-init cache \Mage::getConfig()->loadModules()->loadDb()->saveCache(); } }
<?php namespace N98\Magento\Command\Cache; use N98\Magento\Command\AbstractMagentoCommand; class AbstractCacheCommand extends AbstractMagentoCommand { /** * @return Mage_Core_Model_Cache * @throws \Exception */ protected function _getCacheModel() { if ($this->_magentoMajorVersion == AbstractMagentoCommand::MAGENTO_MAJOR_VERSION_2) { throw new \Exception('There global Mage class was removed from Magento 2. What should we do here?'); return \Mage::getModel('Mage_Core_Model_Cache'); } else { return \Mage::app()->getCacheInstance(); } } /** * Ban cache usage before cleanup to get the latest values. * * @see https://github.com/netz98/n98-magerun/issues/483 */ protected function banUseCache() { $config = $this->getApplication()->getConfig(); if (empty($config['init']['options'])) { $config['init']['options'] = array('global_ban_use_cache' => true); $this->getApplication()->setConfig($config); } } protected function reinitCache() { \Mage::getConfig()->getOptions()->setData('global_ban_use_cache', false); \Mage::app()->baseInit(array()); // Re-init cache \Mage::getConfig()->loadModules()->loadDb()->saveCache(); } }
Convert to array, then use Dumpy.
<?php namespace LessCompiler; /** * An AST dumper. */ class TreeDumper { /** * @param \LessCompiler\AbstractSyntaxTree $tree * @return string */ public function dumpTree(AbstractSyntaxTree $tree) { $dumpy = new \PhpPackages\Dumpy\Dumpy; $dumped = []; foreach ($tree as $node) { $dumped[] = $this->dumpValue($node->getValue()); } return $dumpy->dump($dumped); } /** * @param mixed $value * @return array */ protected function dumpValue($value) { $dumped = []; if ( ! is_array($value)) { return $value; } foreach ($value as $key => $anotherValue) { if (is_array($anotherValue)) { $dumped[$key] = $this->dumpValue($anotherValue); } else if ($anotherValue instanceof Node) { $dumped[$key] = $this->dumpValue($anotherValue->getValue()); } else { $dumped[$key] = $anotherValue; } } return $dumped; } }
<?php namespace LessCompiler; /** * An AST dumper. */ class TreeDumper { /** * @param \LessCompiler\AbstractSyntaxTree $tree * @return string */ public function dumpTree(AbstractSyntaxTree $tree) { $output = ""; foreach ($tree as $node) { $output .= $this->dumpNode($node); } return $output; } /** * @param \LessCompiler\Node $node * @return string */ protected function dumpNode(Node $node, $indenting = 0) { $indentation = " "; $output = sprintf( "%s%s:%s", str_repeat($indentation, $indenting + 1), (new \ReflectionClass($node))->getShortName(), PHP_EOL ); if (is_array($node->getValue())) { foreach ($node->getValue() as $key => $value) { if ($value instanceof Node) { $value = $this->dumpNode($value, $indenting + 1); } // Assuming it's not nested. if (is_array($value)) { foreach ($value as $anotherValue) { $output .= $this->dumpNode($anotherValue); } continue; } $output .= sprintf( "%s%s: %s%s", str_repeat($indentation, $indenting + 2), ucfirst($key), $value, PHP_EOL ); } } else { $output = sprintf("%sValue: %s", $indentation, $node->getValue()); } return $output; } /** * @param mixed $value * @return string */ protected function dumpValue($value) { // ... } }
Handle built state tracking on versions
import logging from django import forms from readthedocs.builds.models import VersionAlias, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project from readthedocs.projects.tasks import clear_artifacts log = logging.getLogger(__name__) class AliasForm(forms.ModelForm): class Meta: model = VersionAlias fields = ( 'project', 'from_slug', 'to_slug', 'largest', ) def __init__(self, instance=None, *args, **kwargs): super(AliasForm, self).__init__(instance=instance, *args, **kwargs) if instance: self.fields['project'].queryset = (Project.objects .filter(pk=instance.project.pk)) class VersionForm(forms.ModelForm): class Meta: model = Version fields = ['active', 'privacy_level', 'tags'] def save(self, *args, **kwargs): obj = super(VersionForm, self).save(*args, **kwargs) if obj.active and not obj.built and not obj.uploaded: trigger_build(project=obj.project, version=obj) def clean(self): cleaned_data = super(VersionForm, self).clean() if self.instance.pk is not None: # new instance only if self.instance.active is True and cleaned_data['active'] is False: log.info('Removing files for version %s' % self.instance.slug) clear_artifacts.delay(version_pk=self.instance.pk) self.instance.built = False return cleaned_data
import logging from django import forms from readthedocs.builds.models import VersionAlias, Version from readthedocs.core.utils import trigger_build from readthedocs.projects.models import Project from readthedocs.projects.tasks import clear_artifacts log = logging.getLogger(__name__) class AliasForm(forms.ModelForm): class Meta: model = VersionAlias fields = ( 'project', 'from_slug', 'to_slug', 'largest', ) def __init__(self, instance=None, *args, **kwargs): super(AliasForm, self).__init__(instance=instance, *args, **kwargs) if instance: self.fields['project'].queryset = (Project.objects .filter(pk=instance.project.pk)) class VersionForm(forms.ModelForm): class Meta: model = Version fields = ['active', 'privacy_level', 'tags'] def save(self, *args, **kwargs): obj = super(VersionForm, self).save(*args, **kwargs) if obj.active and not obj.built and not obj.uploaded: trigger_build(project=obj.project, version=obj) def clean(self): cleaned_data = super(VersionForm, self).clean() if self.instance.pk is not None: # new instance only if self.instance.active is True and cleaned_data['active'] is False: log.info('Removing files for version %s' % self.instance.slug) clear_artifacts.delay(version_pk=[self.instance.pk]) return cleaned_data
Fix feate manage news category
<?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Input; use App\Http\Controllers\Controller; class NewsCategoryController extends Controller { public function index() { $newscategories = \App\NewsCategory::All(); return view('admin/newscategory/index')->with('newscategories', $newscategories); } public function create() { $newscategory_cr = \App\NewsCategory::pluck('name', 'id'); return view('admin/newscategory/create')->with('newscategory_cr', $newscategory_cr); } public function edit($id) { $newscategory = \App\NewsCategory::find($id); return view('admin/newscategory/create')->with('newscategory', $newscategory); } public function update($id) { $newscategory = \App\NewsCategory::find($id); $newscategory->update(Input::all()); return redirect('/admin/newscategory') ->withSuccess('Cat has been updated.'); } public function post() { \App\NewsCategory::create(Input::all()); return redirect('/admin/newscategory')->withSuccess('Cat has been created.'); } public function delete($id) { $newcategory = \App\NewsCategory::find($id); $newcategory->delete(); return redirect('/admin/newscategory') ->withSuccess('News Category has been deleted.'); } }
<?php namespace App\Http\Controllers\Admin; use Illuminate\Support\Facades\Input; use App\Http\Controllers\Controller; class NewsCategoryController extends Controller { public function index() { $newscategories = \App\NewsCategory::All(); return view('admin/newscategory/index')->with('newscategories', $newscategories); } public function create() { $newscategory_cr = \App\NewsCategory::pluck('name', 'id'); return view('admin/newscategory/create')->with('newscategory_cr', $newscategory_cr); } public function edit() { $newscategory = \App\NewsCategory::find($id); return view('admin/newscategory/create')->with('newscategory', $newscategory); } public function update() { $newscategory = \App\NewsCategory::find($id); $newscategory->update(Input::all()); return redirect('/admin/newscategory') ->withSuccess('Cat has been updated.'); } public function post() { \App\NewsCategory::create(Input::all()); return redirect('/admin/newscategory')->withSuccess('Cat has been created.'); } public function delete() { $newcategory = \App\NewsCategory::find($id); $newcategory->delete(); return redirect('/admin/newscategory') ->withSuccess('News Category has been deleted.'); } }
Fix datatables export to export all coumns if no visible columns requested
<?php declare(strict_types=1); namespace Cortex\Foundation\Transformers; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Yajra\DataTables\Transformers\DataArrayTransformer as BaseDataArrayTransformer; class DataArrayTransformer extends BaseDataArrayTransformer { /** * Transform row column by collection. * * @override to return headers as db column names, instead of their language titles. * * @param array $row * @param \Illuminate\Support\Collection $columns * @param string $type * * @return array */ protected function buildColumnByCollection(array $row, Collection $columns, $type = 'printable') { $results = []; $visibleCOlumns = request()->get('visible_columnss', []); foreach ($columns->all() as $column) { if ($column[$type] && (! $visibleCOlumns || in_array($column['name'], $visibleCOlumns))) { $title = $column['name']; $data = Arr::get($row, $column['data']); if ($type === 'exportable') { $title = $this->decodeContent($title); $dataType = gettype($data); $data = $this->decodeContent($data); settype($data, $dataType); } $results[$title] = $data; } } return $results; } }
<?php declare(strict_types=1); namespace Cortex\Foundation\Transformers; use Illuminate\Support\Arr; use Illuminate\Support\Collection; use Yajra\DataTables\Transformers\DataArrayTransformer as BaseDataArrayTransformer; class DataArrayTransformer extends BaseDataArrayTransformer { /** * Transform row column by collection. * * @override to return headers as db column names, instead of their language titles. * * @param array $row * @param \Illuminate\Support\Collection $columns * @param string $type * * @return array */ protected function buildColumnByCollection(array $row, Collection $columns, $type = 'printable') { $results = []; foreach ($columns->all() as $column) { if ($column[$type] && in_array($column['name'], request()->get('visible_columns', []))) { $title = $column['name']; $data = Arr::get($row, $column['data']); if ($type === 'exportable') { $title = $this->decodeContent($title); $dataType = gettype($data); $data = $this->decodeContent($data); settype($data, $dataType); } $results[$title] = $data; } } return $results; } }