text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Add a note regarding event items filtration [WAL-1077]
import template from './dashboard-feed.html'; export const projectEventsFeed = { template, bindings: { project: '<' }, controller: class ProjectEventsFeedController { constructor(DashboardFeedService, EventDialogsService, $uibModal) { this.DashboardFeedService = DashboardFeedService; this.$uibModal = $uibModal; this.title = gettext('Events'); this.buttonTitle = gettext('Event types'); this.emptyText = gettext('No events yet.'); this.showTypes = EventDialogsService.eventTypes.bind(EventDialogsService); this.listState = 'project.events({uuid: $ctrl.project.uuid})'; } $onInit() { this.loadItems(); } $onChange() { this.loadItems(); } loadItems() { if (!this.project) { return; } this.loading = true; this.DashboardFeedService.getProjectEvents(this.project).then(items => { this.items = items.filter(item => { // filter out issue update events as there are too many of them. return item.event_type && item.event_type !== 'issue_update_succeeded'; }); }).finally(() => { this.loading = false; }); } showDetails(event) { return this.$uibModal.open({ component: 'eventDetailsDialog', resolve: { event: () => event, } }).result; } } };
import template from './dashboard-feed.html'; export const projectEventsFeed = { template, bindings: { project: '<' }, controller: class ProjectEventsFeedController { constructor(DashboardFeedService, EventDialogsService, $uibModal) { this.DashboardFeedService = DashboardFeedService; this.$uibModal = $uibModal; this.title = gettext('Events'); this.buttonTitle = gettext('Event types'); this.emptyText = gettext('No events yet.'); this.showTypes = EventDialogsService.eventTypes.bind(EventDialogsService); this.listState = 'project.events({uuid: $ctrl.project.uuid})'; } $onInit() { this.loadItems(); } $onChange() { this.loadItems(); } loadItems() { if (!this.project) { return; } this.loading = true; this.DashboardFeedService.getProjectEvents(this.project).then(items => { this.items = items.filter(item => { return item.event_type && item.event_type !== 'issue_update_succeeded'; }); }).finally(() => { this.loading = false; }); } showDetails(event) { return this.$uibModal.open({ component: 'eventDetailsDialog', resolve: { event: () => event, } }).result; } } };
Create a dummy index with the same name
<?php use PragmaRX\Tracker\Support\Migration; class FixAgentName extends Migration { /** * Table related to this migration. * * @var string */ private $table = 'tracker_agents'; /** * Run the migrations. * * @return void */ public function migrateUp() { try { $this->builder->table( $this->table, function ($table) { $table->dropUnique('tracker_agents_name_unique'); } ); $this->builder->table( $this->table, function ($table) { $table->mediumText('name')->change(); } ); $this->builder->table( $this->table, function ($table) { $table->unique('id', 'tracker_agents_name_unique'); // this is a dummy index } ); } catch (\Exception $e) { dd($e->getMessage()); } } /** * Reverse the migrations. * * @return void */ public function migrateDown() { try { $this->builder->table( $this->table, function ($table) { $table->string('name', 255)->change(); $table->unique('name'); } ); } catch (\Exception $e) { } } }
<?php use PragmaRX\Tracker\Support\Migration; class FixAgentName extends Migration { /** * Table related to this migration. * * @var string */ private $table = 'tracker_agents'; /** * Run the migrations. * * @return void */ public function migrateUp() { try { $this->builder->table( $this->table, function ($table) { $table->dropUnique('tracker_agents_name_unique'); } ); $this->builder->table( $this->table, function ($table) { $table->mediumText('name')->unique()->change(); } ); } catch (\Exception $e) { dd($e->getMessage()); } } /** * Reverse the migrations. * * @return void */ public function migrateDown() { try { $this->builder->table( $this->table, function ($table) { $table->string('name', 255)->change(); $table->unique('name'); } ); } catch (\Exception $e) { } } }
Add reducer cases for add/removing board filters
import initialState from './initialState'; import { BOARD_REQUESTED, BOARD_LOADED, BOARD_DESTROYED, BOARD_SCROLLED_BOTTOM, BOARD_INVALIDATED, SEARCH_BOARD, ADD_FILTER, REMOVE_FILTER, } from '../constants' export default function (state = initialState.board, action) { switch (action.type) { case BOARD_REQUESTED: return Object.assign({}, state, { isFetching: true, didInvalidate: false }) case BOARD_INVALIDATED: return Object.assign({}, state, { didInvalidate: true }) case BOARD_LOADED: return Object.assign({}, state, { posts: action.posts, receivedAt: action.receivedAt, isFetching: false }) case BOARD_DESTROYED: return Object.assign({}, state, { posts: [] }) case BOARD_SCROLLED_BOTTOM: return Object.assign({}, state, { limit: action.payload }) case SEARCH_BOARD: return Object.assign({}, state, { searchWord: action.payload || null }) case ADD_FILTER: return Object.assign({}, state, { filterWords: [...state.filterWords, action.payload] }) case REMOVE_FILTER: return Object.assign({}, state, { filterWords: state.filterWords.filter(word => { action.payload !== word }) }) default: return state } }
import initialState from './initialState'; import { BOARD_REQUESTED, BOARD_LOADED, BOARD_DESTROYED, BOARD_SCROLLED_BOTTOM, BOARD_FILTER, BOARD_INVALIDATED } from '../constants' export default function (state = initialState.board, action) { switch (action.type) { case BOARD_REQUESTED: return Object.assign({}, state, { isFetching: true, didInvalidate: false }) case BOARD_INVALIDATED: return Object.assign({}, state, { didInvalidate: true }) case BOARD_LOADED: return Object.assign({}, state, { posts: action.posts, receivedAt: action.receivedAt, isFetching: false }) case BOARD_DESTROYED: return Object.assign({}, state, { posts: [] }) case BOARD_SCROLLED_BOTTOM: return Object.assign({}, state, { limit: action.payload }) case BOARD_FILTER: return Object.assign({}, state, { filterWord: action.payload || null }) default: return state } }
Fix issue caused by isMasterRequest not being available in earlier Symfony versions
<?php namespace Rj\FrontendBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\HttpKernelInterface; use Symfony\Component\HttpKernel\KernelEvents; class InjectLiveReloadListener implements EventSubscriberInterface { private $url; public function __construct($url) { $this->url = $url; } public function onKernelResponse(FilterResponseEvent $event) { if (!$this->shouldInject($event)) { return; } $response = $event->getResponse(); $content = $response->getContent(); $pos = strripos($content, '</body>'); if (false === $pos) { return; } $script = '<script src="'.$this->url.'"></script>'; $response->setContent(substr($content, 0, $pos).$script.substr($content, $pos)); } public static function getSubscribedEvents() { return array( KernelEvents::RESPONSE => array('onKernelResponse', -128), ); } private function shouldInject($event) { if ($event->getRequestType() !== HttpKernelInterface::MASTER_REQUEST) { return false; } if ($event->getRequest()->isXmlHttpRequest()) { return false; } return $event->getResponse()->headers->has('X-Debug-Token'); } }
<?php namespace Rj\FrontendBundle\EventListener; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpKernel\Event\FilterResponseEvent; use Symfony\Component\HttpKernel\KernelEvents; class InjectLiveReloadListener implements EventSubscriberInterface { private $url; public function __construct($url) { $this->url = $url; } public function onKernelResponse(FilterResponseEvent $event) { if (!$this->shouldInject($event)) { return; } $response = $event->getResponse(); $content = $response->getContent(); $pos = strripos($content, '</body>'); if (false === $pos) { return; } $script = '<script src="'.$this->url.'"></script>'; $response->setContent(substr($content, 0, $pos).$script.substr($content, $pos)); } public static function getSubscribedEvents() { return array( KernelEvents::RESPONSE => array('onKernelResponse', -128), ); } private function shouldInject($event) { if (!$event->isMasterRequest()) { return false; } if ($event->getRequest()->isXmlHttpRequest()) { return false; } return $event->getResponse()->headers->has('X-Debug-Token'); } }
Add hints about ntp and updates
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ServerType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('ip') ->add('os') ->add('autoUpdates', 'checkbox', [ 'required' => false, 'attr' => [ 'help-block' => 'Did you enable <a href="https://help.ubuntu.com/community/AutomaticSecurityUpdates">automatic updates</a>?. You should also set <code>Unattended-Upgrade::Remove-Unused-Dependencies</code> to <code>true</code> and possibly enable <code>"${distro_id} ${distro_codename}-updates";</code>' ] ]) ->add('ntp', 'checkbox', [ 'required' => false, 'attr' => [ 'help-block' => 'Did you install NTP (<code>apt-get install ntp</code>)? If this is an OpsWorks server it is installed by default' ] ]) ->add('hostingLogin', new LoginType()) ->add('rootLogin', new LoginType()) ->add('userLogin', new LoginType()) ; } /** * Configures the options for this type. * * @param OptionsResolver $resolver The resolver for the options. */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => 'AppBundle\Entity\Server' ]); } /** * @return string */ public function getName() { return 'appbundle_server'; } }
<?php namespace AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class ServerType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('ip') ->add('os') ->add('autoUpdates', 'checkbox', [ 'required' => false ]) ->add('ntp', 'checkbox', [ 'required' => false ]) ->add('hostingLogin', new LoginType()) ->add('rootLogin', new LoginType()) ->add('userLogin', new LoginType()) ; } /** * Configures the options for this type. * * @param OptionsResolver $resolver The resolver for the options. */ public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => 'AppBundle\Entity\Server' ]); } /** * @return string */ public function getName() { return 'appbundle_server'; } }
Fix test case with client
from django.core.urlresolvers import reverse from django.test import Client from django.test import TestCase from presentation.models import Presentation from warp.users.models import User class PresentationListTest(TestCase): def setUp(self): self.client = Client() self.test_user = self.create_test_user() self.presentation = Presentation(subject="subject", author=self.test_user, markdown="#Abcdefghijklmno", html="<h1>Abcdefghijklmno</h1>") for _ in range(0, 20): self.presentation.save() def test_get_presentation_list_page(self): response = self.client.get(reverse('presentation:list')) self.assertContains(response, self.presentation.subject) self.assertContains(response, self.presentation.author.username) @staticmethod def create_test_user(): name = "Name name" username = "username" first_name = "Name" last_name = "name" email = "[email protected]" is_staff = False is_active = True user = User(name=name, username=username, first_name=first_name, last_name=last_name, email=email, is_staff=is_staff, is_active=is_active) user.save() return user
from django.contrib.auth.models import AnonymousUser from django.core.urlresolvers import reverse from django.test import TestCase from django.test import RequestFactory from presentation.models import Presentation from presentation.views import PresentationList from warp.users.models import User class PresentationListTest(TestCase): def setUp(self): self.factory = RequestFactory() self.test_user = self.create_test_user() self.presentation = Presentation(subject="subject", author=self.test_user, markdown="#Abcdefghijklmno", html="<h1>Abcdefghijklmno</h1>") for _ in range(0, 20): self.presentation.save() def test_get_presentation_list_page(self): presentation_list_url = reverse('presentation:list') request = self.factory.get(presentation_list_url) request.user = AnonymousUser() response = PresentationList.as_view()(request) self.assertIn(response, self.presentation.subject) self.assertIn(response, self.presentation.author.name) @staticmethod def create_test_user(): name = "Name name" username = "username" first_name = "Name" last_name = "name" email = "[email protected]" is_staff = False is_active = True user = User(name=name, username=username, first_name=first_name, last_name=last_name, email=email, is_staff=is_staff, is_active=is_active) user.save() return user
Break back into three parts. svn path=/trunk/; revision=569
#!/usr/bin/env seed Seed.import_namespace("Gtk"); Gtk.init(null, null); BrowserToolbar = new GType({ parent: Gtk.HBox.type, name: "BrowserToolbar", instance_init: function (klass) { // Private var url_bar = new Gtk.Entry(); var back_button = new Gtk.ToolButton({stock_id:"gtk-go-back"}); var forward_button = new Gtk.ToolButton({stock_id:"gtk-go-forward"}); var refresh_button = new Gtk.ToolButton({stock_id:"gtk-refresh"}); var back = function () { Seed.print("Go Back"); }; var forward = function () { Seed.print("Go Forward"); }; var refresh = function () { Seed.print("Refresh"); }; var browse = function (url) { Seed.print("Navigate to: " + url.text); }; // Implementation back_button.signal.clicked.connect(back); forward_button.signal.clicked.connect(forward); refresh_button.signal.clicked.connect(refresh); url_bar.signal.activate.connect(browse); this.pack_start(back_button); this.pack_start(forward_button); this.pack_start(refresh_button); this.pack_start(url_bar, true, true); } }); window = new Gtk.Window({title: "Browser"}); window.signal.hide.connect(function () { Gtk.main_quit(); }); toolbar = new BrowserToolbar(); window.add(toolbar); window.show_all(); Gtk.main();
#!/usr/bin/env seed Seed.import_namespace("Gtk"); Gtk.init(null, null); BrowserToolbar = new GType({ parent: Gtk.HBox.type, name: "BrowserToolbar", instance_init: function(klass) { var url_bar = new Gtk.Entry(); var back_button = new Gtk.ToolButton({stock_id:"gtk-go-back"}); var forward_button = new Gtk.ToolButton({stock_id:"gtk-go-forward"}); var refresh_button = new Gtk.ToolButton({stock_id:"gtk-refresh"}); var back = function () { Seed.print("back"); }; var forward = function () { Seed.print("forward"); }; var refresh = function () { Seed.print("refresh"); }; var browse = function () { Seed.print("browse"); }; back_button.signal.clicked.connect(back); forward_button.signal.clicked.connect(forward); refresh_button.signal.clicked.connect(refresh); url_bar.signal.activate.connect(browse); this.pack_start(back_button); this.pack_start(forward_button); this.pack_start(refresh_button); this.pack_start(url_bar, true, true); } }); window = new Gtk.Window({title: "Browser"}); window.signal.hide.connect(function () { Gtk.main_quit(); }); window.add(new BrowserToolbar()); window.show_all(); Gtk.main();
Allow access to root leaves.
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) leaves = {} for path, child in self.root.children.items(): if child.isLeaf == True: leaves[path] = child tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree) for path, child in leaves.items(): self.root.putChild(path, child)
import core.provider.authentication as authentication import core.notify.dispatcher as notify import core.notify.plugins.available.changes as changes import core.provider.storage as storage import core.resource.base as resource import conf.vhosts.available.default as default class VHost(default.VHost): host = ['localhost'] port = '8888' def build(self): """ Build the resource tree """ default.VHost.build(self) # [Change the notifiers] # self.root.notifier = notify.Manual([changes.Plugin()]) # plain propfind xslt replaces the other one xsltResource = resource.StaticResource( storage.FileStorageProvider(self.config['basePath']+'/static/public/propfind-plain.xslt'), expirationDays = 2 ) xsltResource.isLeaf = True self.root.children['~static'].putChild('propfind.xslt', xsltResource) tree = resource.TokenAccessResourceDecorator(self.root) self.root = resource.TokenResource( authProvider=authentication.TokenAuthProvider(secret=self.config['share']['secret'], userProvider=self.user ), tree=tree)
Update to handle Laravel 5.4 (Should still work with 5.1+)
<?php namespace EricMakesStuff\ServerMonitor\Monitors; use EricMakesStuff\ServerMonitor\Exceptions\InvalidConfiguration; class ServerMonitorFactory { /** * @param array $monitorConfiguration * @param array $filter * @return mixed */ public static function createForMonitorConfig(array $monitorConfiguration, array $filter = []) { $monitors = collect($monitorConfiguration); if (count($filter) && !empty($filter[0])) { $monitors = $monitors->only($filter); } $configured_monitors = collect(); $monitors->map(function($monitorConfigs, $monitorName) { if (file_exists(__DIR__.'/'.ucfirst($monitorName).'Monitor.php')) { $className = '\\EricMakesStuff\\ServerMonitor\\Monitors\\'.ucfirst($monitorName).'Monitor'; return collect($monitorConfigs)->map(function($monitorConfig) use ($className) { return new $className($monitorConfig); }); } throw InvalidConfiguration::cannotFindMonitor($monitorName); })->each(function($monitor_group) use ($configured_monitors) { $monitor_group->each(function($monitor) use ($configured_monitors) { $configured_monitors->push($monitor); }); }); return $configured_monitors; } }
<?php namespace EricMakesStuff\ServerMonitor\Monitors; use EricMakesStuff\ServerMonitor\Exceptions\InvalidConfiguration; class ServerMonitorFactory { /** * @param array $monitorConfiguration * @param array $filter * @return mixed */ public static function createForMonitorConfig(array $monitorConfiguration, array $filter = []) { $monitors = collect($monitorConfiguration); if (count($filter) && !empty($filter[0])) { $monitors = $monitors->only($filter); } $configured_monitors = collect(); $monitors->map(function($monitorConfigs, $monitorName) { if (file_exists(__DIR__.'/'.ucfirst($monitorName).'Monitor.php')) { $className = '\\EricMakesStuff\\ServerMonitor\\Monitors\\'.ucfirst($monitorName).'Monitor'; return collect($monitorConfigs)->map(function($monitorConfig) use ($className) { return app($className, [$monitorConfig]); }); } throw InvalidConfiguration::cannotFindMonitor($monitorName); })->each(function($monitor_group) use ($configured_monitors) { $monitor_group->each(function($monitor) use ($configured_monitors) { $configured_monitors->push($monitor); }); }); return $configured_monitors; } }
Rename Gulp task for improved clarity
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var jsonlint = require("gulp-jsonlint"); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var plumber = require('gulp-plumber'); gulp.task('set-test-env', function(cb) { process.env.NODE_ENV = 'test'; cb(); }); gulp.task('json', ['set-test-env'], function(cb) { gulp.src(["**/*.json", "!./node_modules/**/*.json"]) .pipe(jsonlint()) .pipe(jsonlint.reporter()); cb(); }); gulp.task('lint', function() { gulp.src('source/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('test', ['set-test-env'], function(cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function(err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function() { cb(mochaErr); }); }); gulp.task('default', ['set-test-env', 'json', 'lint', 'test']);
'use strict'; var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var jsonlint = require("gulp-jsonlint"); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var plumber = require('gulp-plumber'); gulp.task('set-test-env', function(cb) { process.env.NODE_ENV = 'test'; cb(); }); gulp.task('json', ['set-test-env'], function(cb) { gulp.src(["**/*.json", "!./node_modules/**/*.json"]) .pipe(jsonlint()) .pipe(jsonlint.reporter()); cb(); }); gulp.task('static', function() { gulp.src('source/*.js') .pipe(excludeGitignore()) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('test', ['set-test-env'], function(cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function(err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function() { cb(mochaErr); }); }); gulp.task('default', ['set-test-env', 'json', 'static', 'test']);
Allow passing attributes in construct
<?php /** * * Created by mtils on 22.08.18 at 13:31. **/ namespace Ems\Core; use Ems\Contracts\Core\Input as InputContract; use Ems\Contracts\Core\None; use Ems\Core\Exceptions\KeyNotFoundException; use Ems\Core\Support\FastArrayDataTrait; use Ems\Core\Support\InputTrait; use Ems\Core\Support\RoutableTrait; use function array_key_exists; class Input implements InputContract { use FastArrayDataTrait; use RoutableTrait; use InputTrait; /** * Input constructor. * * @param array $parameters */ public function __construct($parameters=[]) { $this->_attributes = $parameters; } /** * {@inheritDoc} * * @param mixed $key * @param mixed $default (optional) * * @return mixed **/ public function get($key, $default = null) { if (array_key_exists($key, $this->_attributes)) { return $this->_attributes[$key]; } return $default; } /** * {@inheritDoc} * * @param string $key * * @throws \Ems\Contracts\Core\Errors\NotFound * * @return mixed **/ public function getOrFail($key) { $result = $this->get($key, new None()); if ($result instanceof None) { throw new KeyNotFoundException("Key '$key' not found in Input"); } return $result; } }
<?php /** * * Created by mtils on 22.08.18 at 13:31. **/ namespace Ems\Core; use Ems\Contracts\Core\Input as InputContract; use Ems\Contracts\Core\None; use Ems\Core\Exceptions\KeyNotFoundException; use Ems\Core\Support\FastArrayDataTrait; use Ems\Core\Support\InputTrait; use Ems\Core\Support\RoutableTrait; use function array_key_exists; class Input implements InputContract { use FastArrayDataTrait; use RoutableTrait; use InputTrait; /** * {@inheritDoc} * * @param mixed $key * @param mixed $default (optional) * * @return mixed **/ public function get($key, $default = null) { if (array_key_exists($key, $this->_attributes)) { return $this->_attributes[$key]; } return $default; } /** * {@inheritDoc} * * @param string $key * * @throws \Ems\Contracts\Core\Errors\NotFound * * @return mixed **/ public function getOrFail($key) { $result = $this->get($key, new None()); if ($result instanceof None) { throw new KeyNotFoundException("Key '$key' not found in Input"); } return $result; } }
Add DataDog monitoring to cron job runs
#!/usr/bin/env python import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' dogwrap_path = '/usr/local/bin/amo_cron_dogwrap' ctx = { "django": "cd %s; %s %s manage.py" % (opts.zamboni, dogwrap_path, opts.python) } ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
#!/usr/bin/env python import os from optparse import OptionParser TEMPLATE = open(os.path.join(os.path.dirname(__file__), 'crontab.tpl')).read() def main(): parser = OptionParser() parser.add_option("-z", "--zamboni", help="Location of zamboni (required)") parser.add_option("-u", "--user", help=("Prefix cron with this user. " "Only define for cron.d style crontabs")) parser.add_option("-p", "--python", default="/usr/bin/python2.7", help="Python interpreter to use") parser.add_option("-d", "--deprecations", default=False, help="Show deprecation warnings") (opts, args) = parser.parse_args() if not opts.zamboni: parser.error("-z must be defined") if not opts.deprecations: opts.python += ' -W ignore::DeprecationWarning' ctx = {'django': 'cd %s; %s manage.py' % (opts.zamboni, opts.python)} ctx['z_cron'] = '%s cron' % ctx['django'] if opts.user: for k, v in ctx.iteritems(): ctx[k] = '%s %s' % (opts.user, v) # Needs to stay below the opts.user injection. ctx['python'] = opts.python print(TEMPLATE % ctx) if __name__ == "__main__": main()
Add tests for parser tokens
"""parse_token test case""" import unittest from lighty.templates.tag import parse_token class ParseTokenTestCase(unittest.TestCase): ''' Test form fields ''' def setUp(self): # Test Field class pass def testCleanBrackets(self): parsed = parse_token('"test.html"') needed = ['test.html'] assert parsed == needed, 'Brackets cleaning failed: %s except %s' % ( parsed, needed) def testCleanInnerBrackets(self): parsed = parse_token('"test\'html"') needed = ['test\'html'] assert parsed == needed, 'Brackets cleaning failed: %s except %s' % ( parsed, needed) def testParseSimpleTokens(self): parsed = parse_token('a in b') needed = ['a', 'in', 'b'] assert parsed == needed, 'Token parsing failed: %s except %s' % ( parsed, needed) def testParseTokensWithSentence(self): parsed = parse_token('a as "Let me in"') needed = ['a', 'as', 'Let me in'] assert parsed == needed, 'Token with sentence parsing failed: %s' % ( ' '.join((parsed, 'except', needed))) def test(): suite = unittest.TestSuite() suite.addTest(ParseTokenTestCase('testCleanBrackets')) suite.addTest(ParseTokenTestCase("testCleanInnerBrackets")) suite.addTest(ParseTokenTestCase("testParseSimpleTokens")) suite.addTest(ParseTokenTestCase("testParseTokensWithSentence")) return suite
"""parse_token test case""" import unittest from lighty.templates.tag import parse_token class FormFieldsTestCase(unittest.TestCase): ''' Test form fields ''' def setUp(self): # Test Field class pass def testCleanBrackets(self): parsed = parse_token('"test.html"') needed = ['test.html'] assert parsed == needed, 'Brackets cleaning failed: %s except %s' % ( parsed, needed) def testCleanInnerBrackets(self): parsed = parse_token('"test\'html"') needed = ['test\'html'] assert parsed == needed, 'Brackets cleaning failed: %s except %s' % ( parsed, needed) def testParseSimpleTokens(self): parsed = parse_token('a in b') needed = ['a', 'in', 'b'] assert parsed == needed, 'Token parsing failed: %s except %s' % ( parsed, needed) def testParseTokensWithSentence(self): parsed = parse_token('a as "Let me in"') needed = ['a', 'as', 'Let me in'] assert parsed == needed, 'Token with sentence parsing failed: %s' % ( ' '.join((parsed, 'except', needed)))
Add facade loader and example to readme
<?php namespace Darkin1\Intercom; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Config; use Intercom\IntercomClient; use Darkin1\Intercom\Facades\Intercom; class IntercomServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { // Allow users to publish config to override the defaults. $this->publishes([ __DIR__.'/../config/intercom.php' => config_path('intercom.php'), ], 'darkin1/intercom'); } /** * Register the service provider. * * @return void */ public function register() { // Use the provided config as default. $this->mergeConfigFrom( __DIR__.'/../config/intercom.php', 'intercom' ); $this->app->singleton('intercom', function ($app) { $appID = $app['config']->get('intercom.app_id'); $apiKey = $app['config']->get('intercom.api_key'); $intercom = new IntercomClient($appID, $apiKey); return new IntercomApi($intercom); }); $this->app->booting(function () { $loader = AliasLoader::getInstance(); $loader->alias('Intercom', Intercom::class); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('intercom'); } }
<?php namespace Darkin1\Intercom; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Config; use Intercom\IntercomClient; class IntercomServiceProvider extends ServiceProvider { /** * Indicates if loading of the provider is deferred. * * @var bool */ protected $defer = true; /** * Bootstrap the application events. * * @return void */ public function boot() { // Allow users to publish config to override the defaults. $this->publishes([ __DIR__.'/../config/intercom.php' => config_path('intercom.php'), ], 'darkin1/intercom'); } /** * Register the service provider. * * @return void */ public function register() { // Use the provided config as default. $this->mergeConfigFrom( __DIR__.'/../config/intercom.php', 'intercom' ); $this->app->singleton('intercom', function ($app) { $appID = $app['config']->get('intercom.app_id'); $apiKey = $app['config']->get('intercom.api_key'); $intercom = new IntercomClient($appID, $apiKey); return new IntercomApi($intercom); }); } /** * Get the services provided by the provider. * * @return array */ public function provides() { return array('intercom'); } }
Fix widgets path when using pages that have an ID (e.g. //host/p/Page)
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "/widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
Add a repr for twelve.Environment
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def __repr__(self): return "<twelve.Environment [{0}]>".format(",".join(self.values)) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
import os import extensions class Environment(object): def __init__(self, adapter=None, environ=None, names=None, *args, **kwargs): super(Environment, self).__init__(*args, **kwargs) if names is None: names = {} self.adapter = adapter self.environ = environ self.names = names self.values = {} self._load_all() def __getattr__(self, name): return self.values.get(name) def _load_all(self): # Load Services self._load_services() def _load_services(self): for plugin in extensions.get(group="twelve.services"): service = plugin.load() value = service( self.environ if self.environ is not None else os.environ, self.names.get(plugin.name) ) if self.adapter is not None: adapters = list(extensions.get(group="twelve.adapters", name="{0}.{1}".format(self.adapter, plugin.name))) if len(adapters): adapter = adapters[0].load() value = adapter(value) self.values[plugin.name] = value
Remove UI asking user to claim it
var handle = function(e) { // Find the relevant link var targetLink = e.currentTarget.href; // Find what we said about it var relevantItem = example_items.filter(function(item) { return item['url'] == targetLink}); console.log(relevantItem); var desc = relevantItem[0]['description'], students = relevantItem[0]['students'], bugID = relevantItem[0]['id'], html = ""; if (desc) { html = '<p>Notes by event organizers:</p><blockquote>' + desc + '</blockquote>'; } html = html + '<p style="text-align: right;"><a class="deep_go" href="' + targetLink + '" target="_blank"">View Open Task Here</a>'; var $dialog = $('<div></div>') .html(html) .dialog({ autoOpen: false, title: 'Info about this task' }); $dialog.dialog('open'); $('#claim_' + bugID).on( 'click', function(){ $dialog.dialog('close'); claim(bugID, $("#new_name").val()).done( function(data, status, jqxhr) { $.getJSON('/tasks/', updateSettings); } ); } ); $("#new_name").val(""); // prevent the default action, e.g., following a link return false; };
var handle = function(e) { // Find the relevant link var targetLink = e.currentTarget.href; // Find what we said about it var relevantItem = example_items.filter(function(item) { return item['url'] == targetLink}); console.log(relevantItem); var desc = relevantItem[0]['description'], students = relevantItem[0]['students'], bugID = relevantItem[0]['id'], html = ""; if (desc) { html = '<p>Notes by event organizers:</p><blockquote>' + desc + '</blockquote>'; } if (Object.keys(students).length ==0) { html += '<p>No one claimed this ticket yet! Claim it by typing your name below:</p><input type="text" id="new_name" value="Your name here"></input><input type="submit" value="Submit" id="claim_' + bugID + '" class="button"/>'; } else { html += '<p>Currently being worked on by ' + students + '</p>'; } html = html + '<p style="text-align: right;"><a class="deep_go" href="' + targetLink + '" target="_blank"">View Open Task Here</a>'; var $dialog = $('<div></div>') .html(html) .dialog({ autoOpen: false, title: 'Info about this task' }); $dialog.dialog('open'); $('#claim_' + bugID).on( 'click', function(){ $dialog.dialog('close'); claim(bugID, $("#new_name").val()).done( function(data, status, jqxhr) { $.getJSON('/tasks/', updateSettings); } ); } ); $("#new_name").val(""); // prevent the default action, e.g., following a link return false; };
Add a default value to sessionGet
<?php namespace PragmaRX\Google2FALaravel\Support; trait Session { /** * Make a session var name for. * * @param null $name * * @return mixed */ protected function makeSessionVarName($name = null) { return $this->config('session_var').(is_null($name) || empty($name) ? '' : '.'.$name); } /** * Get a session var value. * * @param null $var * * @return mixed */ public function sessionGet($var = null, $default = null) { return $this->request->session()->get( $this->makeSessionVarName($var), $default ); } /** * Put a var value to the current session. * * @param $var * @param $value * * @return mixed */ protected function sessionPut($var, $value) { $this->request->session()->put( $this->makeSessionVarName($var), $value ); return $value; } /** * Forget a session var. * * @param null $var */ protected function sessionForget($var = null) { $this->request->session()->forget( $this->makeSessionVarName($var) ); } }
<?php namespace PragmaRX\Google2FALaravel\Support; trait Session { /** * Make a session var name for. * * @param null $name * * @return mixed */ protected function makeSessionVarName($name = null) { return $this->config('session_var').(is_null($name) || empty($name) ? '' : '.'.$name); } /** * Get a session var value. * * @param null $var * * @return mixed */ public function sessionGet($var = null) { return $this->request->session()->get( $this->makeSessionVarName($var) ); } /** * Put a var value to the current session. * * @param $var * @param $value * * @return mixed */ protected function sessionPut($var, $value) { $this->request->session()->put( $this->makeSessionVarName($var), $value ); return $value; } /** * Forget a session var. * * @param null $var */ protected function sessionForget($var = null) { $this->request->session()->forget( $this->makeSessionVarName($var) ); } }
Fix to find entire package hierarchy
from setuptools import setup, find_packages __version__ = '0.1' setup( name='wanikani', description='WaniKani Tools for Python', long_description=open('README.md').read(), author='Paul Traylor', url='http://github.com/kfdm/wanikani/', version=__version__, packages=find_packages(), install_requires=['requests'], # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', ], entry_points={ 'console_scripts': [ 'wk = wanikani.cli:main', 'wanikani = wanikani.django.manage:main [django]', ] }, extras_require={ 'django': [ 'dj_database_url', 'Django >= 1.9, < 1.10', 'django-cache-url', 'envdir', 'icalendar', 'python-social-auth', 'raven', ], } )
from setuptools import setup __version__ = '0.1' setup( name='wanikani', description='WaniKani Tools for Python', long_description=open('README.md').read(), author='Paul Traylor', url='http://github.com/kfdm/wanikani/', version=__version__, packages=['wanikani'], install_requires=['requests'], # http://pypi.python.org/pypi?%3Aaction=list_classifiers classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', ], entry_points={ 'console_scripts': [ 'wk = wanikani.cli:main', 'wanikani = wanikani.django.manage:main [django]', ] }, extras_require={ 'django': [ 'dj_database_url', 'Django >= 1.9, < 1.10', 'django-cache-url', 'envdir', 'icalendar', 'python-social-auth', 'raven', ], } )
Use dialogue terminology in menu
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('D', 'Dialogue'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
from django import forms class CampaignGeneralForm(forms.Form): TYPE_CHOICES = ( ('', 'Select campaign type'), ('B', 'Bulk Message'), ('C', 'Conversation'), ) name = forms.CharField(label="Campaign name", max_length=100) type = forms.ChoiceField(label="Which kind of campaign would you like?", widget=forms.Select(), choices=TYPE_CHOICES) class CampaignConfigurationForm(forms.Form): COUNTRY_CHOICES = ( ('.za', 'South Africa'), ) CHANNEL_CHOICES = ( ('ussd', 'USSD'), ) # more than likely a many to many field, or something similair in the riak # world. Whom I kidding, this is probably just a modelform? countries = forms.MultipleChoiceField(label="Destinations", widget=forms.Select(), choices=COUNTRY_CHOICES) channels = forms.MultipleChoiceField(label="Channels", widget=forms.Select(), choices=CHANNEL_CHOICES) keyword = forms.CharField(label="Keyword", max_length=100) class CampaignBulkMessageForm(forms.Form): message = forms.CharField(label="Bulk message text", widget=forms.Textarea)
Create base test case class for rupture
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class RuptureTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] class AnalyzerTestCase(RuptureTestCase): def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
from django.test import TestCase from breach.models import SampleSet, Victim, Target, Round from breach.analyzer import decide_next_world_state class AnalyzerTestCase(TestCase): def setUp(self): target = Target.objects.create( endpoint='http://di.uoa.gr/', prefix='test', alphabet='0123456789' ) victim = Victim.objects.create( target=target, sourceip='192.168.10.140', snifferendpoint='http://localhost/' ) round = Round.objects.create( victim=victim, amount=1, knownsecret='testsecret', knownalphabet='01' ) self.samplesets = [ SampleSet.objects.create( round=round, candidatealphabet='0', data='bigbigbigbigbigbig' ), SampleSet.objects.create( round=round, candidatealphabet='1', data='small' ) ] def test_decide(self): state, confidence = decide_next_world_state(self.samplesets) self.assertEqual(state["knownsecret"], "testsecret1")
Make the buffer test stream write async As suggested by @pchelolo, asynchronously finish the stream.
'use strict'; var stream = require('stream'); function hello(restbase, req) { var body = new stream.PassThrough(); body.end('hello'); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } function buffer(restbase, req) { var body = new stream.PassThrough(); body.write(new Buffer('hel')); // Delay the final write to test async production. setTimeout(function() { body.end(new Buffer('lo')); }, 500); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } function chunks(restbase, req) { var body = new stream.PassThrough(); for (var i = 0; i < 100; i++) { body.write(i.toString()); } body.end(); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } module.exports = function(options) { return { spec: { paths: { '/hello': { get: { operationId: 'hello' } }, '/buffer': { get: { operationId: 'buffer' } }, '/chunks': { get: { operationId: 'chunks' } } } }, operations: { hello: hello, buffer: buffer, chunks: chunks, } }; };
'use strict'; var stream = require('stream'); function hello(restbase, req) { var body = new stream.PassThrough(); body.end('hello'); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } function buffer(restbase, req) { var body = new stream.PassThrough(); body.end(new Buffer('hello')); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } function chunks(restbase, req) { var body = new stream.PassThrough(); for (var i = 0; i < 100; i++) { body.write(i.toString()); } body.end(); return { status: 200, headers: { 'content-type': 'text/html', }, body: body }; } module.exports = function(options) { return { spec: { paths: { '/hello': { get: { operationId: 'hello' } }, '/buffer': { get: { operationId: 'buffer' } }, '/chunks': { get: { operationId: 'chunks' } } } }, operations: { hello: hello, buffer: buffer, chunks: chunks, } }; };
Clean up dir after move
#!/usr/bin/env python # -*- coding: utf-8 -*- """Parse source tree, get old files and move files info a new folder tree""" import KmdCmd import KmdFiles import os import re import logging class KmdFilesMove(KmdCmd.KmdCommand): regexp = None def extendParser(self): super(KmdFilesMove, self).extendParser() #Extend parser self.parser.add_argument('source', metavar='</path/to/tree>', nargs=1, help='The source tree') self.parser.add_argument('tree', metavar='</path/to/dest>', nargs=1, help='Folder to put matching files') self.parser.add_argument('age', metavar='</path/to/dest>', nargs=1, help='age') def run(self): logging.info("Parsing %s", self.args.source[0]) for root, dirs, files in os.walk(self.args.source[0]): logging.debug("Walking in %s", root) for name in files: pname = os.path.join(root, name) dname = os.path.join(self.args.tree[0]) try : KmdFiles.fileMoveRenameToDirIfOld(pname, dname, int(self.args.age[0]), self.args.doit) except : logging.error("Bad move from %s to %s", pname, dname) KmdFiles.removeEmptyFolders(self.args.source[0], self.args.doit) if __name__ == "__main__": cmd = KmdFilesMove(__doc__) cmd.run()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Parse source tree, get old files and move files info a new folder tree""" import KmdCmd import KmdFiles import os import re import logging class KmdFilesMove(KmdCmd.KmdCommand): regexp = None def extendParser(self): super(KmdFilesMove, self).extendParser() #Extend parser self.parser.add_argument('source', metavar='</path/to/tree>', nargs=1, help='The source tree') self.parser.add_argument('tree', metavar='</path/to/dest>', nargs=1, help='Folder to put matching files') self.parser.add_argument('age', metavar='</path/to/dest>', nargs=1, help='age') def run(self): logging.info("Parsing %s", self.args.source[0]) for root, dirs, files in os.walk(self.args.source[0]): logging.debug("Walking in %s", root) for name in files: pname = os.path.join(root, name) dname = os.path.join(self.args.tree[0]) try : KmdFiles.fileMoveRenameToDirIfOld(pname, dname, int(self.args.age[0]), self.args.doit) except : logging.error("Bad move from %s to %s", pname, dname) if __name__ == "__main__": cmd = KmdFilesMove(__doc__) cmd.run()
Implement the sql query using querybuilder
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * OrganismRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class OrganismRepository extends EntityRepository { public function getNumber(): int { $query = $this->getEntityManager()->createQuery('SELECT COUNT(o.fennecId) FROM AppBundle\Entity\Organism o'); return $query->getSingleScalarResult(); } public function getOrganisms($limit, $search): array { $qb = $this->getEntityManager()->createQueryBuilder(); $qb->select('organism') ->from('AppBundle\Entity\Organism', 'organism') ->where('LOWER(organism.scientificName) LIKE LOWER(:search)') ->setParameter('search', $search) ->setMaxResults($limit); $query = $qb->getQuery(); $result = $query->getArrayResult(); $data = array(); while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) { $result = array(); $result['fennec_id'] = $row['fennec_id']; $result['scientific_name'] = $row['scientific_name']; $data[] = $result; } return $data; } }
<?php namespace AppBundle\Repository; use Doctrine\ORM\EntityRepository; /** * OrganismRepository * * This class was generated by the PhpStorm "Php Annotations" Plugin. Add your own custom * repository methods below. */ class OrganismRepository extends EntityRepository { public function getNumber(): int { $query = $this->getEntityManager()->createQuery('SELECT COUNT(o.fennecId) FROM AppBundle\Entity\Organism o'); return $query->getSingleScalarResult(); } public function getOrganisms($query): array{ $limit = 5; if ($query->has('limit')) { $limit = $query->get('limit'); } $search = "%%"; if ($query->has('search')) { $search = "%".$query->get('search')."%"; } $query_get_organisms = <<<EOF SELECT * FROM organism WHERE organism.scientific_name ILIKE :search LIMIT :limit EOF; $stm_get_organisms = $this->getEntityManager()->createQuery($query_get_organisms); $stm_get_organisms->bindValue('search', $search); $stm_get_organisms->bindValue('limit', $limit); $stm_get_organisms->execute(); $data = array(); while ($row = $stm_get_organisms->fetch(PDO::FETCH_ASSOC)) { $result = array(); $result['fennec_id'] = $row['fennec_id']; $result['scientific_name'] = $row['scientific_name']; $data[] = $result; } return $data; } }
Fix people autosuggest with winthrop_only flag
from django.http import JsonResponse from dal import autocomplete from .models import Person from winthrop.books.models import PersonBook from django.db.models import BooleanField, Case, When, Value from .viaf import ViafAPI class ViafAutoSuggest(autocomplete.Select2ListView): """ View to provide VIAF suggestions for autocomplete info""" def get(self, request, *args, **kwargs): """Return JSON with suggested VIAF ids and display names.""" viaf = ViafAPI() result = viaf.suggest(self.q) # Strip names that are not personal for item in result: if item['nametype'] is not 'personal': del item return JsonResponse({ 'results': [dict( id=viaf.uri_from_id(item['viafid']), text=(item['displayForm']), ) for item in result], }) class PersonAutocomplete(autocomplete.Select2QuerySetView): '''Basic person autocomplete lookup, for use with django-autocomplete-light. Restricted to staff only. Also includes optional winthrop query string that sets whether to prioritize Winthrops based on search criteria in function. Can be extended by Q objects if necesary for more complex searches.''' # NOTE staff restrection applied in url config def get_queryset(self): winthrop_only = self.request.GET.get('winthrop', None) people = Person.objects.filter(authorized_name__icontains=self.q) if winthrop_only: people = people.filter(personbook__isnull=False) return people
from django.http import JsonResponse from dal import autocomplete from .models import Person from winthrop.books.models import PersonBook from django.db.models import BooleanField, Case, When, Value from .viaf import ViafAPI class ViafAutoSuggest(autocomplete.Select2ListView): """ View to provide VIAF suggestions for autocomplete info""" def get(self, request, *args, **kwargs): """Return JSON with suggested VIAF ids and display names.""" viaf = ViafAPI() result = viaf.suggest(self.q) # Strip names that are not personal for item in result: if item['nametype'] is not 'personal': del item return JsonResponse({ 'results': [dict( id=viaf.uri_from_id(item['viafid']), text=(item['displayForm']), ) for item in result], }) class PersonAutocomplete(autocomplete.Select2QuerySetView): '''Basic person autocomplete lookup, for use with django-autocomplete-light. Restricted to staff only. Also includes optional winthrop query string that sets whether to prioritize Winthrops based on search criteria in function. Can be extended by Q objects if necesary for more complex searches.''' # NOTE staff restrection applied in url config def get_queryset(self): winthrop_only = self.request.GET.get('winthrop', None) people = Person.objects.filter(authorized_name__icontains=self.q) if winthrop_only: people = people.filter(personbook__isnull=False) return people
Fix references of nxp to imx6ul Bug: 32830902 Change-Id: Ib24db99577b2b11de3500c1e63840563c2321c05
package com.google.samples.button; import android.os.Build; @SuppressWarnings("WeakerAccess") public class BoardDefaults { private static final String DEVICE_EDISON = "edison"; private static final String DEVICE_RPI3 = "rpi3"; private static final String DEVICE_NXP = "imx6ul"; /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForLED() { // TODO: confirm DEVICE and preferred port for RPI3 and NXP switch (Build.DEVICE) { case DEVICE_EDISON: return "IO13"; case DEVICE_RPI3: return "BCM25"; case DEVICE_NXP: return "??"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the Button is connected on. */ public static String getGPIOForButton() { // TODO: confirm DEVICE and preferred port for RPI3 and NXP switch (Build.DEVICE) { case DEVICE_EDISON: return "IO12"; case DEVICE_RPI3: return "BCM22"; case DEVICE_NXP: return "??"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } }
package com.google.samples.button; import android.os.Build; @SuppressWarnings("WeakerAccess") public class BoardDefaults { private static final String DEVICE_EDISON = "edison"; private static final String DEVICE_RPI3 = "rpi3"; private static final String DEVICE_NXP = "nxp"; /** * Return the GPIO pin that the LED is connected on. * For example, on Intel Edison Arduino breakout, pin "IO13" is connected to an onboard LED * that turns on when the GPIO pin is HIGH, and off when low. */ public static String getGPIOForLED() { // TODO: confirm DEVICE and preferred port for RPI3 and NXP switch (Build.DEVICE) { case DEVICE_EDISON: return "IO13"; case DEVICE_RPI3: return "BCM25"; case DEVICE_NXP: return "??"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } /** * Return the GPIO pin that the Button is connected on. */ public static String getGPIOForButton() { // TODO: confirm DEVICE and preferred port for RPI3 and NXP switch (Build.DEVICE) { case DEVICE_EDISON: return "IO12"; case DEVICE_RPI3: return "BCM22"; case DEVICE_NXP: return "??"; default: throw new IllegalStateException("Unknown Build.DEVICE " + Build.DEVICE); } } }
Fix mod log optional channel
import json import logging import typing from datetime import datetime import discord from cogbot.types import ServerId, ChannelId log = logging.getLogger(__name__) class CogBotServerState: def __init__(self, bot, server: discord.Server, log_channel: ChannelId = None): self.bot = bot self.server: discord.Server = server # resolve log channel self.log_channel: discord.Channel = None if log_channel: self.log_channel = self.bot.get_channel(log_channel) if not self.log_channel: log.warning( f"[{self.server}] Failed to resolve log channel <{log_channel}>" ) async def mod_log( self, member: discord.Member, content: str, channel: discord.Channel = None ): if self.log_channel: now = datetime.utcnow() quote_name = f"{member.display_name} ({member.name}#{member.discriminator})" em = discord.Embed(description=content, timestamp=now) em.set_author(name=quote_name, icon_url=member.avatar_url) if channel: em.set_footer(text=f"#{channel}") await self.bot.send_message(self.log_channel, embed=em)
import json import logging import typing from datetime import datetime import discord from cogbot.types import ServerId, ChannelId log = logging.getLogger(__name__) class CogBotServerState: def __init__(self, bot, server: discord.Server, log_channel: ChannelId = None): self.bot = bot self.server: discord.Server = server # resolve log channel self.log_channel: discord.Channel = None if log_channel: self.log_channel = self.bot.get_channel(log_channel) if not self.log_channel: log.warning( f"[{self.server}] Failed to resolve log channel <{log_channel}>" ) async def mod_log( self, member: discord.Member, content: str, channel: discord.Channel = None ): if self.log_channel: now = datetime.utcnow() quote_name = f"{member.display_name} ({member.name}#{member.discriminator})" em = discord.Embed(description=content, timestamp=now) em.set_author(name=quote_name, icon_url=member.avatar_url) em.set_footer(text=f"#{channel}" if channel else None) await self.bot.send_message(self.log_channel, embed=em)
Add 404 request method and url when using withoutExceptionHandling Whenever a NotFoundHTTPException is thrown, it is helpful to see the request method and url. Helps to debug what route to look at instead of having to first look it up in the test file. I've been using this in my own tests and I love it. Final result: ``` 1) Tests\Feature\Backstage\PublishConcertTest::a_promoter_can_publish_their_own_concert Symfony\Component\HttpKernel\Exception\NotFoundHttpException: POST http://ticketbeast.app/backstage/published-concerts ```
<?php namespace Illuminate\Foundation\Testing\Concerns; use Exception; use Illuminate\Contracts\Debug\ExceptionHandler; use Symfony\Component\Console\Application as ConsoleApplication; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; trait InteractsWithExceptionHandling { /** * The previous exception handler. * * @var ExceptionHandler|null */ protected $previousExceptionHandler; /** * Restore exception handling. * * @return $this */ protected function withExceptionHandling() { if ($this->previousExceptionHandler) { $this->app->instance(ExceptionHandler::class, $this->previousExceptionHandler); } return $this; } /** * Disable exception handling for the test. * * @return $this */ protected function withoutExceptionHandling() { $this->previousExceptionHandler = app(ExceptionHandler::class); $this->app->instance(ExceptionHandler::class, new class implements ExceptionHandler { public function __construct() { } public function report(Exception $e) { } public function render($request, Exception $e) { if ($e instanceof NotFoundHttpException) { throw new NotFoundHttpException("{$request->method()} {$request->url()}", null, $e->getCode()); } else { throw $e; } } public function renderForConsole($output, Exception $e) { (new ConsoleApplication)->renderException($e, $output); } }); return $this; } }
<?php namespace Illuminate\Foundation\Testing\Concerns; use Exception; use Illuminate\Contracts\Debug\ExceptionHandler; use Symfony\Component\Console\Application as ConsoleApplication; trait InteractsWithExceptionHandling { /** * The previous exception handler. * * @var ExceptionHandler|null */ protected $previousExceptionHandler; /** * Restore exception handling. * * @return $this */ protected function withExceptionHandling() { if ($this->previousExceptionHandler) { $this->app->instance(ExceptionHandler::class, $this->previousExceptionHandler); } return $this; } /** * Disable exception handling for the test. * * @return $this */ protected function withoutExceptionHandling() { $this->previousExceptionHandler = app(ExceptionHandler::class); $this->app->instance(ExceptionHandler::class, new class implements ExceptionHandler { public function __construct() { } public function report(Exception $e) { } public function render($request, Exception $e) { throw $e; } public function renderForConsole($output, Exception $e) { (new ConsoleApplication)->renderException($e, $output); } }); return $this; } }
Change the name back to pyhumod With the change of name from pyhumod to humod this would be a separate pypi package and we don't want that.
# -*- coding: utf-8 -*- import os from distutils.core import setup from humod import __version__ CONFIG_FILES = [('/etc/ppp/peers', ['conf/humod'])] try: os.stat('/etc/ppp/options') except OSError: CONFIG_FILES = [('/etc/ppp/peers', ['conf/humod']), ('/etc/ppp/options', ['conf/options'])] setup(name='pyhumod', version=__version__, packages=['humod'], description='Access SMS, GSM and 3G features of Huawei and ' 'compatible modems via clean and pragmatic Python API', author='Slawek Ligus, František Malina', author_email='[email protected]', url='https://github.com/oozie/pyhumod', license='BSD', platforms=['Linux'], install_requires=['pyserial'], data_files=CONFIG_FILES, classifiers=['License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Intended Audience :: Developers', 'Topic :: Communications', 'Topic :: Software Development :: Libraries'])
# -*- coding: utf-8 -*- import os from distutils.core import setup from humod import __version__ CONFIG_FILES = [('/etc/ppp/peers', ['conf/humod'])] try: os.stat('/etc/ppp/options') except OSError: CONFIG_FILES = [('/etc/ppp/peers', ['conf/humod']), ('/etc/ppp/options', ['conf/options'])] setup(name='humod', version=__version__, packages=['humod'], description='Access SMS, GSM and 3G features of Huawei and ' 'compatible modems via clean and pragmatic Python API', author='Slawek Ligus, František Malina', author_email='[email protected]', url='https://github.com/oozie/pyhumod', license='BSD', platforms=['Linux'], install_requires=['pyserial'], data_files=CONFIG_FILES, classifiers=['License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: POSIX', 'Operating System :: POSIX :: Linux', 'Operating System :: MacOS :: MacOS X', 'Intended Audience :: Developers', 'Topic :: Communications', 'Topic :: Software Development :: Libraries'])
Update function name and return value
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def get_converted(self, type=Request.GET): if type is Request.GET: return self.data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
import requests from time import time class Client: def __init__(self, host, requests, do_requests_counter): self.host = host self.requests = requests self.counter = do_requests_counter class Request: GET = 'get' POST = 'post' def __init__(self, url, type=GET, data=None): self.url = url self.type = type self.data = data def do(self): try: data = '' if isinstance(self.data, RequestData): data = self.data.for_type(type=self.type) started = time() response = getattr(requests, self.type)( url=self.url, data=data ) finished = time() return finished - started except AttributeError: raise RequestTypeError(type=self.type) class RequestData: def __init__(self, data=None): self.data = data def for_type(self, type=Request.GET): if type is Request.GET: return data class RequestTypeError(Exception): def __init__(self, type): self.type = type def __str__(self): return 'Invalid request type "%s"' % self.type
Revert "bump to 0.8.1 to fix packaging issue" This reverts commit c3ea277ea65d11f7b9c6fb9d54bd0f0f3713a98d.
#!/usr/bin/env python from setuptools import setup, find_packages setup(name="opencivicdata-django", version='0.8.0', author="James Turk", author_email='[email protected]', license="BSD", description="python opencivicdata library", long_description="", url="", py_modules=['opencivicdata.apps', 'opencivicdata.common'], packages=['opencivicdata.admin', 'opencivicdata.management', 'opencivicdata.management.commands', 'opencivicdata.migrations', 'opencivicdata.models', 'opencivicdata.tests'], install_requires=[ 'Django>=1.9b1', 'psycopg2', 'opencivicdata-divisions', ], platforms=["any"], classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.4", ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup(name="opencivicdata-django", version='0.8.1', author="James Turk", author_email='[email protected]', license="BSD", description="python opencivicdata library", long_description="", url="", py_modules=['opencivicdata.apps', 'opencivicdata.common'], packages=['opencivicdata.admin', 'opencivicdata.management', 'opencivicdata.management.commands', 'opencivicdata.migrations', 'opencivicdata.models', 'opencivicdata.tests'], # ugly hack b/c this is a namespace package data_files=[('opencivicdata/templates/opencivicdata/admin/', [ 'opencivicdata/templates/opencivicdata/admin/merge.html', 'opencivicdata/templates/opencivicdata/admin/unresolved.html', 'opencivicdata/templates/opencivicdata/admin/unresolved-confirm.html', ])], install_requires=[ 'Django>=1.9rc2', 'psycopg2', 'opencivicdata-divisions', ], platforms=["any"], classifiers=["Development Status :: 4 - Beta", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Natural Language :: English", "Operating System :: OS Independent", "Programming Language :: Python :: 3.4", ], )
Fix incorrect id assign in Timelane
// @flow import _ from 'lodash' import ProxySet from './_proxy-set' import type Project from './project' import type Composition from './composition' import Layer from './layer' export default class TimeLane { static deserialize(timelaneJson: Object, comp: Composition) { const timelane = new TimeLane const config = _.pick(timelaneJson.config, ['name']) const layers = timelaneJson.layers.map(layerJson => Layer.deserialize(layerJson)) Object.defineProperty(timelane, 'id', {value: timelaneJson.id}) timelane.layers = new Set(layers) Object.assign(timelane.config, config) return timelane } id: ?string = null layers: Set<Layer> = new Set() config: { name: ?string, } = { name: null } get name(): string { return this.config.name } set name(name: string) { this.config.name = name } constructor() { Object.seal(this) } toPreBSON(): Object { return { id: this.id, config: Object.assign({}, this.config), layers: Array.from(this.layers.values()).map(layer => layer.toPreBSON()), } } toJSON(): Object { return { id: this.id, config: Object.assign({}, this.config), layers: Array.from(this.layers.values()).map(layer => layer.toJSON()), } } }
// @flow import _ from 'lodash' import ProxySet from './_proxy-set' import type Project from './project' import type Composition from './composition' import Layer from './layer' export default class TimeLane { static deserialize(timelaneJson: Object, comp: Composition) { const timelane = new TimeLane const config = _.pick(timelaneJson.config, ['name']) const layers = timelaneJson.layers.map(layerJson => Layer.deserialize(layerJson)) Object.defineProperty(timelane, 'id', timelaneJson.id) timelane.layers = new Set(layers) Object.assign(timelane.config, config) return timelane } id: ?string = null layers: Set<Layer> = new Set() config: { name: ?string, } = { name: null } get name(): string { return this.config.name } set name(name: string) { this.config.name = name } constructor() { Object.seal(this) } toPreBSON(): Object { return { id: this.id, config: Object.assign({}, this.config), layers: Array.from(this.layers.values()).map(layer => layer.toPreBSON()), } } toJSON(): Object { return { id: this.id, config: Object.assign({}, this.config), layers: Array.from(this.layers.values()).map(layer => layer.toJSON()), } } }
Add type hint for run_in_threadpool return type
import asyncio import functools import typing from typing import Any, AsyncGenerator, Iterator try: import contextvars # Python 3.7+ only. except ImportError: # pragma: no cover contextvars = None # type: ignore T = typing.TypeVar("T") async def run_in_threadpool( func: typing.Callable[..., T], *args: typing.Any, **kwargs: typing.Any ) -> T: loop = asyncio.get_event_loop() if contextvars is not None: # pragma: no cover # Ensure we run in the same context child = functools.partial(func, *args, **kwargs) context = contextvars.copy_context() func = context.run args = (child,) elif kwargs: # pragma: no cover # loop.run_in_executor doesn't accept 'kwargs', so bind them in here func = functools.partial(func, **kwargs) return await loop.run_in_executor(None, func, *args) class _StopIteration(Exception): pass def _next(iterator: Iterator) -> Any: # We can't raise `StopIteration` from within the threadpool iterator # and catch it outside that context, so we coerce them into a different # exception type. try: return next(iterator) except StopIteration: raise _StopIteration async def iterate_in_threadpool(iterator: Iterator) -> AsyncGenerator: while True: try: yield await run_in_threadpool(_next, iterator) except _StopIteration: break
import asyncio import functools import typing from typing import Any, AsyncGenerator, Iterator try: import contextvars # Python 3.7+ only. except ImportError: # pragma: no cover contextvars = None # type: ignore async def run_in_threadpool( func: typing.Callable, *args: typing.Any, **kwargs: typing.Any ) -> typing.Any: loop = asyncio.get_event_loop() if contextvars is not None: # pragma: no cover # Ensure we run in the same context child = functools.partial(func, *args, **kwargs) context = contextvars.copy_context() func = context.run args = (child,) elif kwargs: # pragma: no cover # loop.run_in_executor doesn't accept 'kwargs', so bind them in here func = functools.partial(func, **kwargs) return await loop.run_in_executor(None, func, *args) class _StopIteration(Exception): pass def _next(iterator: Iterator) -> Any: # We can't raise `StopIteration` from within the threadpool iterator # and catch it outside that context, so we coerce them into a different # exception type. try: return next(iterator) except StopIteration: raise _StopIteration async def iterate_in_threadpool(iterator: Iterator) -> AsyncGenerator: while True: try: yield await run_in_threadpool(_next, iterator) except _StopIteration: break
Modify Hero :: Life + 2
#-*- coding: utf-8 -*- from lib.base_entity import BaseEntity from lib.base_animation import BaseAnimation from pygame.locals import K_UP as UP class HeroAnimation(BaseAnimation): """Custom class Animation : HeroAnimation """ WIDTH_SPRITE = 31 HEIGHT_SPRITE = 31 def get_sprite(self, move_direction): direction_num = move_direction - UP frame = self.subsurface( self.frame * self.WIDTH_SPRITE, direction_num * self.HEIGHT_SPRITE, self.WIDTH_SPRITE, self.HEIGHT_SPRITE ).convert_alpha() return frame class Hero(BaseEntity): """Custom class Entity : Hero Entity for the player. Represents the player and player's move """ def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img): super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img) self.life = 3 def init_animation(self, max_frame, max_frame_delay, img): return HeroAnimation(max_frame, max_frame_delay, img) def is_alive(self): """Return true if player is alive""" return self.life > 0 def lose_life(self): self.life = self.life - 1 print self.life
#-*- coding: utf-8 -*- from lib.base_entity import BaseEntity from lib.base_animation import BaseAnimation from pygame.locals import K_UP as UP class HeroAnimation(BaseAnimation): """Custom class Animation : HeroAnimation """ WIDTH_SPRITE = 31 HEIGHT_SPRITE = 31 def get_sprite(self, move_direction): direction_num = move_direction - UP frame = self.subsurface( self.frame * self.WIDTH_SPRITE, direction_num * self.HEIGHT_SPRITE, self.WIDTH_SPRITE, self.HEIGHT_SPRITE ).convert_alpha() return frame class Hero(BaseEntity): """Custom class Entity : Hero Entity for the player. Represents the player and player's move """ def __init__(self, name, rect_data, speed, max_frame, max_frame_delay, img): super(Hero, self).__init__(name, rect_data, speed, max_frame, max_frame_delay, img) self.life = 1 def init_animation(self, max_frame, max_frame_delay, img): return HeroAnimation(max_frame, max_frame_delay, img) def is_alive(self): """Return true if player is alive""" return self.life > 0 def lose_life(self): self.life = self.life - 1
Add pdbpp to dev dependencies
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="[email protected]", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', 'pdbpp' ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
"""Mailmerge build and install configuration.""" import os try: from setuptools import setup except ImportError: from distutils.core import setup with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme_file: README = readme_file.read() setup( name="mailmerge", description="A simple, command line mail merge tool", long_description=README, version="1.9", author="Andrew DeOrio", author_email="[email protected]", url="https://github.com/awdeorio/mailmerge/", license="MIT", packages=["mailmerge"], keywords=["mail merge", "mailmerge", "email"], install_requires=[ "chardet", "click", "configparser", "jinja2", "future", "backports.csv;python_version<='2.7'", "markdown", ], extras_require={ 'dev': [ 'pylint', 'pydocstyle', 'pycodestyle', 'pytest', 'tox', ] }, # Python command line utilities will be installed in a PATH-accessible bin/ entry_points={ 'console_scripts': [ 'mailmerge = mailmerge.__main__:cli', ] }, )
[Backoffice] Add meta for easy development.
<?php /** * This file is part of the Clastic package. * * (c) Dries De Peuter <[email protected]> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Clastic\BlogBundle\Form\Module; use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension; use Symfony\Component\Form\FormBuilderInterface; /** * NodeTypeExtension * * @author Dries De Peuter <[email protected]> */ class BlogFormExtension extends AbstractNodeTypeExtension { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->findTab($builder, 'general') ->add('introduction', 'wysiwyg') ->add('body', 'wysiwyg'); $builder->get('tabs') ->add( $this->createTab($builder, 'category', array('label' => 'Category')) ->add('categories', 'entity_multi_select', array( 'class' => 'ClasticBlogBundle:Category', 'property' => 'node.title', 'required' => false, )) ); $builder->get('tabs')->add($this ->createTab($builder, 'links', array( 'label' => 'Links', 'position' => 'first', )) ->add('links', 'collection', array( 'type' => 'link', 'allow_add' => true, 'allow_delete' => true, 'required' => false, 'mapped' => false, )) ); } }
<?php /** * This file is part of the Clastic package. * * (c) Dries De Peuter <[email protected]> * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Clastic\BlogBundle\Form\Module; use Clastic\NodeBundle\Form\Extension\AbstractNodeTypeExtension; use Symfony\Component\Form\FormBuilderInterface; /** * NodeTypeExtension * * @author Dries De Peuter <[email protected]> */ class BlogFormExtension extends AbstractNodeTypeExtension { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $this->findTab($builder, 'general') ->add('introduction', 'wysiwyg') ->add('body', 'wysiwyg'); $builder->get('tabs') ->add( $this->createTab($builder, 'category', array('label' => 'Category')) ->add('categories', 'entity_multi_select', array( 'class' => 'ClasticBlogBundle:Category', 'property' => 'node.title', 'required' => false, )) ); } }
Call super __init__ in GameMDP
from .mdp import MDP from .game_mdp import GameMDP from ..utils import utility class FixedGameMDP(GameMDP): def __init__(self, game, opp_player, opp_idx): ''' opp_player: the opponent player opp_idx: the idx of the opponent player in the game ''' super(FixedGameMDP, self).__init__(game) self._opp_player = opp_player self._opp_idx = opp_idx self._agent_idx = opp_idx ^ 1 def reward(self, game, move, next_game): return utility(next_game, self._agent_idx) if next_game.is_over() else 0 def start_state(self): new_game = self._game.copy() if not new_game.is_over() and new_game.cur_player() == self._opp_idx: chosen_move = self._opp_player.choose_move(new_game) new_game.make_move(chosen_move) return new_game def transitions(self, game, move): if game.is_over(): return [] new_game = game.copy().make_move(move) if not new_game.is_over() and new_game.cur_player() == self._opp_idx: chosen_move = self._opp_player.choose_move(new_game) new_game.make_move(chosen_move) return [(new_game, 1.0)]
from .mdp import MDP from .game_mdp import GameMDP from ..utils import utility class FixedGameMDP(GameMDP): def __init__(self, game, opp_player, opp_idx): ''' opp_player: the opponent player opp_idx: the idx of the opponent player in the game ''' self._game = game self._opp_player = opp_player self._opp_idx = opp_idx self._agent_idx = opp_idx ^ 1 self._states = {} def reward(self, game, move, next_game): return utility(next_game, self._agent_idx) if next_game.is_over() else 0 def start_state(self): new_game = self._game.copy() if not new_game.is_over() and new_game.cur_player() == self._opp_idx: chosen_move = self._opp_player.choose_move(new_game) new_game.make_move(chosen_move) return new_game def transitions(self, game, move): if game.is_over(): return [] new_game = game.copy().make_move(move) if not new_game.is_over() and new_game.cur_player() == self._opp_idx: chosen_move = self._opp_player.choose_move(new_game) new_game.make_move(chosen_move) return [(new_game, 1.0)]
Use cached property decorator connection pool.
# -*- coding: utf-8 -*- from __future__ import absolute_import import urllib3 try: import simplejson as json except ImportError: import json # pyflakes.ignore from .decorators import cached_property from .errors import NSQHttpError class HTTPClient(object): @cached_property def http(self): return urllib3.connection_from_url(url=self.base_url) def http_request(self, method, url, **kwargs): response = self.http.request_encode_url(method, url, **kwargs) if 'application/json' in response.getheader('content-type', ''): return self._http_check_json(response) return self._http_check(response) def _http_check(self, response): if response.status != 200: raise NSQHttpError('http error <%s>' % response.status) return response.data def _http_check_json(self, response): try: data = json.loads(response.data) except ValueError: return self._http_check(response) if response.status != 200: status_txt = data.get('status_txt', 'http error') raise NSQHttpError('%s <%s>' % (status_txt, response.status)) return data['data'] def http_get(self, url, **kwargs): return self.http_request('GET', url, **kwargs) def http_post(self, url, **kwargs): return self.http_request('POST', url, **kwargs)
# -*- coding: utf-8 -*- from __future__ import absolute_import import urllib3 try: import simplejson as json except ImportError: import json # pyflakes.ignore from .errors import NSQHttpError class HTTPClient(object): base_url = None __http = None @property def http(self): if self.__http is None: self.__http = urllib3.connection_from_url(url=self.base_url) return self.__http def http_request(self, method, url, **kwargs): response = self.http.request_encode_url(method, url, **kwargs) if 'application/json' in response.getheader('content-type', ''): return self._http_check_json(response) return self._http_check(response) def _http_check(self, response): if response.status != 200: raise NSQHttpError('http error <%s>' % response.status) return response.data def _http_check_json(self, response): try: data = json.loads(response.data) except ValueError: return self._http_check(response) if response.status != 200: status_txt = data.get('status_txt', 'http error') raise NSQHttpError('%s <%s>' % (status_txt, response.status)) return data['data'] def http_get(self, url, **kwargs): return self.http_request('GET', url, **kwargs) def http_post(self, url, **kwargs): return self.http_request('POST', url, **kwargs)
Improve accuracy of keyword counts.
/** Keyword analysis for HackMyResume. @license MIT. See LICENSE.md for details. @module keyword-inspector.js */ (function() { var _ = require('underscore'); var FluentDate = require('../core/fluent-date'); /** Analyze the resume's use of keywords. @class keywordInspector */ var keywordInspector = module.exports = { /** A unique name for this inspector. */ moniker: 'keyword-inspector', /** Run the Keyword Inspector on a resume. @method run @return An collection of statistical keyword data. */ run: function( rez ) { // http://stackoverflow.com/a/2593661/4942583 function regex_quote(str) { return (str + '').replace(/[.?*+^$[\]\\(){}|-]/ig, "\\$&"); } var searchable = ''; rez.transformStrings( ['imp', 'computed', 'safe'], function trxString( key, val ) { searchable += ' ' + val; }); return rez.keywords().map(function(kw) { var regex = new RegExp( '\\b' + regex_quote( kw )/* + '\\b'*/, 'ig'); var regex = new RegExp( regex_quote( kw ), 'ig'); var myArray, count = 0; while ((myArray = regex.exec( searchable )) !== null) { count++; } return { name: kw, count: count }; }); } }; }());
/** Keyword analysis for HackMyResume. @license MIT. See LICENSE.md for details. @module keyword-inspector.js */ (function() { var _ = require('underscore'); var FluentDate = require('../core/fluent-date'); /** Analyze the resume's use of keywords. @class keywordInspector */ var keywordInspector = module.exports = { /** A unique name for this inspector. */ moniker: 'keyword-inspector', /** Run the Keyword Inspector on a resume. @method run @return An collection of statistical keyword data. */ run: function( rez ) { // http://stackoverflow.com/a/2593661/4942583 function regex_quote(str) { return (str + '').replace(/[.?*+^$[\]\\(){}|-]/ig, "\\$&"); }; var searchable = ''; rez.transformStrings( [], function trxString( key, val ) { searchable += val; }); return rez.keywords().map(function(kw) { var regex = new RegExp( regex_quote( kw ), 'ig'); var myArray, count = 0; while ((myArray = regex.exec( searchable )) !== null) { count++; } return { name: kw, count: count }; }); } }; }());
Set base interval to 40 (to simulate a 25 fps video)
/*! * @license MIT * @author Marek Kalnik * @copyright (c) Maisons du Monde */ ;(function ($, document) { "use strict"; $.MDMAnimationHeartbeat = function (steps, speed) { var max = steps, current = 0, delay, interval, beat; // set default speed if none is passed as parameter delay = typeof speed !== 'undefined' ? speed : 40; $(document).bind('mdm-animation.stop', function () { clearInterval(interval); }); $(document).bind('mdm-animation.start', function () { if (current > max) { $(document).trigger('mdm-animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('mdm-animation.reset', function () { current = 0; }); $(document).bind('mdm-animation.beat', function (event, animation) { current = animation.current + 1; }); beat = function () { $(document).trigger('mdm-animation.beat', [ {'current':current, 'max':max} ]); if (current > max) { $(document).trigger('mdm-animation.stop'); } }; }; })(jQuery, document);
/*! * @license MIT * @author Marek Kalnik * @copyright (c) Maisons du Monde */ ;(function ($, document) { "use strict"; $.MDMAnimationHeartbeat = function (steps, speed) { var max = steps, current = 0, delay, interval, beat; // set default speed if none is passed as parameter delay = typeof speed !== 'undefined' ? speed : 70; $(document).bind('mdm-animation.stop', function () { clearInterval(interval); }); $(document).bind('mdm-animation.start', function () { if (current > max) { $(document).trigger('mdm-animation.reset'); } interval = setInterval(beat, delay); }); $(document).bind('mdm-animation.reset', function () { current = 0; }); $(document).bind('mdm-animation.beat', function (event, animation) { current = animation.current + 1; }); beat = function () { $(document).trigger('mdm-animation.beat', [ {'current':current, 'max':max} ]); if (current > max) { $(document).trigger('mdm-animation.stop'); } }; }; })(jQuery, document);
Add configuration options for randomness
# encoding: UTF-8 import random from . import config def sampler(source): def reshuffle(): copy = list(source) random.shuffle(copy) return copy stack = reshuffle() lastitem = '' while True: try: item = stack.pop() if item == lastitem: item = stack.pop() yield item lastitem = item except IndexError: stack = reshuffle() continue def incremental_chance(start=0.5, increment=0.01): current_chance = start while True: r = random.random() success = (r < current_chance) if success: current_chance = start else: current_chance += increment yield success def status_generator(): random_status = sampler(config.TWEET_MESSAGES) show_status = incremental_chance(start=config.TWEET_CHANCE_INITIAL, increment=config.TWEET_CHANCE_INCREMENT) fixed = config.TWEET_FIXED while True: status = '' if next(show_status): status = next(random_status) + " " yield "{status}{fixed}".format(status=status, fixed=fixed) if __name__ == '__main__': gen = status_generator() for i in range(0, 20): print(next(gen))
# encoding: UTF-8 import random from . import config def sampler(source): def reshuffle(): copy = list(source) random.shuffle(copy) return copy stack = reshuffle() lastitem = '' while True: try: item = stack.pop() if item == lastitem: item = stack.pop() yield item lastitem = item except IndexError: stack = reshuffle() continue def incremental_chance(increment=0.01, start=0.5): current_chance = start while True: r = random.random() success = (r < current_chance) if success: current_chance = start else: current_chance += increment yield success def status_generator(): random_status = sampler(config.TWEET_MESSAGES) show_status = incremental_chance(start=0, increment=0.25) fixed = config.TWEET_FIXED while True: status = '' if next(show_status): status = next(random_status) + " " yield "{status}{fixed}".format(status=status, fixed=fixed) if __name__ == '__main__': gen = status_generator() for i in range(0, 20): print(next(gen))
Add non-nullable modifier to return type of functions never returning null
/** * @description * var app = angular.module('App', ['flow.provider'], function(flowFactoryProvider){ * flowFactoryProvider.defaults = {target: '/'}; * }); * @name flowFactoryProvider */ angular.module('flow.provider', []) .provider('flowFactory', function() { 'use strict'; /** * Define the default properties for flow.js * @name flowFactoryProvider.defaults * @type {Object} */ this.defaults = {}; /** * Flow, MaybeFlow or NotFlow * @name flowFactoryProvider.factory * @type {function} * @return {!Flow} */ this.factory = function (options) { return new Flow(options); }; /** * Define the default events * @name flowFactoryProvider.events * @type {Array} * @private */ this.events = []; /** * Add default events * @name flowFactoryProvider.on * @function * @param {string} event * @param {Function} callback */ this.on = function (event, callback) { this.events.push([event, callback]); }; this.$get = function() { var fn = this.factory; var defaults = this.defaults; var events = this.events; return { 'create': function(opts) { // combine default options with global options and options var flow = fn(angular.extend({}, defaults, opts)); angular.forEach(events, function (event) { flow.on(event[0], event[1]); }); return flow; } }; }; });
/** * @description * var app = angular.module('App', ['flow.provider'], function(flowFactoryProvider){ * flowFactoryProvider.defaults = {target: '/'}; * }); * @name flowFactoryProvider */ angular.module('flow.provider', []) .provider('flowFactory', function() { 'use strict'; /** * Define the default properties for flow.js * @name flowFactoryProvider.defaults * @type {Object} */ this.defaults = {}; /** * Flow, MaybeFlow or NotFlow * @name flowFactoryProvider.factory * @type {function} * @return {Flow} */ this.factory = function (options) { return new Flow(options); }; /** * Define the default events * @name flowFactoryProvider.events * @type {Array} * @private */ this.events = []; /** * Add default events * @name flowFactoryProvider.on * @function * @param {string} event * @param {Function} callback */ this.on = function (event, callback) { this.events.push([event, callback]); }; this.$get = function() { var fn = this.factory; var defaults = this.defaults; var events = this.events; return { 'create': function(opts) { // combine default options with global options and options var flow = fn(angular.extend({}, defaults, opts)); angular.forEach(events, function (event) { flow.on(event[0], event[1]); }); return flow; } }; }; });
Revert "Rename lock to _lock to imply that it's private." tilequeue/queue/file.py -On second thought, the convention of prefixing private instance variables with an underscore isn't consistently adhered to elsewhere in the codebase, so don't bother using it, or we'll end up with a mix of classes that do and don't use it. This reverts commit 4417b3c701e44fbf94fb7375a7a3f148f1ee6112.
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self.lock = threading.RLock() def enqueue(self, coord): with self.lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self.lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self.lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self.lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
from tilequeue.tile import serialize_coord, deserialize_coord, CoordMessage import threading class OutputFileQueue(object): def __init__(self, fp): self.fp = fp self._lock = threading.RLock() def enqueue(self, coord): with self._lock: payload = serialize_coord(coord) self.fp.write(payload + '\n') def enqueue_batch(self, coords): n = 0 for coord in coords: self.enqueue(coord) n += 1 return n, 0 def read(self, max_to_read=1, timeout_seconds=20): with self._lock: coords = [] for _ in range(max_to_read): try: coord = next(self.fp) except StopIteration: break coords.append(CoordMessage(deserialize_coord(coord), None)) return coords def job_done(self, coord_message): pass def clear(self): with self._lock: self.fp.seek(0) self.fp.truncate() return -1 def close(self): with self._lock: remaining_queue = "".join([ln for ln in self.fp]) self.clear() self.fp.write(remaining_queue) self.fp.close()
[core] Check if @sanity/cli has dataset edit capabilities before using it
export default { name: 'visibility', group: 'dataset', signature: 'get/set [dataset] [mode]', description: 'Set visibility of a dataset', // eslint-disable-next-line complexity action: async (args, context) => { const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions const client = apiClient() if (!client.datasets.edit) { throw new Error('@sanity/cli must be upgraded first:\n npm install -g @sanity/cli') } if (!action) { throw new Error('Action must be provided (get/set)') } if (!['set', 'get'].includes(action)) { throw new Error('Invalid action (only get/set allowed)') } if (!ds) { throw new Error('Dataset name must be provided') } if (action === 'set' && !aclMode) { throw new Error('Please provide a visibility mode (public/private)') } const dataset = `${ds}` const current = (await client.datasets.list()).find(curr => curr.name === dataset) if (!current) { throw new Error('Dataset not found') } if (action === 'get') { output.print(current.aclMode) return } if (current.aclMode === aclMode) { output.print(`Dataset already in "${aclMode}"-mode`) return } if (aclMode === 'private') { output.print( 'Please note that while documents are private, assets (files and images) are still public\n' ) } await client.datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } }
export default { name: 'visibility', group: 'dataset', signature: 'get/set [dataset] [mode]', description: 'Set visibility of a dataset', // eslint-disable-next-line complexity action: async (args, context) => { const {apiClient, output} = context const [action, ds, aclMode] = args.argsWithoutOptions if (!action) { throw new Error('Action must be provided (get/set)') } if (!['set', 'get'].includes(action)) { throw new Error('Invalid action (only get/set allowed)') } if (!ds) { throw new Error('Dataset name must be provided') } if (action === 'set' && !aclMode) { throw new Error('Please provide a visibility mode (public/private)') } const dataset = `${ds}` const client = apiClient() const current = (await client.datasets.list()).find(curr => curr.name === dataset) if (!current) { throw new Error('Dataset not found') } if (action === 'get') { output.print(current.aclMode) return } if (current.aclMode === aclMode) { output.print(`Dataset already in "${aclMode}"-mode`) return } if (aclMode === 'private') { output.print( 'Please note that while documents are private, assets (files and images) are still public\n' ) } await apiClient().datasets.edit(dataset, {aclMode}) output.print('Dataset visibility changed') } }
Update API base url in static JS
var API_URL = 'https://api.buildnumber.io' $().ready( function(){ var $emailField = $('#email-field') var $signupButton = $('#signup-button') var $form = $('#signup-form') var $errorContainer = $('#signup-result .result-error') var $successContainer = $('#signup-result .result-success') $signupButton.ladda() $form.submit(function(ev) { ev.preventDefault() var email = $emailField.val() $emailField.prop('disabled', true) $signupButton.ladda('start') $errorContainer.slideUp(300) $successContainer.slideUp(300) $.post(API_URL + '/accounts', { email: email }).success(function(data) { var msg = "Your API token has been sent to " + email + ".<br>" + "Check your emails!" $successContainer.html(msg) $successContainer.slideDown(300) }).error(function(err) { $errorContainer.text(err) $errorContainer.slideDown(300) }).always(function() { $emailField.prop('disabled', false) $signupButton.ladda('stop') }) }) });
var API_URL = 'http://127.0.0.1:8000' $().ready( function(){ var $emailField = $('#email-field') var $signupButton = $('#signup-button') var $form = $('#signup-form') var $errorContainer = $('#signup-result .result-error') var $successContainer = $('#signup-result .result-success') $signupButton.ladda() $form.submit(function(ev) { ev.preventDefault() var email = $emailField.val() $emailField.prop('disabled', true) $signupButton.ladda('start') $errorContainer.slideUp(300) $successContainer.slideUp(300) $.post(API_URL + '/accounts', { email: email }).success(function(data) { var msg = "Your API token has been sent to " + email + ".<br>" + "Check your emails!" $successContainer.html(msg) $successContainer.slideDown(300) }).error(function(err) { $errorContainer.text(err) $errorContainer.slideDown(300) }).always(function() { $emailField.prop('disabled', false) $signupButton.ladda('stop') }) }) });
Test returning a json response.
<?php namespace TrueApex\ExpenseBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class ApiController extends Controller { public function indexAction() { $response_data = array( 'data' => array( array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 12000, 'notes' => 'Breakfast', ), array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 10000, 'notes' => 'Lunch', ), array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 11000, 'notes' => 'Dinner', ), ), 'error' => false, ); $json = json_encode($response_data); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; } }
<?php namespace TrueApex\ExpenseBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class ApiController extends Controller { public function indexAction() { $data = array( array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 12000, 'notes' => 'Breakfast', ), array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 10000, 'notes' => 'Lunch', ), array( 'category' => 'Food & Drinks', 'date' => 'Nov 23, 2016', 'amount' => 11000, 'notes' => 'Dinner', ), ); $json = json_encode($data); $response = new Response($json); $response->headers->set('Content-Type', 'application/json'); return $response; } }
Add PUT method to retrofit server
package org.commcare.core.network; import java.util.List; import java.util.Map; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.HeaderMap; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.QueryMap; import retrofit2.http.Streaming; import retrofit2.http.Url; public interface CommCareNetworkService { @Streaming @GET Call<ResponseBody> makeGetRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers); @Streaming @Multipart @POST Call<ResponseBody> makeMultipartPostRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers, @Part List<MultipartBody.Part> files); @Streaming @POST Call<ResponseBody> makePostRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers, @Body RequestBody body); @PUT Call<ResponseBody> makePutRequest(@Url String url, @Body RequestBody body); }
package org.commcare.core.network; import java.util.List; import java.util.Map; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.HeaderMap; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.QueryMap; import retrofit2.http.Streaming; import retrofit2.http.Url; public interface CommCareNetworkService { @Streaming @GET Call<ResponseBody> makeGetRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers); @Streaming @Multipart @POST Call<ResponseBody> makeMultipartPostRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers, @Part List<MultipartBody.Part> files); @Streaming @POST Call<ResponseBody> makePostRequest(@Url String url, @QueryMap Map<String, String> params, @HeaderMap Map<String, String> headers, @Body RequestBody body); }
Add use statement for SpecificationIterator
<?php /* * This file is part of the Behat. * (c) Konstantin Kudryashov <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Behat\Testwork\Ordering\Orderer; use Behat\Testwork\Specification\SpecificationArrayIterator; use Behat\Testwork\Specification\SpecificationIterator; /** * Prioritises Suites and Features into random order * * @author Ciaran McNulty <[email protected]> */ final class RandomOrderer implements Orderer { /** * @param SpecificationIterator[] $scenarioIterators * @return SpecificationIterator[] */ public function order(array $scenarioIterators) { $orderedFeatures = $this->orderFeatures($scenarioIterators); shuffle($orderedFeatures); return $orderedFeatures; } /** * @param array $scenarioIterators * @return array */ private function orderFeatures(array $scenarioIterators) { $orderedSuites = array(); foreach ($scenarioIterators as $scenarioIterator) { $orderedSpecifications = iterator_to_array($scenarioIterator); shuffle($orderedSpecifications); $orderedSuites[] = new SpecificationArrayIterator( $scenarioIterator->getSuite(), $orderedSpecifications ); } return $orderedSuites; } /** * @return string */ public function getName() { return 'random'; } }
<?php /* * This file is part of the Behat. * (c) Konstantin Kudryashov <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Behat\Testwork\Ordering\Orderer; use Behat\Testwork\Specification\SpecificationArrayIterator; /** * Prioritises Suites and Features into random order * * @author Ciaran McNulty <[email protected]> */ final class RandomOrderer implements Orderer { /** * @param SpecificationIterator[] $scenarioIterators * @return SpecificationIterator[] */ public function order(array $scenarioIterators) { $orderedFeatures = $this->orderFeatures($scenarioIterators); shuffle($orderedFeatures); return $orderedFeatures; } /** * @param array $scenarioIterators * @return array */ private function orderFeatures(array $scenarioIterators) { $orderedSuites = array(); foreach ($scenarioIterators as $scenarioIterator) { $orderedSpecifications = iterator_to_array($scenarioIterator); shuffle($orderedSpecifications); $orderedSuites[] = new SpecificationArrayIterator( $scenarioIterator->getSuite(), $orderedSpecifications ); } return $orderedSuites; } /** * @return string */ public function getName() { return 'random'; } }
Comment line with protocol to avoid this error javax.ws.rs.WebApplicationException: HTTP 422 Service 'gerrit-http-service' is invalid: spec.ports[0].protocol: unsupported value 'HTTP'
package io.fabric8.app.gerrit; import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor; import io.fabric8.openshift.api.model.template.TemplateBuilder; @KubernetesModelProcessor public class GerritModelProcessor { public void onList(TemplateBuilder builder) { builder.addNewServiceObject() .withNewMetadata() .withName("gerrit-http-service") .addToLabels("component", "gerrit") .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() /* .withProtocol("HTTP")*/ .withPort(80) .withNewTargetPort(8080) .endPort() .addToSelector("component", "gerrit") .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() // Second service .addNewServiceObject() .withNewMetadata() .withName("gerrit-ssh-service") .addToLabels("component", "gerrit") .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() /* .withProtocol("SSH")*/ .withPort(29418) .withNewTargetPort(29418) .endPort() .addToSelector("component", "gerrit") .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() .build(); } }
package io.fabric8.app.gerrit; import io.fabric8.kubernetes.generator.annotation.KubernetesModelProcessor; import io.fabric8.openshift.api.model.template.TemplateBuilder; @KubernetesModelProcessor public class GerritModelProcessor { public void onList(TemplateBuilder builder) { builder.addNewServiceObject() .withNewMetadata() .withName("gerrit-http-service") .addToLabels("component", "gerrit") .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("http") .withPort(80) .withNewTargetPort(8080) .endPort() .addToSelector("component", "gerrit") .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() // Second service .addNewServiceObject() .withNewMetadata() .withName("gerrit-ssh-service") .addToLabels("component", "gerrit") .addToLabels("provider", "fabric8") .endMetadata() .withNewSpec() .addNewPort() .withProtocol("ssh") .withPort(29418) .withNewTargetPort(29418) .endPort() .addToSelector("component", "gerrit") .addToSelector("provider", "fabric8") .endSpec() .endServiceObject() .build(); } }
Make sure we only write chars to stdout
import sys import os from datamodel.base import node class ConsolePrinter(node.Node): """ This node prints on stdout its context and then returns it as output. """ def input(self, context): self._context = context def output(self): try: sys.stdout.write(str(self._context)) sys.stdout.write(os.linesep) except: pass return self._context def reset(self): del self._context class LogPrinter(node.Node): """ This node prints its context on a statically defined logger and then returns it as output """ def __init__(self, logger, loglevel, stringify=False, name=None): """ :param logger: any logging.Logger subtype :param loglevel: the log level :param stringify: try to cast to str the context before passing it to the logger :param name: name of this node """ node.Node.__init__(self, name=name) self._logger = logger self._loglevel = loglevel self._stringify = stringify def input(self, context): self._context = context def output(self): str_context = self._context if self._stringify: try: str_context = str(self._context) except: pass # oops... self._logger.log(self._loglevel, str_context) return self._context def reset(self): del self._context
import sys from datamodel.base import node class ConsolePrinter(node.Node): """ This node prints on stdout its context and then returns it as output. """ def input(self, context): self._context = context def output(self): sys.stdout.write(self._context) return self._context def reset(self): del self._context class LogPrinter(node.Node): """ This node prints its context on a statically defined logger and then returns it as output """ def __init__(self, logger, loglevel, stringify=False, name=None): """ :param logger: any logging.Logger subtype :param loglevel: the log level :param stringify: try to cast to str the context before passing it to the logger :param name: name of this node """ node.Node.__init__(self, name=name) self._logger = logger self._loglevel = loglevel self._stringify = stringify def input(self, context): self._context = context def output(self): str_context = self._context if self._stringify: try: str_context = str(self._context) except: pass # oops... self._logger.log(self._loglevel, str_context) return self._context def reset(self): del self._context
Fix get user info link in search list
/** * * InputSearchLi * */ import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.scss'; function InputSearchLi({ onClick, isAdding, item }) { const icon = isAdding ? 'fa-plus' : 'fa-minus-circle'; const liStyle = isAdding ? { cursor: 'pointer' } : {}; const handleClick = isAdding ? () => onClick(item) : () => {}; const path = `/admin/plugins/content-manager/user/${item.id}?redirectUrl=/plugins/content-manager/user/?page=1&limit=20&sort=id&source=users-permissions`; return ( <li className={styles.li} style={liStyle} onClick={handleClick}> <div> <div className={styles.container}> {item.username} <a href={`${path}`} target="_blank"> <i className="fa fa-external-link" /> </a> </div> <div onClick={(e) => { e.stopPropagation(); e.preventDefault(); onClick(item); }} > <i className={`fa ${icon}`} /> </div> </div> </li> ); } InputSearchLi.defaultProps = { item: { name: '', }, }; InputSearchLi.propTypes = { isAdding: PropTypes.bool.isRequired, item: PropTypes.object, onClick: PropTypes.func.isRequired, }; export default InputSearchLi;
/** * * InputSearchLi * */ import React from 'react'; import PropTypes from 'prop-types'; import styles from './styles.scss'; function InputSearchLi({ onClick, isAdding, item }) { const icon = isAdding ? 'fa-plus' : 'fa-minus-circle'; const liStyle = isAdding ? { cursor: 'pointer' } : {}; const handleClick = isAdding ? () => onClick(item) : () => {}; const path = `/plugins/content-manager/user/${item.id}?redirectUrl=/plugins/content-manager/user/?page=1&limit=20&sort=id&source=users-permissions`; return ( <li className={styles.li} style={liStyle} onClick={handleClick}> <div> <div className={styles.container}> {item.username} <a href={`${path}`} target="_blank"> <i className="fa fa-external-link" /> </a> </div> <div onClick={(e) => { e.stopPropagation(); e.preventDefault(); onClick(item); }} > <i className={`fa ${icon}`} /> </div> </div> </li> ); } InputSearchLi.defaultProps = { item: { name: '', }, }; InputSearchLi.propTypes = { isAdding: PropTypes.bool.isRequired, item: PropTypes.object, onClick: PropTypes.func.isRequired, }; export default InputSearchLi;
Allow any logger implementing `LoggerInterface` to be passed
<?php /* * This file is apart of the DiscordPHP project. * * Copyright (c) 2016-2020 David Cole <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the LICENSE.md file. */ namespace Discord\Wrapper; use Psr\Log\LoggerInterface; /** * Provides an easy to use wrapper for the logger. */ class LoggerWrapper { /** * The logger. * * @var LoggerInterface Logger. */ protected $logger; /** * Whether logging is enabled. * * @var bool Logging enabled. */ protected $enabled; /** * Constructs the logger. * * @param LoggerInterface $logger The Monolog logger. * @param bool $enabled Whether logging is enabled. */ public function __construct(LoggerInterface $logger, $enabled = true) { $this->logger = $logger; $this->enabled = $enabled; } /** * Handles dynamic calls to the class. * * @param string $function The function called. * @param array $params The paramaters. * * @return mixed */ public function __call($function, $params) { if (! $this->enabled) { return false; } return call_user_func_array([$this->logger, $function], $params); } }
<?php /* * This file is apart of the DiscordPHP project. * * Copyright (c) 2016-2020 David Cole <[email protected]> * * This source file is subject to the MIT license that is bundled * with this source code in the LICENSE.md file. */ namespace Discord\Wrapper; use Monolog\Logger as Monolog; /** * Provides an easy to use wrapper for the logger. */ class LoggerWrapper { /** * The monolog logger. * * @var Monolog Logger. */ protected $logger; /** * Whether logging is enabled. * * @var bool Logging enabled. */ protected $enabled; /** * Constructs the logger. * * @param Monolog $logger The Monolog logger. * @param bool $enabled Whether logging is enabled. */ public function __construct(Monolog $logger, $enabled = true) { $this->logger = $logger; $this->enabled = $enabled; } /** * Handles dynamic calls to the class. * * @param string $function The function called. * @param array $params The paramaters. * * @return mixed */ public function __call($function, $params) { if (! $this->enabled) { return false; } return call_user_func_array([$this->logger, $function], $params); } }
Define a model for 'Analyses' in Analysis Request inherit from records_field_artemplate.
from openerp import fields, models, api from base_olims_model import BaseOLiMSModel schema = (fields.Many2one(string='Services', comodel_name='olims.analysis_service', domain="[('category', '=', Category)]", relation='recordfield_service'), fields.Boolean(string='Hidden',readonly=False), fields.Float(string='Price', default=0.00,compute='_ComputeServicePriceField'), fields.Many2one(string='Partition', comodel_name='olims.partition_ar_template'), fields.Many2one(string='Category', comodel_name='olims.analysis_category'), ) analysis_schema = (fields.Many2one(string='Priority', comodel_name='olims.ar_priority'), fields.Many2one(string='Partition', comodel_name='olims.ar_partition'), fields.Char(string="Error"), fields.Char(string="Min"), fields.Char(string="Max"), fields.Many2one(string='analysis_request_id', comodel_name ='olims.analysis_request'), ) class RecodrdsFieldARTemplate(models.Model, BaseOLiMSModel): _name='olims.records_field_artemplates' @api.onchange('Services') def _ComputeServicePriceField(self): # set auto-changing field for item in self: if item.Services: item.Price = item.Services.Price @api.onchange('Services') def _OnChangeGetServiceHiddenField(self): # set auto-changing field if self.Services: self.Hidden = self.Services.Hidden class ARAnalysis(models.Model, BaseOLiMSModel): _inherit = 'olims.records_field_artemplates' _name = 'olims.ar_analysis' RecodrdsFieldARTemplate.initialze(schema) ARAnalysis.initialze(analysis_schema)
from openerp import fields, models, api from base_olims_model import BaseOLiMSModel schema = (fields.Many2one(string='Services', comodel_name='olims.analysis_service', domain="[('category', '=', Category)]", relation='recordfield_service'), fields.Boolean(string='Hidden',readonly=False), fields.Float(string='Price', default=0.00,compute='_ComputeServicePriceField'), fields.Many2one(string='Partition', comodel_name='olims.partition_ar_template'), fields.Many2one(string='Category', comodel_name='olims.analysis_category'), ) class RecodrdsFieldARTemplate(models.Model, BaseOLiMSModel): _name='olims.records_field_artemplates' @api.onchange('Services') def _ComputeServicePriceField(self): # set auto-changing field for item in self: if item.Services: item.Price = item.Services.Price @api.onchange('Services') def _OnChangeGetServiceHiddenField(self): # set auto-changing field if self.Services: self.Hidden = self.Services.Hidden RecodrdsFieldARTemplate.initialze(schema)
Clear the contact form after it has been successfully posted.
from django.shortcuts import render from django.http import Http404 from django.contrib.messages import success from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .models import HomePage, StaticPage from category.models import Category from .forms import ContactForm def home_page(request, slug="home-page"): home_page = HomePage.objects.get(slug=slug) return render(request, "core/home_page.html", { "page": home_page, "categories": Category.objects.all()[:9] }) def static_page(request, slug=None): try: page = Page.objects.get(slug=slug) except Page.DoesNotExist: raise Http404 if page.specific_class == HomePage: return home_page(request, page.slug) return render(request, "core/static_page.html", { "self": page.specific }) def contribute(request, slug=None): page = StaticPage.objects.get(slug=slug) return render(request, "core/contribute.html", { "self": page }) def contact_us(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() success(request, _("Your query has successfully been sent")) form = ContactForm() else: form = ContactForm() return render(request, "core/contact_us.html", { "contact_form": form })
from django.shortcuts import render from django.http import Http404 from django.contrib.messages import success from django.utils.translation import ugettext_lazy as _ from wagtail.wagtailcore.models import Page from .models import HomePage, StaticPage from category.models import Category from .forms import ContactForm def home_page(request, slug="home-page"): home_page = HomePage.objects.get(slug=slug) return render(request, "core/home_page.html", { "page": home_page, "categories": Category.objects.all()[:9] }) def static_page(request, slug=None): try: page = Page.objects.get(slug=slug) except Page.DoesNotExist: raise Http404 if page.specific_class == HomePage: return home_page(request, page.slug) return render(request, "core/static_page.html", { "self": page.specific }) def contribute(request, slug=None): page = StaticPage.objects.get(slug=slug) return render(request, "core/contribute.html", { "self": page }) def contact_us(request): if request.method == "POST": form = ContactForm(request.POST) if form.is_valid(): form.save() success(request, _("Your query has successfully been sent")) else: form = ContactForm() return render(request, "core/contact_us.html", { "contact_form": form })
Increase timeout for integration test which might help Travis
var fs = require("fs"); var getDataUriForBase64PNG = function (pngBase64) { return "data:image/png;base64," + pngBase64; }; var renderPage = function (url, successCallback) { var page = require("webpage").create(); page.viewportSize = { width: 210, height: 110 }; page.open(url, function () { setTimeout(function () { var base64PNG, imgURI; base64PNG = page.renderBase64("PNG"); imgURI = getDataUriForBase64PNG(base64PNG); successCallback(imgURI); }, 500); }); }; renderPage(fs.absolute('test/integrationTestPage.html'), function (imageUrl) { renderPage(fs.absolute('test/fixtures/testResult.png'), function (targetImageUrl) { var imageDiffPage = require("webpage").create(); imageDiffPage.onConsoleMessage = function (msg) { console.log("Integration test: " + msg); if (msg === "success") { phantom.exit(0); } else { imageDiffPage.render("test/rasterizeHtmlSmokeTestDiff.png"); phantom.exit(1); } }; imageDiffPage.open("test/diffHelperPage.html", function () { imageDiffPage.evaluate(function (url1, url2) { isEqual(url1, url2, 5); }, imageUrl, targetImageUrl); }); }); });
var fs = require("fs"); var getDataUriForBase64PNG = function (pngBase64) { return "data:image/png;base64," + pngBase64; }; var renderPage = function (url, successCallback) { var page = require("webpage").create(); page.viewportSize = { width: 210, height: 110 }; page.open(url, function () { setTimeout(function () { var base64PNG, imgURI; base64PNG = page.renderBase64("PNG"); imgURI = getDataUriForBase64PNG(base64PNG); successCallback(imgURI); }, 200); }); }; renderPage(fs.absolute('test/integrationTestPage.html'), function (imageUrl) { renderPage(fs.absolute('test/fixtures/testResult.png'), function (targetImageUrl) { var imageDiffPage = require("webpage").create(); imageDiffPage.onConsoleMessage = function (msg) { console.log("Integration test: " + msg); if (msg === "success") { phantom.exit(0); } else { imageDiffPage.render("test/rasterizeHtmlSmokeTestDiff.png"); phantom.exit(1); } }; imageDiffPage.open("test/diffHelperPage.html", function () { imageDiffPage.evaluate(function (url1, url2) { isEqual(url1, url2, 5); }, imageUrl, targetImageUrl); }); }); });
Remove testing and debug stuff.
<?php require_once("../libs/sendgrid-php/sendgrid-php.php"); // Simple class to send email notifications. class Mailer { public static function sendMail($clientAddress, $body) { $request_body = json_decode('{ "personalizations": [ { "to": [ { "email": "'.$clientAddress.'" } ], "cc": [ { "email": "[email protected]" } ], "subject": "Your order!" } ], "from": { "email": "[email protected]" }, "content": [ { "type": "text/plain", "value": "'.$body.'" } ] }'); if (Mailer::getWeb1Env() == "PROD") { $apiKey = getenv('SENDGRID_API'); $sg = new \SendGrid($apiKey); $response = $sg->client->mail()->send()->post($request_body); // DEBUG //echo $request_body."\n"; //echo $response->statusCode(); //echo $response->headers(); //echo $response->body(); return $response->statusCode(); } else { // We do not send mails in dev and test. // Maybe print some debug output here. } } private static function getWeb1Env() { $env = getenv('WEB1_ENV'); if ( $env != "") { return $env; } else { die("WEB1_ENV environment variable is not set!"); } } }
<?php require_once("../libs/sendgrid-php/sendgrid-php.php"); // Simple class to send email notifications. class Mailer { public static function sendMail($clientAddress, $body) { $request_body = json_decode('{ "personalizations": [ { "to": [ { "email": "'.$clientAddress.'" } ], "cc": [ { "email": "[email protected]" } ], "subject": "Your order!" } ], "from": { "email": "[email protected]" }, "content": [ { "type": "text/plain", "value": "'.$body.'" } ] }'); if (Mailer::getWeb1Env() == "PROD") { $apiKey = getenv('SENDGRID_API'); $sg = new \SendGrid($apiKey); $response = $sg->client->mail()->send()->post($request_body); // DEBUG echo $request_body."\n"; echo $response->statusCode(); echo $response->headers(); echo $response->body(); return $response->statusCode(); } else { // We do not send mails in dev and test. // Maybe print some debug output here. } } private static function getWeb1Env() { $env = getenv('WEB1_ENV'); if ( $env != "") { return $env; } else { die("WEB1_ENV environment variable is not set!"); } } } Mailer::sendMail("[email protected]", "This is the body of the message.");
Remove used full path attribute
package com.choudhury.logger; import org.apache.log4j.BasicConfigurator; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Level; import java.util.logging.Logger; public class LoggerInterceptor extends HandlerInterceptorAdapter { static Logger logger = Logger.getLogger(LoggerInterceptor.class.getName()); static { BasicConfigurator.configure(); logger.setLevel(Level.INFO); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("Before handling the request"); return super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("After handling the request"); super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("After rendering the view"); super.afterCompletion(request, response, handler, ex); } }
package com.choudhury.logger; import org.apache.log4j.BasicConfigurator; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.logging.Level; import java.util.logging.Logger; public class LoggerInterceptor extends HandlerInterceptorAdapter { static Logger logger = Logger.getLogger(LoggerInterceptor.class.getName()); static { BasicConfigurator.configure(); logger.setLevel((Level) Level.INFO); } @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("Before handling the request"); return super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("After handling the request"); super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("After rendering the view"); super.afterCompletion(request, response, handler, ex); } }
Halo: Remove support for windows till fully tested
"""Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() if os_arch != 'Windows': return True return False def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def is_text_type(text): """Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not """ if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text
"""Utilities for Halo library. """ import platform import six import codecs from colorama import init, Fore from termcolor import colored init(autoreset=True) def is_supported(): """Check whether operating system supports main symbols or not. Returns ------- boolean Whether operating system supports main symbols or not """ os_arch = platform.system() + str(platform.architecture()[0]) if os_arch != 'Windows32bit': return True return False def colored_frame(frame, color): """Color the frame with given color and returns. Parameters ---------- frame : str Frame to be colored color : str Color to be applied Returns ------- str Colored frame """ return colored(frame, color, attrs=['bold']) def is_text_type(text): """Check if given parameter is a string or not Parameters ---------- text : * Parameter to be checked for text type Returns ------- bool Whether parameter is a string or not """ if isinstance(text, six.text_type) or isinstance(text, six.string_types): return True return False def decode_utf_8_text(text): """Decode the text from utf-8 format Parameters ---------- text : str String to be decoded Returns ------- str Decoded string """ try: return codecs.decode(text, 'utf-8') except: return text
Enable On the rocks plugin
# -*- coding: utf-8 -*- # Execute this file to see what plugins will be loaded. # Implementation leans to Lex Toumbourou's example: # https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/ import os import pkgutil import sys def load_venue_plugins(): """ Read plugin directory and load found plugins. Variable "blacklisted" can be used to exclude loading certain plugins. """ blacklisted = ["plugin_tiketti"] foundblacklisted = list() loadedplugins = list() pluginspathabs = os.path.join(os.path.dirname(__file__), "venues") for loader, plugname, ispkg in \ pkgutil.iter_modules(path = [pluginspathabs]): if plugname in sys.modules: continue if plugname in blacklisted: foundblacklisted.append(plugname.lstrip("plugin_")) continue plugpath = "venues.%s" % (plugname) loadplug = __import__(plugpath, fromlist = [plugname]) classname = plugname.split("_")[1].title() loadedclass = getattr(loadplug, classname) instance = loadedclass() loadedplugins.append(instance) print(f"Loaded plugin: {instance.getVenueName()}") print("Blacklisted plugins: {}.\n".format(", ".join(foundblacklisted[1:]))) return loadedplugins if __name__ == '__main__': load_venue_plugins()
# -*- coding: utf-8 -*- # Execute this file to see what plugins will be loaded. # Implementation leans to Lex Toumbourou's example: # https://lextoumbourou.com/blog/posts/dynamically-loading-modules-and-classes-in-python/ import os import pkgutil import sys def load_venue_plugins(): """ Read plugin directory and load found plugins. Variable "blacklisted" can be used to exclude loading certain plugins. """ blacklisted = ["plugin_tiketti", "plugin_ontherocks"] foundblacklisted = list() loadedplugins = list() pluginspathabs = os.path.join(os.path.dirname(__file__), "venues") for loader, plugname, ispkg in \ pkgutil.iter_modules(path = [pluginspathabs]): if plugname in sys.modules: continue if plugname in blacklisted: foundblacklisted.append(plugname.lstrip("plugin_")) continue plugpath = "venues.%s" % (plugname) loadplug = __import__(plugpath, fromlist = [plugname]) classname = plugname.split("_")[1].title() loadedclass = getattr(loadplug, classname) instance = loadedclass() loadedplugins.append(instance) print(f"Loaded plugin: {instance.getVenueName()}") print("Blacklisted plugins: {}.\n".format(", ".join(foundblacklisted[1:]))) return loadedplugins if __name__ == '__main__': load_venue_plugins()
Add docopt - not finished
"""Usage: logview [options] Options: -h, --help show this help message -v, --verbose print status messages --ignore=loglevels ignore logs of the specified levels """ import threading import socket import logging import os import colorama import docopt from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
import threading import socket import logging import os import colorama from termcolor import colored from collections import deque markerStack = deque(['']) def colorMessage(message): if 'Info' in message : print(colored(message, 'green')) elif 'Error' in message : print(colored(message, 'red')) elif 'Fatal' in message : print(colored(message, 'red', 'white')) else: print(message) def appendMessageToBuffer(message): markerStack.append(message) if len(markerStack) > MAX_ELEMENTS_IN_QUEUE: markerStack.popleft() def updateView(): for marker in reversed(markerStack): colorMessage(marker) class UdpListener(): def __init__(self): self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.bind(('127.0.0.1', 4242)) self.clients_list = [] def listen(self): while True: msg = self.sock.recv(4096) appendMessageToBuffer(msg) updateView() def start_listening(self): t = threading.Thread(target=self.listen) t.start() if __name__ == "__main__": print 'call' colorama.init() listener = UdpListener() listener.start_listening()
Set the default color to teal
import React, { PureComponent } from 'react'; import Box from '../box'; import PropTypes from 'prop-types'; import cx from 'classnames'; import omit from 'lodash.omit'; import theme from './theme.css'; const factory = (baseType, type, defaultElement) => { class Text extends PureComponent { isSoft(color) { if (color !== 'white' && color !== 'teal') { return false; } return this.props.soft; } render() { const { children, className, color, element, ...others } = this.props; const isSoft = this.isSoft(color); const classNames = cx( theme[baseType], theme[type], theme[color], { [theme['soft']]: isSoft, }, className, ); const Element = element || defaultElement; const rest = omit(others, ['soft']); return ( <Box className={classNames} data-teamleader-ui={baseType} element={Element} {...rest}> {children} </Box> ); } } Text.propTypes = { children: PropTypes.node, className: PropTypes.string, color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']), element: PropTypes.node, soft: PropTypes.bool, }; Text.defaultProps = { color: 'teal', element: null, soft: false, }; return Text; }; export { factory as textFactory };
import React, { PureComponent } from 'react'; import Box from '../box'; import PropTypes from 'prop-types'; import cx from 'classnames'; import omit from 'lodash.omit'; import theme from './theme.css'; const factory = (baseType, type, defaultElement) => { class Text extends PureComponent { isSoft(color) { if (color !== 'white' && color !== 'teal') { return false; } return this.props.soft; } render() { const { children, className, color, element, ...others } = this.props; const isSoft = this.isSoft(color); const classNames = cx( theme[baseType], theme[type], theme[color], { [theme['soft']]: isSoft, }, className, ); const Element = element || defaultElement; const rest = omit(others, ['soft']); return ( <Box className={classNames} data-teamleader-ui={baseType} element={Element} {...rest}> {children} </Box> ); } } Text.propTypes = { children: PropTypes.node, className: PropTypes.string, color: PropTypes.oneOf(['white', 'neutral', 'mint', 'teal', 'violet', 'ruby', 'gold', 'aqua']), element: PropTypes.node, soft: PropTypes.bool, }; Text.defaultProps = { element: null, soft: false, }; return Text; }; export { factory as textFactory };
Fix BEM preset; ignoreComments --> false
var _ = require('lodash'); /** * Sets options * @param {Object} [options] * @param {String[]} [options.ignoreAttributes] * @param {String[]} [options.compareAttributesAsJSON] * @param {Boolean} [options.ignoreWhitespaces=true] * @param {Boolean} [options.ignoreComments=true] * @param {Boolean} [options.ignoreClosingTags=false] * @param {Boolean} [options.ignoreDuplicateAttributes=false] * returns {Object} */ module.exports = function (options) { if (typeof options === 'string') { if (options === 'bem') { options = { // ignore generated attributes ignoreAttributes: ['id', 'for', 'aria-labelledby', 'aria-describedby'], compareAttributesAsJSON: [ 'data-bem', { name: 'onclick', isFunction: true }, { name: 'ondblclick', isFunction: true } ], ignoreComments: false }; } else { console.error(options.bold.red + ' is an invalid preset name. Use ' + 'bem'.bold.green + ' instead.'); process.exit(1); } } return _.defaults(options || {}, { ignoreAttributes: [], compareAttributesAsJSON: [], ignoreWhitespaces: true, ignoreComments: true, ignoreEndTags: false, ignoreDuplicateAttributes: false }); };
var _ = require('lodash'); /** * Sets options * @param {Object} [options] * @param {String[]} [options.ignoreAttributes] * @param {String[]} [options.compareAttributesAsJSON] * @param {Boolean} [options.ignoreWhitespaces=true] * @param {Boolean} [options.ignoreComments=true] * @param {Boolean} [options.ignoreClosingTags=false] * @param {Boolean} [options.ignoreDuplicateAttributes=false] * returns {Object} */ module.exports = function (options) { if (typeof options === 'string') { if (options === 'bem') { options = { // ignore generated attributes ignoreAttributes: ['id', 'for', 'aria-labelledby', 'aria-describedby'], compareAttributesAsJSON: [ 'data-bem', { name: 'onclick', isFunction: true }, { name: 'ondblclick', isFunction: true } ] }; } else { console.error(options.bold.red + ' is an invalid preset name. Use ' + 'bem'.bold.green + ' instead.'); process.exit(1); } } return _.defaults(options || {}, { ignoreAttributes: [], compareAttributesAsJSON: [], ignoreWhitespaces: true, ignoreComments: true, ignoreEndTags: false, ignoreDuplicateAttributes: false }); };
Add test to show login form is broken
from django.core import management from django.utils import unittest from django.contrib.contenttypes.models import ContentType from django.test.client import Client from post.models import Post from foundry.models import Member, Listing class TestCase(unittest.TestCase): def setUp(self): self.client = Client() # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='[email protected]' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all()) def test_pages(self): response =self.client.get('/login') self.assertEqual(response.status_code, 200) self.failIf(response.content.find('<form') == -1)
from django.core import management from django.test import TestCase from django.contrib.contenttypes.models import ContentType from post.models import Post from foundry.models import Member, Listing class TestCase(TestCase): def setUp(self): # Post-syncdb steps management.call_command('migrate', interactive=False) management.call_command('load_photosizes', interactive=False) # Editor self.editor, dc = Member.objects.get_or_create( username='editor', email='[email protected]' ) # Posts for i in range(1, 5): post = Post.objects.create( title='Post %s' % i, content='<b>aaa</b>', owner=self.editor, state='published', ) post.sites = [1] post.save() setattr(self, 'post%s' % i, post) def test_listing(self): content_type = ContentType.objects.get(app_label='post', model='post') posts = Listing.objects.create( title='Posts', count=0, style='VerticalThumbnail', ) posts.content_type = [content_type] posts.sites = [1] posts.save() self.failUnless(self.post1.modelbase_obj in posts.queryset.all())
jsonpickle.handler: Remove usage of built-in 'type' name 'type' is a built-in function so use 'cls' instead of 'type'. Signed-off-by: David Aguilar <[email protected]>
class BaseHandler(object): """ Abstract base class for handlers. """ def __init__(self, base): """ Initialize a new handler to handle `type`. :Parameters: - `base`: reference to pickler/unpickler """ self._base = base def flatten(self, obj, data): """ Flatten `obj` into a json-friendly form. :Parameters: - `obj`: object of `type` """ raise NotImplementedError("Abstract method.") def restore(self, obj): """ Restores the `obj` to `type` :Parameters: - `object`: json-friendly object """ raise NotImplementedError("Abstract method.") class Registry(object): REGISTRY = {} def register(self, cls, handler): """ Register handler. :Parameters: - `cls`: Object class - `handler`: `BaseHandler` subclass """ self.REGISTRY[cls] = handler return handler def get(self, cls): """ Get the customer handler for `obj` (if any) :Parameters: - `cls`: class to handle """ return self.REGISTRY.get(cls, None) registry = Registry()
class BaseHandler(object): """ Abstract base class for handlers. """ def __init__(self, base): """ Initialize a new handler to handle `type`. :Parameters: - `base`: reference to pickler/unpickler """ self._base = base def flatten(self, obj, data): """ Flatten `obj` into a json-friendly form. :Parameters: - `obj`: object of `type` """ raise NotImplementedError("Abstract method.") def restore(self, obj): """ Restores the `obj` to `type` :Parameters: - `object`: json-friendly object """ raise NotImplementedError("Abstract method.") class Registry(object): REGISTRY = {} def register(self, type, handler): """ Register handler. :Parameters: - `handler`: `BaseHandler` subclass """ self.REGISTRY[type] = handler return handler def get(self, cls): """ Get the customer handler for `obj` (if any) :Parameters: - `cls`: class to handle """ return self.REGISTRY.get(cls, None) registry = Registry()
Save token to session storage
/** * Created by dell on 2015/6/9. */ (function(){ "use strict"; var adminServices = angular.module('app.admin.services',["app.services"]); adminServices.factory("adminInfo",["ApiServer",function(ApiServer){ return ApiServer.createResource('admin/login',{},{ "login":{method:'POST',url:ApiServer.getApiUrl('admin/login')} }); }]); adminServices.service('admin',[function(){ this._id; this.name; this.last_login; this.token; this.set = function(info){ this._id = info._id; this.name = info.name; this.last_login = info.last_login; this.token = info.token; }; }]); adminServices.service('adminManager',['adminInfo','$q','admin',function(adminInfo,$q,admin){ this.login = function(user_info){ var deferred = $q.defer(); adminInfo.login(user_info).$promise.then(function(response){ admin.set(response.context); sessionStorage.setItem("AUTHOR",JSON.stringify(response.context)); sessionStorage.setItem("TOKEN",response.context.token); deferred.resolve(response); },function(){ deferred.reject(); }); return deferred.promise; } }]); }).call(this);
/** * Created by dell on 2015/6/9. */ (function(){ "use strict"; var adminServices = angular.module('app.admin.services',["app.services"]); adminServices.factory("adminInfo",["ApiServer",function(ApiServer){ return ApiServer.createResource('admin/login',{},{ "login":{method:'POST',url:ApiServer.getApiUrl('admin/login')} }); }]); adminServices.service('admin',[function(){ this._id; this.name; this.last_login; this.token; this.set = function(info){ this._id = info._id; this.name = info.name; this.last_login = info.last_login; this.token = info.token; }; }]); adminServices.service('adminManager',['adminInfo','$q','admin',function(adminInfo,$q,admin){ this.login = function(user_info){ var deferred = $q.defer(); adminInfo.login(user_info).$promise.then(function(response){ admin.set(response.context); sessionStorage.setItem("AUTHOR",JSON.stringify(response.context)); deferred.resolve(response); },function(){ deferred.reject(); }); return deferred.promise; } }]); }).call(this);
Rename Template to CfnTemplate to avoid name collision
import boto3 import sys from colors import green, red from botocore.exceptions import ClientError s3_client = boto3.client('s3') class InvalidTemplateError(BaseException): def __init__(self, m): self.m = m def __str__(self): return self.m class CfnTemplate(): def __init__(self, file): self.file = file try: self.content = open(file, 'r').read() except IOError as e: print(red('File {!r} does not exist'.format(file))) raise e self.public_url = '' self.key = '' def validate(self): sys.stdout.write('Validating {} ... '.format(self.file)) cfn_client = boto3.client('cloudformation') try: cfn_client.validate_template(TemplateBody=self.content) except ClientError as e: print(red('invalid')) print(e) exit(1) else: print(green('valid')) return self def upload(self, bucket, path): self.key = path.strip('/') + '/' + self.file self.public_url = 'https://{}.s3.amazonaws.com/{}'.format(bucket, self.key) print("Publishing {} to {}".format(self.file, self.public_url)) s3_client.put_object( Bucket=bucket, Body=self.content, ACL='public-read', Key=path + '/' + self.file ) return self
import boto3 import sys from colors import green, red from botocore.exceptions import ClientError s3_client = boto3.client('s3') class InvalidTemplateError(BaseException): def __init__(self, m): self.m = m def __str__(self): return self.m class Template(): def __init__(self, file): self.file = file try: self.content = open(file, 'r').read() except IOError as e: print(red('File {!r} does not exist'.format(file))) raise e self.public_url = '' self.key = '' def validate(self): sys.stdout.write('Validating {} ... '.format(self.file)) cfn_client = boto3.client('cloudformation') try: cfn_client.validate_template(TemplateBody=self.content) except ClientError as e: print(red('invalid')) print(e) exit(1) else: print(green('valid')) return self def upload(self, bucket, path): self.key = path.strip('/') + '/' + self.file self.public_url = 'https://{}.s3.amazonaws.com/{}'.format(bucket, self.key) print("Publishing {} to {}".format(self.file, self.public_url)) s3_client.put_object( Bucket=bucket, Body=self.content, ACL='public-read', Key=path + '/' + self.file ) return self
Use "npm ci" instead of "npm i"
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm ci')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish' + (version.includes('rc')? ' --tag next' : ''))) .then(() => { console.log(`version ${version} has just been released`); }) .done();
var vow = require('vow'), vowNode = require('vow-node'), childProcess = require('child_process'), fs = require('fs'), exec = vowNode.promisify(childProcess.exec), readFile = vowNode.promisify(fs.readFile), writeFile = vowNode.promisify(fs.writeFile); version = process.argv.slice(2)[0] || 'patch'; exec('git pull') .then(() => exec('npm i')) .then(() => exec('npm run build')) .then(() => exec(`npm version ${version}`)) .then(() => vow.all([ readFile('package.json', 'utf8'), readFile(__dirname + '/distHeaderTmpl.txt', 'utf8'), readFile('dist/vidom.js'), readFile('dist/vidom.min.js') ])) .spread((packageContent, distHeaderTmpl, distContent, distMinContent) => { version = JSON.parse(packageContent).version; var distHeader = distHeaderTmpl.replace('${VERSION}', version); return vow.all([ writeFile('dist/vidom.js', distHeader + distContent), writeFile('dist/vidom.min.js', distHeader + distMinContent) ]); }) .then(() => exec('git push --follow-tags')) .then(() => exec('npm publish' + (version.includes('rc')? ' --tag next' : ''))) .then(() => { console.log(`version ${version} has just been released`); }) .done();
Add 127.0.0.1 default if Public IP not specified.
'use strict'; // to allow mongodb host and port injection thanks // to the EZMASTER_MONGODB_HOST_PORT environment parameter // (docker uses it) var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT ? process.env.EZMASTER_MONGODB_HOST_PORT : 'localhost:27017'; var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN ? process.env.EZMASTER_PUBLIC_DOMAIN : null; /* var publicIP = process.env.EZMASTER_PUBLIC_IP ? process.env.EZMASTER_PUBLIC_IP : '127.0.0.1'; */ var publicIP = process.env.EZMASTER_PUBLIC_IP || '127.0.0.1'; module.exports = { connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster', collectionName: 'data', publicDomain: publicDomain, publicIP: publicIP, browserifyModules : [ 'vue' , 'vue-resource' , 'components/addInstance' , 'components/table' , 'vue-validator' , 'heartbeats' ], rootURL : '/', routes: [ 'route.js', 'status.js' ], middlewares: { '/*': 'reverseproxy.js' }, filters: ['jbj-parse'] }; module.exports.package = require('./package.json');
'use strict'; // to allow mongodb host and port injection thanks // to the EZMASTER_MONGODB_HOST_PORT environment parameter // (docker uses it) var mongoHostPort = process.env.EZMASTER_MONGODB_HOST_PORT ? process.env.EZMASTER_MONGODB_HOST_PORT : 'localhost:27017'; var publicDomain = process.env.EZMASTER_PUBLIC_DOMAIN ? process.env.EZMASTER_PUBLIC_DOMAIN : null; var publicIP = process.env.EZMASTER_PUBLIC_IP ? process.env.EZMASTER_PUBLIC_IP : '127.0.0.1'; module.exports = { connectionURI: 'mongodb://' + mongoHostPort + '/ezmaster', collectionName: 'data', publicDomain: publicDomain, publicIP: publicIP, browserifyModules : [ 'vue' , 'vue-resource' , 'components/addInstance' , 'components/table' , 'vue-validator' , 'heartbeats' ], rootURL : '/', routes: [ 'route.js', 'status.js' ], middlewares: { '/*': 'reverseproxy.js' }, filters: ['jbj-parse'] }; module.exports.package = require('./package.json');
Fix scrollspy bug occured by layout changes
(function () { var $body = $('body'); if (!isMobile) { $('.section-tabs a').click(function () { var href = $(this).attr('href'); gotoTab(href); return false; }); $body.scrollspy({ 'data-spy': 'scroll', 'data-target': '.section-tabs', 'offset': 100 }) .on('activate.changehash', function () { var target = $('.section-tabs li.active a').attr('href'); selectTab(target); }); function gotoTab(target) { selectTab(target); var $elem = $(target); $body.animate({ scrollTop: $elem.offset().top }, 300); } function selectTab(target) { var $list = $('.section-tabs li'); $list.removeClass('active'); $list.children('[href="'+target+'"]').parent('li').addClass('active'); if (location.hash != target) { if (history.pushState) { history.pushState({}, null, target); } else { location.hash = target; } } } } }());
(function () { var $specContainer = $('#spec-container'); if (!isMobile) { $('.section-tabs a').click(function () { var href = $(this).attr('href'); gotoTab(href); return false; }); $specContainer.scrollspy({ 'data-spy': 'scroll', 'data-target': '.section-tabs', 'offset': 100 }) .on('activate.changehash', function () { var target = $('.section-tabs li.active a').attr('href'); selectTab(target); }); function gotoTab(target) { selectTab(target); var $elem = $(target); $specContainer.animate({ scrollTop: $specContainer.scrollTop() + $elem.position().top }, 300); } function selectTab(target) { var $list = $('.section-tabs li'); $list.removeClass('active'); $list.children('[href="'+target+'"]').parent('li').addClass('active'); if (location.hash != target) { if (history.pushState) { history.pushState({}, null, target); } else { location.hash = target; } } } } }());
Change output for algorithm list to service name instead of class name
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\Console\Processor; use Picodexter\ParameterEncryptionBundle\Configuration\AlgorithmConfigurationContainerInterface; use Symfony\Component\Console\Helper\Table; /** * AlgorithmListProcessor. */ class AlgorithmListProcessor implements AlgorithmListProcessorInterface { /** * @var AlgorithmConfigurationContainerInterface */ private $algorithmConfigContainer; /** * Constructor. * * @param AlgorithmConfigurationContainerInterface $algorithmContainer */ public function __construct(AlgorithmConfigurationContainerInterface $algorithmContainer) { $this->algorithmConfigContainer = $algorithmContainer; } /** * @inheritDoc */ public function renderAlgorithmListTable(Table $table) { $table->setHeaders(['Algorithm ID', 'Encryption service name', 'Decryption service name']); foreach ($this->algorithmConfigContainer->getAlgorithmConfigurations() as $algorithm) { $table->addRow([ $algorithm->getId(), $algorithm->getEncrypterServiceName(), $algorithm->getDecrypterServiceName() ]); } $table->render(); } }
<?php /* * This file is part of the PcdxParameterEncryptionBundle package. * * (c) picodexter <https://picodexter.io/> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Picodexter\ParameterEncryptionBundle\Console\Processor; use Picodexter\ParameterEncryptionBundle\Configuration\AlgorithmConfigurationContainerInterface; use Symfony\Component\Console\Helper\Table; /** * AlgorithmListProcessor. */ class AlgorithmListProcessor implements AlgorithmListProcessorInterface { /** * @var AlgorithmConfigurationContainerInterface */ private $algorithmConfigContainer; /** * Constructor. * * @param AlgorithmConfigurationContainerInterface $algorithmContainer */ public function __construct(AlgorithmConfigurationContainerInterface $algorithmContainer) { $this->algorithmConfigContainer = $algorithmContainer; } /** * @inheritDoc */ public function renderAlgorithmListTable(Table $table) { $table->setHeaders(['Algorithm ID', 'Encryption class', 'Decryption class']); foreach ($this->algorithmConfigContainer->getAlgorithmConfigurations() as $algorithm) { $table->addRow([ $algorithm->getId(), get_class($algorithm->getEncrypter()), get_class($algorithm->getDecrypter()) ]); } $table->render(); } }
Sort the list of files processed before running the test on each.
#! /usr/bin/env python # (Force the script to use the latest build.) # # test_parser.py import parser, traceback _numFailed = 0 def testChunk(t, fileName): global _numFailed print '----', fileName, try: ast = parser.suite(t) tup = parser.ast2tuple(ast) # this discards the first AST; a huge memory savings when running # against a large source file like Tkinter.py. ast = None new = parser.tuple2ast(tup) except parser.ParserError, err: print print 'parser module raised exception on input file', fileName + ':' traceback.print_exc() _numFailed = _numFailed + 1 else: if tup != parser.ast2tuple(new): print print 'parser module failed on input file', fileName _numFailed = _numFailed + 1 else: print 'o.k.' def testFile(fileName): t = open(fileName).read() testChunk(t, fileName) def test(): import sys args = sys.argv[1:] if not args: import glob args = glob.glob("*.py") args.sort() map(testFile, args) sys.exit(_numFailed != 0) if __name__ == '__main__': test()
#! /usr/bin/env python # (Force the script to use the latest build.) # # test_parser.py import parser, traceback _numFailed = 0 def testChunk(t, fileName): global _numFailed print '----', fileName, try: ast = parser.suite(t) tup = parser.ast2tuple(ast) # this discards the first AST; a huge memory savings when running # against a large source file like Tkinter.py. ast = None new = parser.tuple2ast(tup) except parser.ParserError, err: print print 'parser module raised exception on input file', fileName + ':' traceback.print_exc() _numFailed = _numFailed + 1 else: if tup != parser.ast2tuple(new): print print 'parser module failed on input file', fileName _numFailed = _numFailed + 1 else: print 'o.k.' def testFile(fileName): t = open(fileName).read() testChunk(t, fileName) def test(): import sys args = sys.argv[1:] if not args: import glob args = glob.glob("*.py") map(testFile, args) sys.exit(_numFailed != 0) if __name__ == '__main__': test() # # end of file
Define __DEV__ for frontend tests
import webpack from 'webpack' import nodeExternals from 'webpack-node-externals'; var path = require('path') export default { target: 'node', externals: [nodeExternals()], module: { rules: [ //{ test: /\.jsx$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.js$/, exclude: /node_modules/, use: ["react-hot-loader", "babel-loader"] }, { test: /\.css$/, use: ["style-loader","css"] }, { test: /\.sass$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader", options : { includePaths: ["./"] } }] }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file-loader', { loader: 'image-webpack-loader', query: { mozjpeg: { progressive: true, }, gifslice: { interlaced: false, }, optipng: { optimizationLevel: 7, }, pngquant: { quality: '65-90', speed: 4 } } } ] } ] }, devtool: "cheap-module-source-map", resolve: { alias:{ app : path.resolve("./app/js"), sass : path.resolve("./app/sass"), lang : path.resolve("./lang") } }, plugins: [ new webpack.DefinePlugin({ __DEV__: JSON.stringify(false), }) ] };
import nodeExternals from 'webpack-node-externals'; var path = require('path') export default { target: 'node', externals: [nodeExternals()], module: { rules: [ //{ test: /\.jsx$/, loaders: ['react-hot', 'babel'], exclude: /node_modules/ }, { test: /\.js$/, exclude: /node_modules/, use: ["react-hot-loader", "babel-loader"] }, { test: /\.css$/, use: ["style-loader","css"] }, { test: /\.sass$/, use: [{ loader: "style-loader" }, { loader: "css-loader" }, { loader: "sass-loader", options : { includePaths: ["./"] } }] }, { test: /\.(jpe?g|png|gif|svg)$/i, loaders: [ 'file-loader', { loader: 'image-webpack-loader', query: { mozjpeg: { progressive: true, }, gifslice: { interlaced: false, }, optipng: { optimizationLevel: 7, }, pngquant: { quality: '65-90', speed: 4 } } } ] } ] }, devtool: "cheap-module-source-map", resolve: { alias:{ app : path.resolve("./app/js"), sass : path.resolve("./app/sass"), lang : path.resolve("./lang") } }, };
Fix incorrect action reference in doc block
<?php declare (strict_types = 1); namespace GrottoPress\Jentil\Setups\Scripts; use GrottoPress\Jentil\AbstractTheme; final class Script extends AbstractScript { public function __construct(AbstractTheme $jentil) { parent::__construct($jentil); $this->id = 'jentil'; } public function run() { \add_action('wp_enqueue_scripts', [$this, 'enqueue']); \add_filter('body_class', [$this, 'addBodyClasses']); } /** * @action wp_enqueue_scripts */ public function enqueue() { \wp_enqueue_script( $this->id, $this->app->utilities->fileSystem->dir( 'url', '/dist/scripts/jentil.min.js' ), ['jquery'], '', true ); } /** * Add 'no-js' class to body * * This should be removed by our script if * javascript is supported by client. * * @filter body_class */ public function addBodyClasses(array $classes): array { $classes[] = 'no-js'; return $classes; } }
<?php declare (strict_types = 1); namespace GrottoPress\Jentil\Setups\Scripts; use GrottoPress\Jentil\AbstractTheme; final class Script extends AbstractScript { public function __construct(AbstractTheme $jentil) { parent::__construct($jentil); $this->id = 'jentil'; } public function run() { \add_action('wp_enqueue_scripts', [$this, 'enqueue']); \add_filter('body_class', [$this, 'addBodyClasses']); } /** * @action wp_footer */ public function enqueue() { \wp_enqueue_script( $this->id, $this->app->utilities->fileSystem->dir( 'url', '/dist/scripts/jentil.min.js' ), ['jquery'], '', true ); } /** * Add 'no-js' class to body * * This should be removed by our script if * javascript is supported by client. * * @filter body_class */ public function addBodyClasses(array $classes): array { $classes[] = 'no-js'; return $classes; } }
Add interpolation support to the Line series component
(function(d3, fc) { 'use strict'; fc.series.line = function() { // convenience functions that return the x & y screen coords for a given point var x = function(d) { return line.xScale.value(line.xValue.value(d)); }; var y = function(d) { return line.yScale.value(line.yValue.value(d)); }; var lineData = d3.svg.line() .defined(function(d) { return !isNaN(y(d)); }) .x(x) .y(y); var line = function(selection) { selection.each(function(data) { var path = d3.select(this) .selectAll('path.line') .data([data]); path.enter() .append('path') .attr('class', 'line'); path.attr('d', lineData); line.decorate.value(path); }); }; line.decorate = fc.utilities.property(fc.utilities.fn.noop); line.xScale = fc.utilities.property(d3.time.scale()); line.yScale = fc.utilities.property(d3.scale.linear()); line.yValue = fc.utilities.property(function(d) { return d.close; }); line.xValue = fc.utilities.property(function(d) { return d.date; }); return d3.rebind(line, lineData, 'interpolate'); }; }(d3, fc));
(function(d3, fc) { 'use strict'; fc.series.line = function() { // convenience functions that return the x & y screen coords for a given point var x = function(d) { return line.xScale.value(line.xValue.value(d)); }; var y = function(d) { return line.yScale.value(line.yValue.value(d)); }; var lineData = d3.svg.line() .defined(function(d) { return !isNaN(y(d)); }) .x(x) .y(y); var line = function(selection) { selection.each(function(data) { var path = d3.select(this) .selectAll('path.line') .data([data]); path.enter() .append('path') .attr('class', 'line'); path.attr('d', lineData); line.decorate.value(path); }); }; line.decorate = fc.utilities.property(fc.utilities.fn.noop); line.xScale = fc.utilities.property(d3.time.scale()); line.yScale = fc.utilities.property(d3.scale.linear()); line.yValue = fc.utilities.property(function(d) { return d.close; }); line.xValue = fc.utilities.property(function(d) { return d.date; }); return line; }; }(d3, fc));
Throw exception when call close() on fragment
package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { throw new UnsupportedOperationException("You can not close the fragment"); } }
package com.popalay.cardme.ui.base; import android.app.Activity; import android.support.annotation.NonNull; import com.arellomobile.mvp.MvpAppCompatFragment; public abstract class BaseFragment extends MvpAppCompatFragment implements BaseView { @NonNull public BaseActivity getBaseActivity() { final Activity activity = getActivity(); if (activity != null && activity instanceof BaseActivity) { return (BaseActivity) activity; } throw new RuntimeException("BaseActivity is null"); } protected void showLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showLoadingDialog(); } protected void hideLoadingDialog() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideLoadingDialog(); } @Override public void showError(String error) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showError(error); } @Override public void showMessage(String message) { final BaseActivity baseActivity = getBaseActivity(); baseActivity.showMessage(message); } @Override public void hideError() { } @Override public void hideMessage() { } @Override public void showProgress() { showLoadingDialog(); } @Override public void hideProgress() { hideLoadingDialog(); } @Override public void hideKeyboard() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.hideKeyboard(); } @Override public void close() { final BaseActivity baseActivity = getBaseActivity(); baseActivity.close(); } }
FIx wrong key name and simplify the assignment
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, **kwargs): kwargs.setdefault('parents', []) super().__init__(**kwargs) def set_default_subparser(self, name, args=None): """ Default subparser selection. name: is the name of the subparser to call by default args: if set is the argument list handed to parse_args() """ subparser_found = False for arg in sys.argv[1:]: if arg in ['-h', '--help']: # global help if no subparser break else: for x in self._subparsers._actions: if not isinstance(x, argparse._SubParsersAction): continue for sp_name in x._name_parser_map.keys(): if sp_name in sys.argv[1:]: subparser_found = True if not subparser_found: # insert default in first position, this implies no # global options without a sub_parsers specified if args is None: sys.argv.insert(1, name) else: args.insert(0, name)
"""ArgumentParser with Italian translation.""" import argparse import sys def _callable(obj): return hasattr(obj, '__call__') or hasattr(obj, '__bases__') class ArgParser(argparse.ArgumentParser): def __init__(self, **kwargs): if kwargs.get('parent', None) is None: kwargs['parents'] = [] super().__init__(**kwargs) def set_default_subparser(self, name, args=None): """ Default subparser selection. name: is the name of the subparser to call by default args: if set is the argument list handed to parse_args() """ subparser_found = False for arg in sys.argv[1:]: if arg in ['-h', '--help']: # global help if no subparser break else: for x in self._subparsers._actions: if not isinstance(x, argparse._SubParsersAction): continue for sp_name in x._name_parser_map.keys(): if sp_name in sys.argv[1:]: subparser_found = True if not subparser_found: # insert default in first position, this implies no # global options without a sub_parsers specified if args is None: sys.argv.insert(1, name) else: args.insert(0, name)
Change form field to URLField. see #31
"""Radicale extension forms.""" from django import forms from django.utils.translation import ugettext_lazy from modoboa.lib import form_utils from modoboa.parameters import forms as param_forms class ParametersForm(param_forms.AdminParametersForm): """Global parameters.""" app = "modoboa_radicale" server_settings = form_utils.SeparatorField( label=ugettext_lazy("Server settings") ) server_location = forms.URLField( label=ugettext_lazy("Server URL"), help_text=ugettext_lazy( "The URL of your Radicale server. " "It will be used to construct calendar URLs." ), widget=forms.TextInput(attrs={"class": "form-control"}) ) rights_management_sep = form_utils.SeparatorField( label=ugettext_lazy("Rights management")) rights_file_path = forms.CharField( label=ugettext_lazy("Rights file's path"), initial="/etc/modoboa_radicale/rights", help_text=ugettext_lazy( "Path to the file that contains rights definition" ), widget=forms.TextInput(attrs={"class": "form-control"}) ) allow_calendars_administration = form_utils.YesNoField( label=ugettext_lazy("Allow calendars administration"), initial=False, help_text=ugettext_lazy( "Allow domain administrators to manage user calendars " "(read and write)" ) )
"""Radicale extension forms.""" from django import forms from django.utils.translation import ugettext_lazy from modoboa.lib import form_utils from modoboa.parameters import forms as param_forms class ParametersForm(param_forms.AdminParametersForm): """Global parameters.""" app = "modoboa_radicale" server_settings = form_utils.SeparatorField( label=ugettext_lazy("Server settings") ) server_location = forms.CharField( label=ugettext_lazy("Server URL"), help_text=ugettext_lazy( "The URL of your Radicale server. " "It will be used to construct calendar URLs." ), widget=forms.TextInput(attrs={"class": "form-control"}) ) rights_management_sep = form_utils.SeparatorField( label=ugettext_lazy("Rights management")) rights_file_path = forms.CharField( label=ugettext_lazy("Rights file's path"), initial="/etc/modoboa_radicale/rights", help_text=ugettext_lazy( "Path to the file that contains rights definition" ), widget=forms.TextInput(attrs={"class": "form-control"}) ) allow_calendars_administration = form_utils.YesNoField( label=ugettext_lazy("Allow calendars administration"), initial=False, help_text=ugettext_lazy( "Allow domain administrators to manage user calendars " "(read and write)" ) )
Enhance air pollution service formatting
import { apiConstants, apiProvidersConst, httpService, newsModelFactory } from '../../common/common.js'; export default class AirPollution { static getSummary() { let options = httpService.clone(apiConstants.airPollution); options.path = options.path.replace('{0}', options.token); return httpService.performGetRequest(options, dataTransformer); function dataTransformer(data) { return [ newsModelFactory.get({ title: 'Air pollution', info: constructInfo(data), url: null, image: null, dateTime: new Date().toDateString(), provider: apiProvidersConst.AIR_POLLUTION.id }) ]; } function constructInfo(data) { const itemSeparator = ' ', valueSeparator = '/', lineSeparator = '\r\n'; let info = ''; if (data && data.table && data.table.values) { info += 'current: ' + data.sensor.P1.current + valueSeparator + data.sensor.P2.current + lineSeparator; data.table.values.reverse().forEach((model) => { info += formatDate(new Date(model.time * 1000)) + itemSeparator + model.P1 + valueSeparator + model.P2 + lineSeparator; }); } return info; function formatDate(dateValue) { return dateValue.getDate().toString() + '-' + (dateValue.getMonth() + 1).toString(); } } } }
import { apiConstants, apiProvidersConst, httpService, newsModelFactory } from '../../common/common.js'; export default class AirPollution { static getSummary() { let options = httpService.clone(apiConstants.airPollution); options.path = options.path.replace('{0}', options.token); return httpService.performGetRequest(options, dataTransformer); function dataTransformer(data) { return [ newsModelFactory.get({ title: 'Air pollution', info: constructInfo(data), url: null, image: null, dateTime: new Date().toDateString(), provider: apiProvidersConst.AIR_POLLUTION.id }) ]; } function constructInfo(data) { const itemSeparator = ' ', lineSeparator = '\r\n'; let info = ''; if (data && data.table && data.table.values) { info += 'current: ' + data.sensor.P1.current + lineSeparator; data.table.values.reverse().forEach((model) => { info += formatDate(new Date(model.time * 1000)) + ' ' + model.P1 + lineSeparator; }); } return info; function formatDate(dateValue) { return dateValue.getDate().toString() + '-' + (dateValue.getMonth() + 1).toString(); } } } }
Fix unlink, >1 filter and lines too long
# -*- coding: utf-8 -*- # © 2016 Carlos Dauden <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice( automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge and len(inv_to_merge) > 1: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.browse(unlink_list).unlink() return res
# -*- coding: utf-8 -*- # © 2016 Carlos Dauden <[email protected]> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). from openerp import api, models class PurchaseOrderLine(models.Model): _inherit = 'account.analytic.account' @api.multi def _recurring_create_invoice(self, automatic=False): invoice_obj = self.env['account.invoice'] invoices = invoice_obj.browse( super(PurchaseOrderLine, self)._recurring_create_invoice(automatic)) res = [] unlink_list = [] for partner in invoices.mapped('partner_id'): inv_to_merge = invoices.filtered( lambda x: x.partner_id.id == partner) if partner.contract_invoice_merge: invoices_merged = inv_to_merge.do_merge() res.extend(invoices_merged) unlink_list.extend(inv_to_merge) else: res.extend(inv_to_merge) if unlink_list: invoice_obj.unlink([x.id for x in unlink_list]) return res
Remove casting from scope getter. We don’t need this, and it seemed to be causing weird issues where the Mongo arrays were being turned into strings when experimenting with the Artisan REPL.
<?php namespace Northstar\Models; use Jenssegers\Mongodb\Model; class ApiKey extends Model { /** * The database collection used by the model. * * @var string */ protected $collection = 'api_keys'; /** * The model's default attributes. * * @var array */ protected $attributes = [ 'scope' => ['user'], ]; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'app_id', 'scope', ]; /** * Create a new API key. * * @param $attributes * @return ApiKey */ public function __construct(array $attributes = []) { parent::__construct($attributes); // Automatically set random API key. This field *may* be manually // set when seeding the database, so we first check if empty. if (empty($this->api_key)) { $this->api_key = str_random(40); } } /** * Mutator for 'app_id' field. */ public function setAppIdAttribute($app_id) { $this->attributes['app_id'] = snake_case(str_replace(' ', '', $app_id)); } /** * Getter for 'scope' field. */ public function getScopeAttribute() { if (empty($this->attributes['scope'])) { return ['user']; } return $this->attributes['scope']; } }
<?php namespace Northstar\Models; use Jenssegers\Mongodb\Model; class ApiKey extends Model { /** * The database collection used by the model. * * @var string */ protected $collection = 'api_keys'; /** * The model's default attributes. * * @var array */ protected $attributes = [ 'scope' => ['user'], ]; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'app_id', 'scope', ]; /** * Create a new API key. * * @param $attributes * @return ApiKey */ public function __construct(array $attributes = []) { parent::__construct($attributes); // Automatically set random API key. This field *may* be manually // set when seeding the database, so we first check if empty. if (empty($this->api_key)) { $this->api_key = str_random(40); } } /** * Mutator for 'app_id' field. */ public function setAppIdAttribute($app_id) { $this->attributes['app_id'] = snake_case(str_replace(' ', '', $app_id)); } /** * Getter for 'scope' field. */ public function getScopeAttribute() { if (empty($this->attributes['scope'])) { return ['user']; } $scope = $this->attributes['scope']; return is_string($scope) ? json_decode($scope) : $scope; } }
Enable links in list group
var React = require('react'); var classNames = require('classnames'); var ListItem = React.createClass({ propTypes: { active: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, onClick: React.PropTypes.func }, getDefaultProps: function() { return { active: false, href: '#' }; }, onClick: function(e) { if (!this.props.onClick) { return; } e.preventDefault(); this.props.onClick(); }, render: function() { var className = classNames('list-group-item', this.props.className, { active: this.props.active }); return ( <a href={this.props.href} className={className} onClick={this.onClick}>{this.props.children}</a> ); } }); var ListGroup = React.createClass({ render: function() { return ( <ul className="list-group"> {this.props.children} </ul> ); } }); module.exports = ListGroup; module.exports.Item = ListItem;
var React = require('react'); var classNames = require('classnames'); var ListItem = React.createClass({ propTypes: { active: React.PropTypes.bool, href: React.PropTypes.string, className: React.PropTypes.string, onClick: React.PropTypes.func }, getDefaultProps: function() { return { active: false, href: '#' }; }, onClick: function(e) { if (!this.props.onClick) { return; } e.preventDefault(); this.props.onClick(); }, render: function() { var className = classNames('list-group-item', this.props.className, { active: this.props.active }); return ( <a className={className} onClick={this.onClick}>{this.props.children}</a> ); } }); var ListGroup = React.createClass({ render: function() { return ( <ul className="list-group"> {this.props.children} </ul> ); } }); module.exports = ListGroup; module.exports.Item = ListItem;
Exclude filter and xrange fixers.
from setuptools import setup, find_packages version = '3.7' setup(name='jarn.mkrelease', version=version, description='Python egg releaser', long_description=open('README.txt').read() + '\n' + open('CHANGES.txt').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], keywords='create release python egg eggs', author='Stefan H. Holek', author_email='[email protected]', url='http://pypi.python.org/pypi/jarn.mkrelease', license='BSD', packages=find_packages(), namespace_packages=['jarn'], include_package_data=True, zip_safe=False, test_suite='jarn.mkrelease.tests', install_requires=[ 'setuptools', 'setuptools-subversion', 'setuptools-hg', 'setuptools-git', 'lazy', ], entry_points={ 'console_scripts': 'mkrelease=jarn.mkrelease.mkrelease:main', }, use_2to3=True, use_2to3_exclude_fixers=[ 'lib2to3.fixes.fix_filter', 'lib2to3.fixes.fix_xrange', ], )
from setuptools import setup, find_packages version = '3.7' setup(name='jarn.mkrelease', version=version, description='Python egg releaser', long_description=open('README.txt').read() + '\n' + open('CHANGES.txt').read(), classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: MacOS :: MacOS X', 'Operating System :: POSIX', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 3', ], keywords='create release python egg eggs', author='Stefan H. Holek', author_email='[email protected]', url='http://pypi.python.org/pypi/jarn.mkrelease', license='BSD', packages=find_packages(), namespace_packages=['jarn'], include_package_data=True, zip_safe=False, use_2to3=True, test_suite='jarn.mkrelease.tests', install_requires=[ 'setuptools', 'setuptools-subversion', 'setuptools-hg', 'setuptools-git', 'lazy', ], entry_points={ 'console_scripts': 'mkrelease=jarn.mkrelease.mkrelease:main', }, )
Add param to return summarized data
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.ProgressReport', { extend: 'Ext.data.Model', fields: [ 'AuthorUsername', 'Subject', { name: 'ID', type: 'integer', useNull: true, defaultValue: null }, { name: 'Class', defaultValue: 'Slate\\Progress\\Note' }, { name: 'Type', depends: [ 'Class' ], calculate: function (data) { switch (data.Class) { case 'Slate\\Progress\\SectionInterimReport': return 'InterimReport'; case 'Slate\\Progress\\SectionTermReport': case 'NarrativeReport': return 'TermReport'; case 'Slate\\Progress\\Note': default: return 'ProgressNote'; // case 'Standards': // return 'Standard'; } } }, { name: 'Date', type: 'date', dateFormat: 'Y-m-d H:i:s' }, { name: 'StudentID', type: 'integer' }, { name: 'CourseSectionID', type: 'integer' }, { name: 'TermID', type: 'integer' } ], proxy: { type: 'slaterecords', url: '/progress', extraParams: { summarize: true } } });
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext,Slate*/ Ext.define('SlateAdmin.model.person.ProgressReport', { extend: 'Ext.data.Model', fields: [ 'AuthorUsername', 'Subject', { name: 'ID', type: 'integer', useNull: true, defaultValue: null }, { name: 'Class', defaultValue: 'Slate\\Progress\\Note' }, { name: 'Type', depends: [ 'Class' ], calculate: function (data) { switch (data.Class) { case 'Slate\\Progress\\SectionInterimReport': return 'InterimReport'; case 'Slate\\Progress\\SectionTermReport': case 'NarrativeReport': return 'TermReport'; case 'Slate\\Progress\\Note': default: return 'ProgressNote'; // case 'Standards': // return 'Standard'; } } }, { name: 'Date', type: 'date', dateFormat: 'Y-m-d H:i:s' }, { name: 'StudentID', type: 'integer' }, { name: 'CourseSectionID', type: 'integer' }, { name: 'TermID', type: 'integer' } ], proxy: { type: 'slaterecords', url: '/progress' } });
Refactor private variable declaration to constructor
'use strict'; const Animation = require('./animation'), eventBus = require('./event-bus'); const pacmanNormalColor = 0xffff00, pacmanFrighteningColor = 0xffffff, ghostFrightenedColor = 0x5555ff; class CharacterAnimations { constructor(gfx) { this._gfx = gfx; this._animations = []; this._handlePause = () => { for (let animation of this._animations) { animation.pause(); } }; this._handleResume = () => { for (let animation of this._animations) { animation.resume(); } }; } start() { eventBus.register('event.pause.begin', this._handlePause); eventBus.register('event.pause.end', this._handleResume); } stop() { eventBus.unregister('event.pause.begin', this._handlePause); eventBus.unregister('event.pause.end', this._handleResume); } createPacManAnimations() { let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor); this._animations.push(animation); return animation; } createGhostAnimations(ghostNormalColor) { let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor); this._animations.push(animation); return animation; } } module.exports = CharacterAnimations;
'use strict'; const Animation = require('./animation'), eventBus = require('./event-bus'); const pacmanNormalColor = 0xffff00, pacmanFrighteningColor = 0xffffff, ghostFrightenedColor = 0x5555ff; class CharacterAnimations { constructor(gfx) { this._gfx = gfx; this._animations = []; } start() { this._handlePause = () => { for (let animation of this._animations) { animation.pause(); } }; eventBus.register('event.pause.begin', this._handlePause); this._handleResume = () => { for (let animation of this._animations) { animation.resume(); } }; eventBus.register('event.pause.end', this._handleResume); } stop() { eventBus.unregister('event.pause.begin', this._handlePause); eventBus.unregister('event.pause.end', this._handleResume); } createPacManAnimations() { let animation = new Animation(this._gfx, pacmanNormalColor, pacmanFrighteningColor); this._animations.push(animation); return animation; } createGhostAnimations(ghostNormalColor) { let animation = new Animation(this._gfx, ghostNormalColor, ghostFrightenedColor); this._animations.push(animation); return animation; } } module.exports = CharacterAnimations;
Add missing Owner to User Seeder
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * Create one user for every role * * @return void */ public function run() { $roles = \App\Role::getAllSystemRoles(); //$this->seedOnlyOwner(); foreach ($roles as $role) { $ucfRole = ucfirst($role); $u = factory(App\User::class, $role)->create([ 'name' => $ucfRole, 'email' => $role . '@' . $role . '.dev', 'password' => bcrypt($role), ]); $u->companies()->save( factory(App\Company::class, 1)->make([ 'name' => $ucfRole . '\'s Company' // = Owner's Company ]) ); } } public function seedOnlyOwner() { $owner = factory(App\User::class, 'owner')->create([ 'name' => 'Owner', 'email' => '[email protected]', 'password' => bcrypt('pA$word'), ]); $owner->companies()->save( factory(App\Company::class, 1)->make([ 'name' => ucfirst('owner') . '\'s Company' // = Owner's Company ]) ); } }
<?php use Illuminate\Database\Seeder; use Illuminate\Database\Eloquent\Model; class UsersTableSeeder extends Seeder { /** * Run the database seeds. * * Create one user for every role * * @return void */ public function run() { $roles = \App\Role::getAllRoles(); //$this->seedOnlyOwner(); foreach ($roles as $role) { $ucfRole = ucfirst($role); $u = factory(App\User::class, $role)->create([ 'name' => $ucfRole, 'email' => $role . '@' . $role . '.dev', 'password' => bcrypt($role), ]); $u->companies()->save( factory(App\Company::class, 1)->make([ 'name' => $ucfRole . '\'s Company' // = Owner's Company ]) ); } } public function seedOnlyOwner() { $owner = factory(App\User::class, 'owner')->create([ 'name' => 'Owner', 'email' => '[email protected]', 'password' => bcrypt('pA$word'), ]); $owner->companies()->save( factory(App\Company::class, 1)->make([ 'name' => ucfirst('owner') . '\'s Company' // = Owner's Company ]) ); } }
Fix for EventManager BC breaks
<?php namespace ZfcBase\EventManager; use Traversable; use Zend\EventManager\EventManagerAwareInterface; use Zend\EventManager\EventManagerInterface; use Zend\EventManager\EventManager; abstract class EventProvider implements EventManagerAwareInterface { /** * @var EventManagerInterface */ protected $events; /** * Set the event manager instance used by this context * * @param EventManagerInterface $events * @return mixed */ public function setEventManager(EventManagerInterface $events) { $identifiers = array(__CLASS__, get_called_class()); if (isset($this->eventIdentifier)) { if ((is_string($this->eventIdentifier)) || (is_array($this->eventIdentifier)) || ($this->eventIdentifier instanceof Traversable) ) { $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier)); } elseif (is_object($this->eventIdentifier)) { $identifiers[] = $this->eventIdentifier; } // silently ignore invalid eventIdentifier types } $events->setIdentifiers($identifiers); $this->events = $events; return $this; } /** * Retrieve the event manager * * Lazy-loads an EventManager instance if none registered. * * @return EventManagerInterface */ public function getEventManager() { if (!$this->events instanceof EventManagerInterface) { $this->setEventManager(new EventManager()); } return $this->events; } }
<?php namespace ZfcBase\EventManager; use Traversable; use Zend\EventManager\EventManagerAwareInterface; use Zend\EventManager\EventManagerInterface; use Zend\EventManager\EventManager; abstract class EventProvider implements EventManagerAwareInterface { /** * @var EventManagerInterface */ protected $events; /** * Set the event manager instance used by this context * * @param EventManagerInterface $events * @return mixed */ public function setEventManager(EventManagerInterface $events) { $identifiers = array(__CLASS__, get_called_class()); if (isset($this->eventIdentifier)) { if ((is_string($this->eventIdentifier)) || (is_array($this->eventIdentifier)) || ($this->eventIdentifier instanceof Traversable) ) { $identifiers = array_unique(array_merge($identifiers, (array) $this->eventIdentifier)); } elseif (is_object($this->eventIdentifier)) { $identifiers[] = $this->eventIdentifier; } // silently ignore invalid eventIdentifier types } $events->setIdentifiers($identifiers); $this->events = $events; return $this; } /** * Retrieve the event manager * * Lazy-loads an EventManager instance if none registered. * * @return EventManagerInterface */ public function events() { if (!$this->events instanceof EventManagerInterface) { $this->setEventManager(new EventManager()); } return $this->events; } }
Move to function only tests & fix test for generator based build_file_list build_file_list is a generator now so we need to make sure it returns an iterable but not a string.
import collections import os import sys from tvrenamr.cli import helpers from .utils import random_files def test_passing_current_dir_makes_file_list_a_list(files): file_list = helpers.build_file_list([files]) assert isinstance(file_list, collections.Iterable) PY3 = sys.version_info[0] == 3 string_type = str if PY3 else basestring text_type = str if PY3 else unicode assert not isinstance(file_list, (string_type, text_type)) def test_setting_recursive_adds_all_files_below_the_folder(files): new_folders = ('herp', 'derp', 'test') os.makedirs(os.path.join(files, *new_folders)) def build_folder(folder): new_files = ('foo', 'bar', 'blah') for fn in new_files: with open(os.path.join(files, folder, fn), 'w') as f: f.write('') build_folder('herp') build_folder('herp/derp') build_folder('herp/derp/test') file_list = helpers.build_file_list([files], recursive=True) for root, dirs, files in os.walk(files): for fn in files: assert (root, fn) in file_list def test_ignoring_files(files): ignore = random_files(files) file_list = helpers.build_file_list([files], ignore_filelist=ignore) assert all(fn not in file_list for fn in ignore)
import os from tvrenamr.cli import helpers from .base import BaseTest class TestFrontEnd(BaseTest): def setup(self): super(TestFrontEnd, self).setup() self.config = helpers.get_config() def test_passing_current_dir_makes_file_list_a_list(self): assert isinstance(helpers.build_file_list([self.files]), list) def test_setting_recursive_adds_all_files_below_the_folder(self): new_folders = ('herp', 'derp', 'test') os.makedirs(os.path.join(self.files, *new_folders)) def build_folder(folder): new_files = ('foo', 'bar', 'blah') for fn in new_files: with open(os.path.join(self.files, folder, fn), 'w') as f: f.write('') build_folder('herp') build_folder('herp/derp') build_folder('herp/derp/test') file_list = helpers.build_file_list([self.files], recursive=True) for root, dirs, files in os.walk(self.files): for fn in files: assert os.path.join(root, fn) in file_list def test_ignoring_files(self): ignore = self.random_files(self.files) file_list = helpers.build_file_list([self.files], ignore_filelist=ignore) assert all(fn not in file_list for fn in ignore)
Fix license trove classifier, bump to 1.0.1
# -*- coding: utf-8 -*- """setup.py -- setup file for antimarkdown """ import os from setuptools import setup README = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst') setup( name = "antimarkdown", packages = ['antimarkdown'], install_requires = [ 'lxml', ], package_data = { '': ['*.txt', '*.html'], }, zip_safe = False, version = "1.0.1", description = "HTML to Markdown converter.", long_description = open(README).read(), author = "David Eyk", author_email = "[email protected]", url = "http://github.com/Crossway/antimarkdown/", license = 'BSD', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Filters', 'Topic :: Text Processing :: Markup :: HTML', 'Topic :: Communications :: Email :: Filters', ], )
# -*- coding: utf-8 -*- """setup.py -- setup file for antimarkdown """ import os from setuptools import setup README = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'README.rst') setup( name = "antimarkdown", packages = ['antimarkdown'], install_requires = [ 'lxml', ], package_data = { '': ['*.txt', '*.html'], }, zip_safe = False, version = "1.0.0", description = "HTML to Markdown converter.", long_description = open(README).read(), author = "David Eyk", author_email = "[email protected]", url = "http://github.com/Crossway/antimarkdown/", license = 'BSD', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content :: CGI Tools/Libraries', 'Topic :: Internet :: WWW/HTTP :: Site Management', 'Topic :: Software Development :: Documentation', 'Topic :: Software Development :: Libraries :: Python Modules', 'Topic :: Text Processing :: Filters', 'Topic :: Text Processing :: Markup :: HTML', 'Topic :: Communications :: Email :: Filters', ], )
BUILD: Tag 0.2 for correct org.
from setuptools import setup, find_packages from sys import version_info def install_requires(): requires = [ 'traitlets>=4.1', 'six>=1.9.0', 'pyyaml>=3.11', ] if (version_info.major, version_info.minor) < (3, 4): requires.append('singledispatch>=3.4.0') return requires def extras_require(): return { 'test': [ 'tox', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def main(): setup( name='straitlets', version='0.2.0', description="Serializable IPython Traitlets", author="Quantopian Team", author_email="[email protected]", packages=find_packages(include='straitlets.*'), include_package_data=True, zip_safe=True, url="https://github.com/quantopian/serializable-traitlets", classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: IPython', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', ], install_requires=install_requires(), extras_require=extras_require() ) if __name__ == '__main__': main()
from setuptools import setup, find_packages from sys import version_info def install_requires(): requires = [ 'traitlets>=4.1', 'six>=1.9.0', 'pyyaml>=3.11', ] if (version_info.major, version_info.minor) < (3, 4): requires.append('singledispatch>=3.4.0') return requires def extras_require(): return { 'test': [ 'tox', 'pytest>=2.8.5', 'pytest-cov>=1.8.1', 'pytest-pep8>=1.0.6', ], } def main(): setup( name='straitlets', version='0.1.1', description="Serializable IPython Traitlets", author="Scott Sanderson", author_email="[email protected]", packages=find_packages(include='straitlets.*'), include_package_data=True, zip_safe=True, url="https://github.com/quantopian/serializable-traitlets", classifiers=[ 'Development Status :: 3 - Alpha', 'Framework :: IPython', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python', ], install_requires=install_requires(), extras_require=extras_require() ) if __name__ == '__main__': main()
Support enums in proxying request objects
package io.github.ibuildthecloud.gdapi.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import org.apache.commons.lang3.StringUtils; public class ProxyUtils { @SuppressWarnings("unchecked") public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) { final Object obj = new Object(); return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() { @SuppressWarnings("rawtypes") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(obj, args); } if (method.getName().startsWith("get")) { String name = StringUtils.uncapitalize(method.getName().substring(3)); Object val = map.get(name); if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) { return ((Long)val).intValue(); } if (val instanceof String && method.getReturnType().isEnum()) { return Enum.valueOf((Class<? extends Enum>)method.getReturnType(), val.toString()); } return val; } if (method.getName().startsWith("set") && args.length == 1) { String name = StringUtils.uncapitalize(method.getName().substring(3)); map.put(name, args[0]); } return null; } }); } }
package io.github.ibuildthecloud.gdapi.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Map; import org.apache.commons.lang3.StringUtils; public class ProxyUtils { @SuppressWarnings("unchecked") public static <T> T proxy(final Map<String, Object> map, Class<T> typeClz) { final Object obj = new Object(); return (T)Proxy.newProxyInstance(typeClz.getClassLoader(), new Class<?>[] { typeClz }, new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getDeclaringClass() == Object.class) { return method.invoke(obj, args); } if (method.getName().startsWith("get")) { String name = StringUtils.uncapitalize(method.getName().substring(3)); Object val = map.get(name); if (val instanceof Long && (Integer.class.equals(method.getReturnType()) || Integer.TYPE.equals(method.getReturnType()))) { return ((Long)val).intValue(); } return val; } if (method.getName().startsWith("set") && args.length == 1) { String name = StringUtils.uncapitalize(method.getName().substring(3)); map.put(name, args[0]); } return null; } }); } }
Make it work in PY3.5 *properly*
import mock import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.TestCase): @classmethod def setUpClass(cls): class FakeJudge(object): pass class Handler(JudgeControlRequestHandler): judge = FakeJudge() cls.judge = Handler.judge cls.server = HTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=cls.server.serve_forever) thread.daemon = True thread.start() cls.connect = 'http://%s:%s/' % cls.server.server_address def setUp(self): self.update_mock = self.judge.update_problems = mock.Mock() def test_get_404(self): self.assertEqual(requests.get(self.connect).status_code, 404) self.assertEqual(requests.get(self.connect + 'update/problems').status_code, 404) self.update_mock.assert_not_called() def test_post_404(self): self.assertEqual(requests.post(self.connect).status_code, 404) self.update_mock.assert_not_called() def test_update_problem(self): requests.post(self.connect + 'update/problems') self.update_mock.assert_called_with() @classmethod def tearDownClass(cls): cls.server.shutdown()
import threading import unittest import requests from dmoj.control import JudgeControlRequestHandler try: from unittest import mock except ImportError: import mock try: from http.server import HTTPServer except ImportError: from BaseHTTPServer import HTTPServer class ControlServerTest(unittest.TestCase): @classmethod def setUpClass(cls): class FakeJudge(object): pass class Handler(JudgeControlRequestHandler): judge = FakeJudge() cls.judge = Handler.judge cls.server = HTTPServer(('127.0.0.1', 0), Handler) thread = threading.Thread(target=cls.server.serve_forever) thread.daemon = True thread.start() cls.connect = 'http://%s:%s/' % cls.server.server_address def setUp(self): self.update_mock = self.judge.update_problems = mock.Mock() def test_get_404(self): self.assertEqual(requests.get(self.connect).status_code, 404) self.assertEqual(requests.get(self.connect + 'update/problems').status_code, 404) self.update_mock.assert_not_called() def test_post_404(self): self.assertEqual(requests.post(self.connect).status_code, 404) self.update_mock.assert_not_called() def test_update_problem(self): requests.post(self.connect + 'update/problems') self.update_mock.assert_called_with() @classmethod def tearDownClass(cls): cls.server.shutdown()
Improve explanation and naming of variable Per @DavidRans' request.
define(['underscore'], function(_) { /** * @param spec - The spec for this column's indicators * @param prefilter - An (optional) parent IndicatorFilter which will be run * on elements before this one is. */ var constructor = function constructor(spec, prefilter) { /** * Creates indicators on the given element based on the given pull * * @param pull - The pull this is related to * @param element - The DOM element representing pull * @param template - A function which will return a new DOM node (attached to the element it is provided) every time it is called. */ this.filter = function(pull, element, template) { // Stores indicator nodes which were created by a prefilter run. var existingIndicatorNodes; // First, run any "predecessor" filters over it if (prefilter) { // Get the existing nodes this prefilter made existingIndicatorNodes = prefilter.filter(pull, element, template); } else { // There are no nodes (because there's no prefilter to make them.) // Create a new object to store the ones we're going to make. existingIndicatorNodes = {}; } // Then run the filter (if there is one) _.each(spec.indicators, function(indicator, key) { var indicatorNode; // If the (potential) prefilter run has created a node for this // indicator already, look it up if (existingIndicatorNodes[key]) { // Reuse the existing node for this indicator. indicatorNode = existingIndicatorNodes[key]; } else { // There is no existing node for this indicator. Create a new // one. indicatorNode = template(element); existingIndicatorNodes[key] = indicatorNode; } if (indicator instanceof Function) { indicator(pull, indicatorNode); } }); return existingIndicatorNodes; }; }; return constructor; });
define(['underscore'], function(_) { /** * @param spec - The spec for this column's indicators * @param prefilter - An (optional) parent IndicatorFilter which will be run * on elements before this one is. */ var constructor = function constructor(spec, prefilter) { /** * Creates indicators on the given element based on the given pull * * @param pull - The pull this is related to * @param element - The DOM element representing pull * @param template - A function which will return a new DOM node (attached to the element it is provided) every time it is called. */ this.filter = function(pull, element, template) { var existing; // First, run any "predecessor" filters over it if (prefilter) { existing = prefilter.filter(pull, element, template); } else { existing = {}; } // Then run the filter (if there is one) _.each(spec.indicators, function(indicator, key) { var indicatorNode; if (existing[key]) { indicatorNode = existing[key]; } else { indicatorNode = template(element); existing[key] = indicatorNode; } if (indicator instanceof Function) { indicator(pull, indicatorNode); } }); return existing; }; }; return constructor; });
Allow to set umask in DropPrivileges
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", umask=0o077, **kwargs): self.user = user self.group = group self.umask = umask def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) if self.umask is not None: umask(self.umask) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
from pwd import getpwnam from grp import getgrnam from traceback import format_exc from os import getuid, setgroups, setgid, setuid, umask from circuits.core import handler, BaseComponent class DropPrivileges(BaseComponent): def init(self, user="nobody", group="nobody", **kwargs): self.user = user self.group = group def drop_privileges(self): if getuid() > 0: # Running as non-root. Ignore. return try: # Get the uid/gid from the name uid = getpwnam(self.user).pw_uid gid = getgrnam(self.group).gr_gid except KeyError as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) try: # Remove group privileges setgroups([]) # Try setting the new uid/gid setgid(gid) setuid(uid) # Ensure a very conservative umask umask(0o077) except Exception as error: print("ERROR: Could not drop privileges {0:s}".format(error)) print(format_exc()) raise SystemExit(-1) @handler("ready", channel="*") def on_ready(self, server, bind): try: self.drop_privileges() finally: self.unregister()
Fix ActionHandler tests (support of Factory)
var gRex = require('../../index.js'); var Transaction = require("../../src/transaction/transaction"); var ActionHandlerFactory = require("../../src/transaction/actionhandlers/actionhandlerfactory"); var VertexActionHandler = require("../../src/transaction/actionhandlers/vertexactionhandler"); var EdgeActionHandler = require("../../src/transaction/actionhandlers/edgeactionhandler"); var ElementFactory = require("../../src/elementfactory"); var vertexHandler, edgeHandler; var edge, vertex, transaction; describe('Element ActionHandlers', function() { before(function(done){ gRex.connect() .then(function(result) { g = result; done(); }) .fail(function(error) { console.error(error); }); }); before(function() { edge = ElementFactory.build("edge"); vertex = ElementFactory.build("vertex"); transaction = g.begin(); }); describe('Vertex ActionHandler class', function() { describe('when building a vertex action handler', function() { it('should return a vertex ActionHandler', function() { vertexHandler = ActionHandlerFactory.build(vertex, transaction, []); vertexHandler.should.be.instanceof(VertexActionHandler); }); }); }); describe('Edge ActionHandler class', function() { describe('when building a vertex action handler', function() { it('should return an edge ActionHandler', function() { edgeHandler = ActionHandlerFactory.build(edge, transaction, []); edgeHandler.should.be.instanceof(EdgeActionHandler); }); }); }); });
var gRex = require('../../index.js'), Transaction = require("../../src/transaction/transaction"), handlers = require("../../src/transaction/actionhandler"), Element = require("../../src/element"); var vertexHandler, edgeHandler; var edge, vertex, transaction; describe('Element ActionHandlers', function() { before(function(done){ gRex.connect() .then(function(result) { g = result; done(); }) .fail(function(error) { console.error(error); }); }); before(function() { edge = Element.build("edge"); vertex = Element.build("vertex"); transaction = g.begin(); }); describe('Vertex ActionHandler class', function() { describe('when building a vertex action handler', function() { it('should return a vertex ActionHandler', function() { vertexHandler = handlers.ActionHandler.build(vertex, transaction, []); vertexHandler.should.be.instanceof(handlers.VertexActionHandler); }); }); }); describe('Edge ActionHandler class', function() { describe('when building a vertex action handler', function() { it('should return an edge ActionHandler', function() { edgeHandler = handlers.ActionHandler.build(edge, transaction, []); edgeHandler.should.be.instanceof(handlers.EdgeActionHandler); }); }); }); });
Add comment on mail connection
from contextlib import closing from django.core import mail from django.template.loader import render_to_string from django.conf import settings from django.contrib.auth.models import User from pyconde.sponsorship.models import JobOffer from pyconde.accounts.models import Profile from pyconde.celery import app @app.task(ignore_result=True) def send_job_offer(job_offer_id): try: offer = JobOffer.objects.select_related('sponsor').get(pk=job_offer_id) except JobOffer.DoesNotExit: raise RuntimeError('No job offer found with pk %d' % job_offer_id) profiles = Profile.objects.filter(accept_job_offers=True).select_related('user') # Re-use the connection to the server, so that a connection is not # implicitly created for every mail, as described in the docs: # https://docs.djangoproject.com/en/dev/topics/email/#sending-multiple-emails with closing(mail.get_connection()) as connection: offset = 0 while True: chunk = profiles[offset:offset+50] offset += 50 if not chunk: break body = render_to_string('sponsorship/emails/job_offer.txt', { 'offer': offer, 'site': Site.objects.get_current() }) email = mail.EmailMessage(offer.subject, body, bcc=[profile.user.email for profile in chunk], headers={'Reply-To': offer.reply_to}, connection=connection ) email.send()
from contextlib import closing from django.core import mail from django.template.loader import render_to_string from django.conf import settings from django.contrib.auth.models import User from pyconde.sponsorship.models import JobOffer from pyconde.accounts.models import Profile from pyconde.celery import app @app.task(ignore_result=True) def send_job_offer(job_offer_id): try: offer = JobOffer.objects.select_related('sponsor').get(pk=job_offer_id) except JobOffer.DoesNotExit: raise RuntimeError('No job offer found with pk %d' % job_offer_id) profiles = Profile.objects.filter(accept_job_offers=True).select_related('user') with closing(mail.get_connection()) as connection: offset = 0 while True: chunk = profiles[offset:offset+50] offset += 50 if not chunk: break body = render_to_string('sponsorship/emails/job_offer.txt', { 'offer': offer, 'site': Site.objects.get_current() }) email = mail.EmailMessage(offer.subject, body, bcc=[profile.user.email for profile in chunk], headers={'Reply-To': offer.reply_to}, connection=connection ) email.send()
Use expect.subjectOutput instead of this.subjectOutput (support removed in Unexpected 11.0.0)
/*global Uint8Array*/ var exifParser = require('exif-parser'); var fs = require('fs'); module.exports = { name: 'unexpected-exif', version: require('../package.json').version, installInto: function(expect) { expect.installPlugin(require('magicpen-media')); expect.addAssertion( '<string|Buffer> to have (exif|EXIF) data satisfying <any>', function(expect, subject, value) { var title, subjectUrl; if (typeof subject === 'string') { var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/); if (matchDataUrl) { subject = new Buffer(matchDataUrl[1], 'base64'); } else { title = subject; subjectUrl = subject; subject = fs.readFileSync(subject); } } else if (subject instanceof Uint8Array) { subject = new Buffer(subject); } expect.subjectOutput = function() { this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title }); }; var exifData = exifParser.create(subject).parse(); if (exifData && exifData.startMarker) { delete exifData.startMarker; } return expect(exifData, 'to satisfy', value); } ); } };
/*global Uint8Array*/ var exifParser = require('exif-parser'); var fs = require('fs'); module.exports = { name: 'unexpected-exif', version: require('../package.json').version, installInto: function(expect) { expect.installPlugin(require('magicpen-media')); expect.addAssertion( '<string|Buffer> to have (exif|EXIF) data satisfying <any>', function(expect, subject, value) { var title, subjectUrl; if (typeof subject === 'string') { var matchDataUrl = subject.match(/^data:[^;]*;base64,(.*)$/); if (matchDataUrl) { subject = new Buffer(matchDataUrl[1], 'base64'); } else { title = subject; subjectUrl = subject; subject = fs.readFileSync(subject); } } else if (subject instanceof Uint8Array) { subject = new Buffer(subject); } this.subjectOutput = function() { this.image(subjectUrl || subject, { width: 10, height: 5, link: true, title: title }); }; var exifData = exifParser.create(subject).parse(); if (exifData && exifData.startMarker) { delete exifData.startMarker; } return expect(exifData, 'to satisfy', value); } ); } };
Update layout of homepage buttons
@extends('layouts.app') @section('fonts') <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> @endsection @section('content') @if (Auth::check()) <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default col-xs-12 homepage-buttons" href="{{ route('incidents') }}"> <span class="glyphicon glyphicon-info-sign"> <div> Incidents </div> </span> </a> </div> <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default col-xs-12 homepage-buttons" href="{{ route('schedule') }}"> <span class="glyphicon glyphicon-calendar"> <div> Schedule </div> </span> </a> </div> <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default col-xs-12 homepage-buttons" href="{{ route('cityemail') }}"> <span class="glyphicon glyphicon-envelope"> <div> City Email </div> </span> </a> </div> @else @include('auth.login') @endif @endsection
@extends('layouts.app') @section('fonts') <link href="https://fonts.googleapis.com/css?family=Raleway:100,600" rel="stylesheet" type="text/css"> @endsection @section('content') @if (Auth::check()) <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default homepage-buttons" href="{{ route('incidents') }}"> <span class="glyphicon glyphicon-info-sign"> <div> Incidents </div> </span> </a> </div> <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default homepage-buttons" href="{{ route('schedule') }}"> <span class="glyphicon glyphicon-calendar"> <div> Schedule </div> </span> </a> </div> <div class="col-xs-12 col-sm-4 repository-margin-bottom-1rem"> <a class="btn btn-default homepage-buttons" href="{{ route('cityemail') }}"> <span class="glyphicon glyphicon-envelope"> <div> City Email </div> </span> </a> </div> @else @include('auth.login') @endif @endsection
Fix issue with react external name
'use strict'; var path = require('path'); var webpack = require('webpack'); var prod = process.env.NODE_ENV === 'production'; var config = { devtool: prod ? null : 'eval', entry: [ path.join(__dirname, 'demo', 'src', 'demo.js') ], output: { path: path.join(__dirname, 'demo', 'dist', 'js'), filename: 'demo.js', publicPath: '/demo/dist' }, externals: { 'react': { root: 'React', commonjs: 'react', commonjs2: 'react', amd: 'react' }, 'react-dom': { root: 'ReactDOM', commonjs: 'react-dom', commonjs2: 'react-dom', amd: 'react-dom' } }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, presets: ['react'] } }, { test: /\.json$/, loader: 'json' }] }, plugins: [ new webpack.NoErrorsPlugin() ] }; if (prod) { config.plugins.push(new webpack.optimize.DedupePlugin()); config.plugins.push(new webpack.optimize.OccurenceOrderPlugin(true)); config.plugins.push(new webpack.optimize.UglifyJsPlugin()); } module.exports = config;
'use strict'; var path = require('path'); var webpack = require('webpack'); var prod = process.env.NODE_ENV === 'production'; var config = { devtool: prod ? null : 'eval', entry: [ path.join(__dirname, 'demo', 'src', 'demo.js') ], output: { path: path.join(__dirname, 'demo', 'dist', 'js'), filename: 'demo.js', publicPath: '/demo/dist' }, externals: { 'react': 'React', 'react-dom': 'ReactDOM' }, module: { loaders: [{ test: /\.js$/, loader: 'babel', exclude: /node_modules/, query: { cacheDirectory: true, presets: ['react'] } }, { test: /\.json$/, loader: 'json' }] }, plugins: [ new webpack.NoErrorsPlugin() ] }; if (prod) { config.plugins.push(new webpack.optimize.DedupePlugin()); config.plugins.push(new webpack.optimize.OccurenceOrderPlugin(true)); config.plugins.push(new webpack.optimize.UglifyJsPlugin()); } module.exports = config;
Update admin area queries to use new `filter` parameter refs #6005 - updates use of the query params removed in #6005 to use new `filter` param
import Ember from 'ember'; export default Ember.Controller.extend({ notifications: Ember.inject.service(), userPostCount: Ember.computed('model.id', function () { var promise, query = { filter: `author:${this.get('model.slug')}`, status: 'all' }; promise = this.store.query('post', query).then(function (results) { return results.meta.pagination.total; }); return Ember.Object.extend(Ember.PromiseProxyMixin, { count: Ember.computed.alias('content'), inflection: Ember.computed('count', function () { return this.get('count') > 1 ? 'posts' : 'post'; }) }).create({promise: promise}); }), actions: { confirmAccept: function () { var self = this, user = this.get('model'); user.destroyRecord().then(function () { self.get('notifications').closeAlerts('user.delete'); self.store.unloadAll('post'); self.transitionToRoute('team'); }, function () { self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'}); }); }, confirmReject: function () { return false; } }, confirm: { accept: { text: 'Delete User', buttonClass: 'btn btn-red' }, reject: { text: 'Cancel', buttonClass: 'btn btn-default btn-minor' } } });
import Ember from 'ember'; export default Ember.Controller.extend({ notifications: Ember.inject.service(), userPostCount: Ember.computed('model.id', function () { var promise, query = { author: this.get('model.slug'), status: 'all' }; promise = this.store.query('post', query).then(function (results) { return results.meta.pagination.total; }); return Ember.Object.extend(Ember.PromiseProxyMixin, { count: Ember.computed.alias('content'), inflection: Ember.computed('count', function () { return this.get('count') > 1 ? 'posts' : 'post'; }) }).create({promise: promise}); }), actions: { confirmAccept: function () { var self = this, user = this.get('model'); user.destroyRecord().then(function () { self.get('notifications').closeAlerts('user.delete'); self.store.unloadAll('post'); self.transitionToRoute('team'); }, function () { self.get('notifications').showAlert('The user could not be deleted. Please try again.', {type: 'error', key: 'user.delete.failed'}); }); }, confirmReject: function () { return false; } }, confirm: { accept: { text: 'Delete User', buttonClass: 'btn btn-red' }, reject: { text: 'Cancel', buttonClass: 'btn btn-default btn-minor' } } });
Add support for app passwords
const alfy = require('alfy'); const bitbucket = require('./bitbucket/core').bitbucket; const {clientId, secret, appPassword, username} = process.env; const ACCESS_TOKEN = 'access_token'; const GRANT_TYPE = 'client_credentials'; const ALIVE_TIME = 216000; const URL = 'https://bitbucket.org/site/oauth2/access_token'; const OPTIONS = { auth: [clientId, secret].join(':'), json: true, method: 'POST', body: { grant_type: GRANT_TYPE }, form: true }; const loginAttempt = () => { return new Promise((resolve, _reject) => { if ((!username || !appPassword) && (!clientId || !secret)) { return alfy.error('OAuth2 not set. Refer to README for details'); } if (username && appPassword) { return resolve(bitbucket(`Basic ${Buffer.from([username, appPassword].join(':')).toString('base64')}`)); } const accessToken = alfy.cache.get(ACCESS_TOKEN); if (accessToken) { return resolve(bitbucket(accessToken)); } alfy.fetch(URL, OPTIONS) .then(({access_token}) => { const authToken = `Bearer ${access_token}`; alfy.cache.set(ACCESS_TOKEN, authToken, { maxAge: ALIVE_TIME }); resolve(bitbucket(authToken)); }) .catch(() => alfy.cache.set(ACCESS_TOKEN, null)); }); }; module.exports = loginAttempt;
const alfy = require('alfy'); const bitbucket = require('./bitbucket/core').bitbucket; const { clientId, secret } = process.env; const ACCESS_TOKEN = 'access_token'; const GRANT_TYPE = 'client_credentials'; const ALIVE_TIME = 216000; const URL = 'https://bitbucket.org/site/oauth2/access_token'; const OPTIONS = { auth: [clientId, secret].join(':'), json: true, method: 'POST', body: { grant_type: GRANT_TYPE }, form: true }; const loginAttempt = () => { return new Promise((resolve, _reject) => { if (!clientId || !secret) { alfy.error('OAuth2 not set. Refer to README for details'); } else { const accessToken = alfy.cache.get(ACCESS_TOKEN); if (accessToken) { resolve(bitbucket(accessToken)); } else { alfy.fetch(URL, OPTIONS).then(({ access_token }) => { alfy.cache.set(ACCESS_TOKEN, access_token, { maxAge: ALIVE_TIME }); resolve(bitbucket(access_token)); }).catch(() => { alfy.cache.set(ACCESS_TOKEN, null); }); } } }); }; module.exports = loginAttempt;