text
stringlengths
17
1.47k
positive
stringlengths
673
4.43k
negative
stringlengths
677
2.81k
Rebase off develop, add missing parenthesis
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()]))
from django.test import TestCase from django.core.urlresolvers import reverse from whats_fresh_api.models import * from django.contrib.gis.db import models import json class ListProductTestCase(TestCase): fixtures = ['test_fixtures'] def test_url_endpoint(self): url = reverse('entry-list-products') self.assertEqual(url, '/entry/products') def test_list_items(self): """ Tests to see if the list of products contains the proper productss and proper product data """ response = self.client.get(reverse('entry-list-products')) items = response.context['item_list'] for product in Product.objects.all(): self.assertEqual( items[product.id-1]['description'], product.description) self.assertEqual( items[product.id-1]['name'], product.name) self.assertEqual( items[product.id-1]['link'], reverse('edit-product', kwargs={'id': product.id})) self.assertEqual( items[product.id-1]['modified'], product.modified.strftime("%I:%M %P, %d %b %Y")) self.assertEqual( sort(items[product.id-1]['preparations']), sort([prep.name for prep in product.preparations.all()])
Disable gray for foreground on BW devices
module.exports = [ { "type": "heading", "defaultValue": "Preferences" , "size": 3 }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "Colors" }, { "type": "text", "defaultValue": "Only available on compatible platforms." }, { "type": "color", "allowGray": true, "label": "Background", "messageKey": "BACKGROUND_COLOR", "defaultValue": "000000" }, { "type": "color", "allowGray": false, "label": "Foreground", "messageKey": "TIME_COLOR", "defaultValue": "FFFFFF" } ] }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "Features" }, { "type": "toggle", "label": "Vibrate on Bluetooth disconnect", "messageKey": "VIBRATE_ON_DISCONNECT", "defaultValue": false }, { "type": "text", "defaultValue": "Will NOT vibrate during Quiet Time or if health monitoring detects sleeping." } ] }, { "type": "submit", "defaultValue": "Save" } ];
module.exports = [ { "type": "heading", "defaultValue": "Preferences" , "size": 3 }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "Colors" }, { "type": "text", "defaultValue": "Only available on compatible platforms." }, { "type": "color", "allowGray": true, "label": "Background", "messageKey": "BACKGROUND_COLOR", "defaultValue": "000000" }, { "type": "color", "allowGray": true, "label": "Foreground", "messageKey": "TIME_COLOR", "defaultValue": "FFFFFF" } ] }, { "type": "section", "items": [ { "type": "heading", "defaultValue": "Features" }, { "type": "toggle", "label": "Vibrate on Bluetooth disconnect", "messageKey": "VIBRATE_ON_DISCONNECT", "defaultValue": false }, { "type": "text", "defaultValue": "Will NOT vibrate during Quiet Time or if health monitoring detects sleeping." } ] }, { "type": "submit", "defaultValue": "Save" } ];
Update links to external resources on homepage
@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="row text-center"> <div class=" col-xs-12 col-sm-3 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-3 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-3 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> </div><!-- .row --> @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="row text-center"> <div class=" col-xs-12 col-sm-3 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-3 repository-margin-bottom-1rem"> <a class="btn btn-default homepage-buttons"> <span class="glyphicon glyphicon-calendar"> <div> Schedule </div> </span> </a> </div> <div class=" col-xs-12 col-sm-3 repository-margin-bottom-1rem"> <a class="btn btn-default homepage-buttons"> <span class="glyphicon glyphicon-envelope"> <div> City Email </div> </span> </a> </div> </div><!-- .row --> @else @include('auth.login'); @endif @endsection
BAP-10985: Update the rules displaying autocomplete result for business unit owner field
<?php namespace Oro\Bundle\OrganizationBundle\Autocomplete; use Doctrine\Bundle\DoctrineBundle\Registry; use Oro\Bundle\FormBundle\Autocomplete\SearchHandler; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; class BusinessUnitOwnerSearchHandler extends SearchHandler { /** @var Registry */ protected $doctrine; public function __construct($entityName, array $properties, Registry $doctrine) { parent::__construct($entityName, $properties); $this->doctrine = $doctrine; } /** * {@inheritdoc} */ public function convertItem($item) { $result = parent::convertItem($item); $businessUnit = $this->doctrine->getManager()->getRepository('OroOrganizationBundle:BusinessUnit') ->find($result[$this->idFieldName]); $result['treePath'] = $this->getPath($businessUnit, []); $result['organization_id'] = $businessUnit->getOrganization()->getId(); return $result; } /** * @param BusinessUnit $businessUnit * @param $path * * @return mixed */ protected function getPath($businessUnit, $path) { array_unshift($path, ['name'=> $businessUnit->getName()]); $owner = $businessUnit->getOwner(); if ($owner) { $path = $this->getPath($owner, $path); } return $path; } }
<?php namespace Oro\Bundle\OrganizationBundle\Autocomplete; use Doctrine\Bundle\DoctrineBundle\Registry; use Oro\Bundle\FormBundle\Autocomplete\SearchHandler; use Oro\Bundle\OrganizationBundle\Entity\BusinessUnit; class BusinessUnitOwnerSearchHandler extends SearchHandler { /** @var Registry */ protected $doctrine; public function __construct($entityName, array $properties, Registry $doctrine) { parent::__construct($entityName, $properties); $this->doctrine = $doctrine; } /** * {@inheritdoc} */ public function convertItem($item) { $result = parent::convertItem($item); $businessUnit = $this->doctrine->getManager()->getRepository('OroOrganizationBundle:BusinessUnit') ->find($result[$this->idFieldName]); $result['treePath'] = $this->getPath($businessUnit, []); $result['organization_id'] = $businessUnit->getOrganization()->getId(); return $result; } /** * @param BusinessUnit $businessUnit * @param $path * * @return mixed */ protected function getPath($businessUnit, $path) { array_unshift($path, ['name'=> $businessUnit->getName()]); $owner = $businessUnit->getOwner(); if ($owner) { $path = $this->getPath($owner, $path); } return $path; } }
Fix exiftool error on incorrect images
<?php namespace YF\Provider; class Exiftool { public function __construct() { $bin = ''; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $bin = dirname(__FILE__).'/'; } $this->exe = $bin.'exiftool'; } /** * Retreive the metadata of the file * @return The metadata of the file */ public function getData(string $path): array { $key = basename($path); if (!JsonManager::getInstance()->exists($key)) { $data = json_decode(shell_exec("$this->exe $path -json -g"), true)[0]; if (is_null($data)) { $data = []; } unset($data['Preview']); unset($data['ExifTool']); unset($data['File']); JsonManager::getInstance()->set( $key, $data ); } return JsonManager::getInstance()->get($key); } /** * Retreive the content of the XMP Sidecar file * @return The content of the XMP Sidecar file */ public function getXMPSidecarContent(string $path) { return shell_exec("$this->exe -xmp -b $path"); } }
<?php namespace YF\Provider; class Exiftool { public function __construct() { $bin = ''; if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') { $bin = dirname(__FILE__).'/'; } $this->exe = $bin.'exiftool'; } /** * Retreive the metadata of the file * @return The metadata of the file */ public function getData(string $path): array { $key = basename($path); if (!JsonManager::getInstance()->exists($key)) { $data = json_decode(shell_exec("$this->exe $path -json -g"), true)[0]; unset($data['Preview']); unset($data['ExifTool']); unset($data['File']); JsonManager::getInstance()->set( $key, $data ); } return JsonManager::getInstance()->get($key); } /** * Retreive the content of the XMP Sidecar file * @return The content of the XMP Sidecar file */ public function getXMPSidecarContent(string $path) { return shell_exec("$this->exe -xmp -b $path"); } }
Change time and distance getter return types to be nullable
<?php class ViewData { /** * @var int $time */ private $time; /** * @var float $distance */ private $distance; const SPEED_PRECISION = 2; public function __construct() { $this->time = $_POST['time']; $this->distance = $_POST['distance']; } /** * @return int */ public function getTime(): ?int { return $this->time; } /** * @return float */ public function getDistance(): ?float { return $this->distance; } /** * @return bool */ public function hasSentData(): bool { return isset($this->time) && isset($this->distance); } /** * @return string */ public function getAveragePace(): string { return $this->decimalToMinuteString($this->time / $this->distance); } /** * @return string */ public function getAverageSpeed(): string { return round($this->distance / ($this->time / 60), self::SPEED_PRECISION); } /** * @param float $timeAsDecimal * @return string */ private function decimalToMinuteString(float $timeAsDecimal): string { $whole = floor($timeAsDecimal); $decimal = $timeAsDecimal - $whole; $roundedMinutes = round($decimal * 60, 0); $minutes = str_pad($roundedMinutes, 2, "0", STR_PAD_LEFT); return "{$whole}:{$minutes}"; } }
<?php class ViewData { /** * @var int $time */ private $time; /** * @var float $distance */ private $distance; const SPEED_PRECISION = 2; public function __construct() { $this->time = $_POST['time']; $this->distance = $_POST['distance']; } /** * @return int */ public function getTime(): int { return $this->time; } /** * @return float */ public function getDistance(): float { return $this->distance; } /** * @return bool */ public function hasSentData(): bool { return isset($this->time) && isset($this->distance); } /** * @return string */ public function getAveragePace(): string { return $this->decimalToMinuteString($this->time / $this->distance); } /** * @return string */ public function getAverageSpeed(): string { return round($this->distance / ($this->time / 60), self::SPEED_PRECISION); } /** * @param float $timeAsDecimal * @return string */ private function decimalToMinuteString(float $timeAsDecimal): string { $whole = floor($timeAsDecimal); $decimal = $timeAsDecimal - $whole; $roundedMinutes = round($decimal * 60, 0); $minutes = str_pad($roundedMinutes, 2, "0", STR_PAD_LEFT); return "{$whole}:{$minutes}"; } }
Use BrowserRouter rather than HashRouter
import React, { Component, PropTypes } from 'react'; import { combineReducers } from 'redux'; import { Provider } from 'react-redux'; import { Grid, Row, Col } from 'react-bootstrap'; import Router from 'react-router/BrowserRouter'; import Match from 'react-router/Match'; import { Front } from './Front'; import { Menu } from './Menu'; import MainContainer from './components/MainContainer'; import MainNav from './components/MainNav'; import ModuleContainer from './components/ModuleContainer'; import moduleRoutes from './moduleRoutes'; import initialReducers from './initialReducers'; const reducers = { ...initialReducers }; export default class Root extends Component { getChildContext() { return { addReducer: this.addReducer.bind(this) }; } addReducer = (key, reducer) => { if (reducers[key] === undefined) { reducers[key] = reducer; this.props.store.replaceReducer(combineReducers({ ...reducers })); return true; } return false; } render() { const { store } = this.props; return ( <Provider store={store}><Router> <MainContainer> <MainNav /> <ModuleContainer id="content"> <Match pattern="/" exactly component={Front} key="root" /> {moduleRoutes} </ModuleContainer> </MainContainer> </Router></Provider> ); } } Root.childContextTypes = { addReducer: PropTypes.func, }; Root.propTypes = { store: PropTypes.object.isRequired, };
import React, { Component, PropTypes } from 'react'; import { combineReducers } from 'redux'; import { Provider } from 'react-redux'; import { Grid, Row, Col } from 'react-bootstrap'; import Router from 'react-router/HashRouter'; import Match from 'react-router/Match'; import { Front } from './Front'; import { Menu } from './Menu'; import MainContainer from './components/MainContainer'; import MainNav from './components/MainNav'; import ModuleContainer from './components/ModuleContainer'; import moduleRoutes from './moduleRoutes'; import initialReducers from './initialReducers'; const reducers = { ...initialReducers }; export default class Root extends Component { getChildContext() { return { addReducer: this.addReducer.bind(this) }; } addReducer = (key, reducer) => { if (reducers[key] === undefined) { reducers[key] = reducer; this.props.store.replaceReducer(combineReducers({ ...reducers })); return true; } return false; } render() { const { store } = this.props; return ( <Provider store={store}><Router> <MainContainer> <MainNav /> <ModuleContainer id="content"> <Match pattern="/" exactly component={Front} key="root" /> {moduleRoutes} </ModuleContainer> </MainContainer> </Router></Provider> ); } } Root.childContextTypes = { addReducer: PropTypes.func, }; Root.propTypes = { store: PropTypes.object.isRequired, };
Fix uptime and uptime timing
import discord from modules.botModule import BotModule from modules.help import * import time import datetime class Status(BotModule): name = 'status' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!status` shows information about this instance of scubot.' trigger_string = '!status' init_time = time.time() def __init__(self): init_time = time.time() def uptime_convert(self,seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) return days, hours, minutes, seconds async def parse_command(self, message, client): uptime = time.time() - self.init_time uptime_string = self.uptime_convert(uptime) uptime_string = [str(round(x,0))[:-2] for x in uptime_string] uptime_string = uptime_string[0] + 'd ' + uptime_string[1] + 'h ' + uptime_string[2] + 'm ' + uptime_string[3] + 's' module_string = '' for botModule in self.loaded_modules: module_string += botModule.name + ', ' module_string = module_string[:-2] msg = '```\n Uptime: ' + uptime_string + '\n Loaded modules: ' + module_string + '\n```' await client.send_message(message.channel, msg)
import discord from modules.botModule import BotModule from modules.help import * import time import datetime class Status(BotModule): name = 'status' description = 'Allow for the assignment and removal of roles.' help_text = 'Usage: `!status` shows information about this instance of scubot.' trigger_string = '!status' init_time = 0 def __init__(self): init_time = time.time() def uptime_convert(self,seconds): minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) days, hours = divmod(hours, 24) return days, hours, minutes, seconds async def parse_command(self, message, client): uptime = self.init_time - time.time() uptime_string = self.uptime_convert(uptime) uptime_string = [str(round(x,0))[:-2] for x in uptime_string] uptime_string = uptime_string[0] + 'd ' + uptime_string[1] + 'h ' + uptime_string[2] + 'm ' + uptime_string[3] + 's' print(self.loaded_modules) module_string = '' for botModule in self.loaded_modules: module_string += botModule.name + ', ' module_string = module_string[:-2] msg = '```\n Uptime: ' + uptime_string + '\n Loaded modules: ' + module_string + '\n```' await client.send_message(message.channel, msg)
Fix BuzzAPI response format for bad GTID
<?php declare(strict_types=1); // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter // phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class BuzzApiMockController extends Controller { public function anything(Request $request, string $resource, string $action): JsonResponse { $gtid = $request->input('gtid'); $results = []; if ('903000000' === $gtid) { $results[] = [ 'eduPersonPrimaryAffiliation' => 'student', 'givenName' => 'George', 'gtAccountEntitlement' => [], 'gtGTID' => '903000000', 'gtPersonDirectoryId' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345', 'gtPrimaryGTAccountUsername' => 'gburdell3', 'mail' => '[email protected]', 'sn' => 'Burdell', 'uid' => 'gburdell3', ]; } return response()->json([ 'api_result_data' => $results, 'api_buzzapi_logs' => [ 'This response was generated from a mock endpoint for demonstration purposes', ], 'api_provider_logs' => [], ]); } }
<?php declare(strict_types=1); // phpcs:disable Generic.CodeAnalysis.UnusedFunctionParameter // phpcs:disable SlevomatCodingStandard.Functions.UnusedParameter namespace App\Http\Controllers; use Illuminate\Http\JsonResponse; use Illuminate\Http\Request; class BuzzApiMockController extends Controller { public function anything(Request $request, string $resource, string $action): JsonResponse { $gtid = $request->input('gtid'); $results = []; if ('903000000' === $gtid) { $results[] = [ 'eduPersonPrimaryAffiliation' => 'student', 'givenName' => 'George', 'gtAccountEntitlement' => [], 'gtGTID' => '903000000', 'gtPersonDirectoryId' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZ012345', 'gtPrimaryGTAccountUsername' => 'gburdell3', 'mail' => '[email protected]', 'sn' => 'Burdell', 'uid' => 'gburdell3', ]; } return response()->json([ 'api_result_data' => [ $results, ], 'api_buzzapi_logs' => [ 'This response was generated from a mock endpoint for demonstration purposes', ], 'api_provider_logs' => [], ]); } }
Order keys consistently for enhanced readability
import Ember from 'ember'; const { Controller, inject, computed, getOwner } = Ember; export default Controller.extend({ token: inject.service(), secret: computed.reads('token.secret'), tokenIsValid: false, tokenIsInvalid: false, tokenRecord: null, actions: { clearTokenProperties() { this.get('token').setProperties({ secret: undefined, accessor: undefined, }); this.setProperties({ tokenIsValid: false, tokenIsInvalid: false, tokenRecord: null, }); }, verifyToken() { const { secret } = this.getProperties('secret', 'accessor'); const TokenAdapter = getOwner(this).lookup('adapter:token'); this.set('token.secret', secret); TokenAdapter.findSelf().then( token => { this.setProperties({ tokenIsValid: true, tokenIsInvalid: false, tokenRecord: token, }); }, () => { this.set('token.secret', null); this.setProperties({ tokenIsValid: false, tokenIsInvalid: true, tokenRecord: null, }); } ); }, }, });
import Ember from 'ember'; const { Controller, inject, computed, getOwner } = Ember; export default Controller.extend({ token: inject.service(), tokenRecord: null, secret: computed.reads('token.secret'), tokenIsValid: false, tokenIsInvalid: false, actions: { clearTokenProperties() { this.get('token').setProperties({ secret: undefined, accessor: undefined, }); this.setProperties({ tokenIsValid: false, tokenIsInvalid: false, tokenRecord: null, }); }, verifyToken() { const { secret } = this.getProperties('secret', 'accessor'); const TokenAdapter = getOwner(this).lookup('adapter:token'); this.set('token.secret', secret); TokenAdapter.findSelf().then( token => { this.setProperties({ tokenIsValid: true, tokenIsInvalid: false, tokenRecord: token, }); }, () => { this.set('token.secret', null); this.setProperties({ tokenIsInvalid: true, tokenIsValid: false, tokenRecord: null, }); } ); }, }, });
Increase font size on scoreboard point labels Makes it much easier to read from further away Signed-off-by: Tyler Butters <[email protected]>
$(function () { var hc_scoreboard_series = { name: 'Points', id: ':scores', data: [], dataLabels: { enabled: true, color: '#FFFFFF', align: 'center', y: 25, // 25 pixels down from the top style: { fontSize: '3.2vw' } } }; // Get initial chart data, set up columns for teams $.get( '/team/scores' ) .done(function(data) { $.each(data, function(index, result) { hc_scoreboard_series.data.push([ result.teamname, result.points ]); }); $('#hc_scoreboard').highcharts({ chart: { type: 'column' }, title: { text: 'Team Scores' }, subtitle: { text: '(Updates automatically)' }, xAxis: { type: 'category', labels: { rotation: -45, }, crosshair: false }, yAxis: { min: 0, title: { text: 'Points' } }, legend: { enabled: false }, plotOptions: { column: { pointPadding: 0, groupPadding: 0.1, borderWidth: 0, colorByPoint: true, shadow: true } }, series: [hc_scoreboard_series] }); }); });
$(function () { var hc_scoreboard_series = { name: 'Points', id: ':scores', data: [], dataLabels: { enabled: true, color: '#FFFFFF', align: 'center', y: 10, // 10 pixels down from the top } }; // Get initial chart data, set up columns for teams $.get( '/team/scores' ) .done(function(data) { $.each(data, function(index, result) { hc_scoreboard_series.data.push([ result.teamname, result.points ]); }); $('#hc_scoreboard').highcharts({ chart: { type: 'column' }, title: { text: 'Team Scores' }, subtitle: { text: '(Updates automatically)' }, xAxis: { type: 'category', labels: { rotation: -45, }, crosshair: false }, yAxis: { min: 0, title: { text: 'Points' } }, legend: { enabled: false }, plotOptions: { column: { pointPadding: 0, groupPadding: 0.1, borderWidth: 0, colorByPoint: true, shadow: true } }, series: [hc_scoreboard_series] }); }); });
Extend middleware to accept array.
module.exports = function actionListenerMiddleware (listeners) { listeners = Array.isArray(listeners) ? listeners : Array.prototype.slice.call(arguments); var actionListeners = listeners.reduce((result, listener) => { Object.keys(listener).forEach(type => { var typeListeners = Array.isArray(listener[type]) ? listener[type] : [listener[type]]; result[type] = (result[type] || []).concat(typeListeners); }); return result; }, {}); return function(store) { return function(next) { return function(action) { next(action); if (typeof action === 'object') { (actionListeners[action.type] || []).forEach(function(listener) { listener(action, store); }); } }; }; }; } // ES6 // // export function actionListenerMiddleware (...listeners) { // // const actionListeners = listeners.reduce((result, listener) => { // Object.keys(listener).forEach(type => { // const typeListeners = Array.isArray(listener[type]) // ? listener[type] // : [listener[type]]; // result[type] = (result[type] || []).concat(typeListeners); // }); // return result; // }, {}); // // return store => next => action => { // next(action); // if (typeof action === 'object') { // (actionListeners[action.type] || []).forEach(listener => listener(action, store)); // } // }; // }
module.exports = function actionListenerMiddleware () { var listeners = Array.prototype.slice.call(arguments); var actionListeners = listeners.reduce((result, listener) => { Object.keys(listener).forEach(type => { var typeListeners = Array.isArray(listener[type]) ? listener[type] : [listener[type]]; result[type] = (result[type] || []).concat(typeListeners); }); return result; }, {}); return function(store) { return function(next) { return function(action) { next(action); if (typeof action === 'object') { (actionListeners[action.type] || []).forEach(function(listener) { listener(action, store); }); } }; }; }; } // ES6 // // export function actionListenerMiddleware (...listeners) { // // const actionListeners = listeners.reduce((result, listener) => { // Object.keys(listener).forEach(type => { // const typeListeners = Array.isArray(listener[type]) // ? listener[type] // : [listener[type]]; // result[type] = (result[type] || []).concat(typeListeners); // }); // return result; // }, {}); // // return store => next => action => { // next(action); // if (typeof action === 'object') { // (actionListeners[action.type] || []).forEach(listener => listener(action, store)); // } // }; // }
Adjust init verbose and enabled mode handling Reduce complexity and leave the enabled mode to be used with the toggleable decorator that disables functionality when AXES_ENABLED is set to False for testing etc. This conforms with the previous behaviour and logic flow.
from logging import getLogger from pkg_resources import get_distribution from django import apps log = getLogger(__name__) class AppConfig(apps.AppConfig): name = "axes" initialized = False @classmethod def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.initialized: return cls.initialized = True # Only import settings, checks, and signals one time after Django has been initialized from axes.conf import settings from axes import checks, signals # noqa # Skip startup log messages if Axes is not set to verbose if settings.AXES_VERBOSE: log.info("AXES: BEGIN LOG") log.info( "AXES: Using django-axes version %s", get_distribution("django-axes").version, ) if settings.AXES_ONLY_USER_FAILURES: log.info("AXES: blocking by username only.") elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info("AXES: blocking by combination of username and IP.") elif settings.AXES_LOCK_OUT_BY_USER_OR_IP: log.info("AXES: blocking by username or IP.") else: log.info("AXES: blocking by IP only.") def ready(self): self.initialize()
from logging import getLogger from pkg_resources import get_distribution from django import apps log = getLogger(__name__) class AppConfig(apps.AppConfig): name = "axes" initialized = False @classmethod def initialize(cls): """ Initialize Axes logging and show version information. This method is re-entrant and can be called multiple times. It displays version information exactly once at application startup. """ if cls.initialized: return cls.initialized = True # Only import settings, checks, and signals one time after Django has been initialized from axes.conf import settings from axes import checks, signals # noqa # Skip startup log messages if Axes is not enabled or not set to verbose if not settings.AXES_ENABLED: return if not settings.AXES_VERBOSE: return log.info("AXES: BEGIN LOG") log.info( "AXES: Using django-axes version %s", get_distribution("django-axes").version, ) if settings.AXES_ONLY_USER_FAILURES: log.info("AXES: blocking by username only.") elif settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP: log.info("AXES: blocking by combination of username and IP.") elif settings.AXES_LOCK_OUT_BY_USER_OR_IP: log.info("AXES: blocking by username or IP.") else: log.info("AXES: blocking by IP only.") def ready(self): self.initialize()
Update to new v1 endpoint We're moving to a versioned API endpoint. Thanks!
include("shared/request.js"); include("shared/notify.js"); include("shared/cache.js"); var API_URL = "https://api.domainr.com/v1/search"; function runWithString(string) { try { if (LaunchBar.options.commandKey) { LaunchBar.openURL( "https://domainr.com/"+encodeURIComponent(string) ); } string = string.trim(); if (string.length === 0) return; var data = Lib.Cache.get(string, true); if (!data) { data = api_call(string).map(function(item) { return { title: item.domain, url: item.register_url, icon: item.availability, actionArgument: item.domain }; }); Lib.Cache.set(string, data, 20); } return data; } catch (err) { Lib.Notify.error(err); } } function api_call(term) { var resp = Lib.Request.getJSON(API_URL, {client_id: "lb6_action", q: encodeURIComponent(term)}); if (resp.error !== undefined) throw "Domainr error ("+resp.error.status+"): "+resp.error.message; return resp.results; }
include("shared/request.js"); include("shared/notify.js"); include("shared/cache.js"); var API_URL = "https://domainr.com/api/json/search"; function runWithString(string) { try { if (LaunchBar.options.commandKey) { LaunchBar.openURL( "https://domainr.com/"+encodeURIComponent(string) ); } string = string.trim(); if (string.length === 0) return; var data = Lib.Cache.get(string, true); if (!data) { data = api_call(string).map(function(item) { return { title: item.domain, url: item.register_url, icon: item.availability, actionArgument: item.domain }; }); Lib.Cache.set(string, data, 20); } return data; } catch (err) { Lib.Notify.error(err); } } function api_call(term) { var resp = Lib.Request.getJSON(API_URL, {client_id: "lb6_action", q: encodeURIComponent(term)}); if (resp.error !== undefined) throw "Domainr error ("+resp.error.status+"): "+resp.error.message; return resp.results; }
Fix input submit, now clear itself after submit
(function (angular){ 'use strict'; angular.module('app') .controller('counterController', counterController) .controller('todoController', todoController) counterController.$inject = [] todoController.$inject = [] function counterController(){ this.counter = 0; this.add = function() { this.counter >= 10 ? this.counter : this.counter ++; } this.sub = function(){ this.counter === 0 ? this.counter : this.counter --; } }; function todoController(){ this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}]; this.newTask = ''; this.completed = 1; this.total = this.tasks.length; this.showCompleted = true this.add = function(){ console.log(this.newTask) this.tasks.push({name: this.newTask, complete: false}); this.newTask = '' this.total = this.tasks.length; }.bind(this) this.complete = function(taskIndex){ console.log(taskIndex); this.tasks[taskIndex].complete = true; this.completed = this.tasks.reduce(function(p, n){ return n.complete === true ? p + 1 : p; }, 0); } this.hideCompleted= function(){ showCompleted = false }; } })(window.angular);
(function (angular){ 'use strict'; angular.module('app') .controller('counterController', counterController) .controller('todoController', todoController) counterController.$inject = [] todoController.$inject = [] function counterController(){ this.counter = 0; this.add = function() { this.counter >= 10 ? this.counter : this.counter ++; } this.sub = function(){ this.counter === 0 ? this.counter : this.counter --; } }; function todoController(){ this.tasks = [{name: "Brush Your Teeth", complete: true}, {name: "Tie Shoes", complete: false}]; this.newTask = ''; this.completed = 1; this.total = this.tasks.length; this.add = function(){ console.log(this.newTask) this.tasks.push({name: this.newTask, complete: false}); this.total = this.tasks.length; }.bind(this) this.complete = function(taskIndex){ console.log(taskIndex); this.tasks[taskIndex].complete = true; this. this.completed = this.tasks.reduce(function(p, n){ return n.complete === true ? p + 1 : p; }, 0); this.removeCompleted= function(){ }; } } })(window.angular);
Use os.remove instead of os.unlink It's easier to understand
from nazs.core import module from nazs.core.commands import run from nazs.core.sudo import root from django.utils.translation import ugettext as _ import os import logging logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ with root(): if os.path.exists(self.ETC_FILE): os.remove(self.ETC_FILE) run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'") def menu(self, root): menu = module.MenuItem('samba', verbose_name=_('Directory')) root.append(menu)
from nazs.core import module from nazs.core.commands import run from nazs.core.sudo import root from django.utils.translation import ugettext as _ import os import logging logger = logging.getLogger(__name__) class Samba(module.Module): """ Samba 4 module, it deploys samba AD and file server """ ETC_FILE = '/etc/samba/smb.conf' def install(self): """ Installation procedure, it writes basic smb.conf and uses samba-tool to provision the domain """ with root(): if os.path.exists(self.ETC_FILE): os.unlink(self.ETC_FILE) run("samba-tool domain provision " " --domain='zentyal' " " --workgroup='zentyal' " "--realm='zentyal.lan' " "--use-xattrs=yes " "--use-rfc2307 " "--server-role='domain controller' " "--use-ntvfs " "--adminpass='foobar1!'") def menu(self, root): menu = module.MenuItem('samba', verbose_name=_('Directory')) root.append(menu)
Make q variables local to function scope In execute and nestedExecute functions, changed q variable to "var q" so that it's not in the global scope
angular.module('ngCordova.plugins.sqlite', []) .factory('$cordovaSQLite', ['$q', function ($q) { return { openDB: function (dbName) { return window.sqlitePlugin.openDatabase({name: dbName}); }, openDBBackground: function (dbName) { return window.sqlitePlugin.openDatabase({name: dbName, bgType: 1}); }, execute: function (db, query, binding) { var q = $q.defer(); db.transaction(function (tx) { tx.executeSql(query, binding, function (tx, result) { q.resolve(result); }, function (transaction, error) { q.reject(error); }); }); return q.promise; }, nestedExecute: function (db, query1, query2, binding1, binding2) { var q = $q.defer(); db.transaction(function (tx) { tx.executeSql(query1, binding1, function (tx, result) { q.resolve(result); tx.executeSql(query2, binding2, function (tx, res) { q.resolve(res); }) }) }, function (transaction, error) { q.reject(error); }); return q.promise; } // more methods here } }]);
angular.module('ngCordova.plugins.sqlite', []) .factory('$cordovaSQLite', ['$q', function ($q) { return { openDB: function (dbName) { return window.sqlitePlugin.openDatabase({name: dbName}); }, openDBBackground: function (dbName) { return window.sqlitePlugin.openDatabase({name: dbName, bgType: 1}); }, execute: function (db, query, binding) { q = $q.defer(); db.transaction(function (tx) { tx.executeSql(query, binding, function (tx, result) { q.resolve(result); }, function (transaction, error) { q.reject(error); }); }); return q.promise; }, nestedExecute: function (db, query1, query2, binding1, binding2) { q = $q.defer(); db.transaction(function (tx) { tx.executeSql(query1, binding1, function (tx, result) { q.resolve(result); tx.executeSql(query2, binding2, function (tx, res) { q.resolve(res); }) }) }, function (transaction, error) { q.reject(error); }); return q.promise; } // more methods here } }]);
Rename Debug.init JS function to Debug.ready for consistency with other modules
var Debug = { ready: function() { $( '.enable-profiling' ).click( function() { return toggleProfiling.bind( this )( true ); } ); $( '.disable-profiling' ).click( function() { return toggleProfiling.bind( this )( false ); } ); function toggleProfiling( enable ) { var text; var token = $( "#profiling-form input[name=token]" ).val(); if ( enable ) { $( this ).remove(); text = 'Measuring...'; } else { text = 'Disabling...'; } $( '.dev' ).append( '<span class="measure">' + text + '</span>' ); $.post( 'debugging/update', { token: token, enable: enable? 1: 0 }, function() { window.location.reload(); } ); return false; }; $( '.profiling-link' ).click( function() { $( '.debug-window' ).show(); return false; } ); $( '.debug-window .close' ).click( function() { $( '.debug-window' ).hide(); } ); } }; $( document ).ready( Debug.ready );
var Debug = { init: function() { $( '.enable-profiling' ).click( function() { return toggleProfiling.bind( this )( true ); } ); $( '.disable-profiling' ).click( function() { return toggleProfiling.bind( this )( false ); } ); function toggleProfiling( enable ) { var text; var token = $( "#profiling-form input[name=token]" ).val(); if ( enable ) { $( this ).remove(); text = 'Measuring...'; } else { text = 'Disabling...'; } $( '.dev' ).append( '<span class="measure">' + text + '</span>' ); $.post( 'debugging/update', { token: token, enable: enable? 1: 0 }, function() { window.location.reload(); } ); return false; }; $( '.profiling-link' ).click( function() { $( '.debug-window' ).show(); return false; } ); $( '.debug-window .close' ).click( function() { $( '.debug-window' ).hide(); } ); } }; $( document ).ready( Debug.init );
Make 'errors' top property in response array
<?php namespace GraphQL\Executor; use GraphQL\Error\Error; class ExecutionResult implements \JsonSerializable { /** * @var array */ public $data; /** * @var Error[] */ public $errors; /** * @var array[] */ public $extensions; /** * @var callable */ private $errorFormatter = ['GraphQL\Error\Error', 'formatError']; /** * @param array $data * @param array $errors * @param array $extensions */ public function __construct(array $data = null, array $errors = [], array $extensions = []) { $this->data = $data; $this->errors = $errors; $this->extensions = $extensions; } /** * @param callable $errorFormatter * @return $this */ public function setErrorFormatter(callable $errorFormatter) { $this->errorFormatter = $errorFormatter; return $this; } /** * @return array */ public function toArray() { $result = []; if (!empty($this->errors)) { $result['errors'] = array_map($this->errorFormatter, $this->errors); } if (null !== $this->data) { $result['data'] = $this->data; } if (!empty($this->extensions)) { $result['extensions'] = (array) $this->extensions; } return $result; } public function jsonSerialize() { return $this->toArray(); } }
<?php namespace GraphQL\Executor; use GraphQL\Error\Error; class ExecutionResult implements \JsonSerializable { /** * @var array */ public $data; /** * @var Error[] */ public $errors; /** * @var array[] */ public $extensions; /** * @var callable */ private $errorFormatter = ['GraphQL\Error\Error', 'formatError']; /** * @param array $data * @param array $errors * @param array $extensions */ public function __construct(array $data = null, array $errors = [], array $extensions = []) { $this->data = $data; $this->errors = $errors; $this->extensions = $extensions; } /** * @param callable $errorFormatter * @return $this */ public function setErrorFormatter(callable $errorFormatter) { $this->errorFormatter = $errorFormatter; return $this; } /** * @return array */ public function toArray() { $result = []; if (null !== $this->data) { $result['data'] = $this->data; } if (!empty($this->errors)) { $result['errors'] = array_map($this->errorFormatter, $this->errors); } if (!empty($this->extensions)) { $result['extensions'] = (array) $this->extensions; } return $result; } public function jsonSerialize() { return $this->toArray(); } }
Update examples to return env from output defined on parent workflow
'use strict'; // workflows/createDeployment var Joi = require('joi'); module.exports = { schema: Joi.object({ deployerId: Joi.string().required(), name: Joi.string().min(1).required(), }).required().unknown(true), version: '1.0', decider: function(args) { return { createDeploymentDoc: { activity: 'createDeploymentDoc', input: (env) => ({}), output: (env) => { return { env: { theId: env.id, newValueThatIWant: env.newValueThatIWant } }; } }, startNewDeployment: { dependsOn: ['createDeploymentDoc'], input: (env) => { return { deploymentId: env.theId }; }, workflow: 'startDeployment' }, doSomethingWithDeployment: { dependsOn: ['startNewDeployment'], input: (env) => { return { theValue: env.newValueThatIWant }; }, output: (env) => { env.BLAMMO = 'mrow0'; return { env }; }, workflow: 'doSomething' }, setDeploymentStateCreated: { dependsOn: ['startNewDeployment'], input: (env) => { return { state: 'Running', id: env.theId }; }, activity: 'setDeploymentDocState', }, } }, output: function(results) { return { env: { deployment: results.startNewDeployment } }; } };
'use strict'; // workflows/createDeployment var Joi = require('joi'); module.exports = { schema: Joi.object({ deployerId: Joi.string().required(), name: Joi.string().min(1).required(), }).required().unknown(true), version: '1.0', decider: function(args) { return { createDeploymentDoc: { activity: 'createDeploymentDoc', input: (env) => ({}), output: (env) => ({ theId: env.id, newValueThatIWant: env.newValueThatIWant }) }, startNewDeployment: { dependsOn: ['createDeploymentDoc'], input: (env) => ({ deploymentId: env.theId }), workflow: 'startDeployment' }, doSomethingWithDeployment: { dependsOn: ['startNewDeployment'], input: (env) => { return { theValue: env.newValueThatIWant }; }, output: (env) => { env.BLAMMO = 'mrow0'; return { env }; }, workflow: 'doSomething' }, setDeploymentStateCreated: { dependsOn: ['startNewDeployment'], input: (env) => { return { state: 'Running', id: env.theId }; }, activity: 'setDeploymentDocState', }, } }, output: function(results) { return { env: { deployment: results.startNewDeployment } }; } };
Remove button to clone a topic when creating a dashboard
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; // constants import { TEMPLATES } from './constants'; class TemplateSelector extends PureComponent { static propTypes = { onChange: PropTypes.func.isRequired } state = { template: TEMPLATES[0].value } onChangeTemplate = (template) => { const { onChange } = this.props; const newTemplate = TEMPLATES.find(_template => _template.value === template); this.setState({ template }); onChange(newTemplate); } render() { const { template } = this.state; return ( <div className="c-dashboard-template-selector"> <div className="row"> <div className="column small-12 medium-6"> <h2 className="c-title -primary -huge">Content</h2> <p>Use a template, clone a topic page into a new dashboard or start a new one from scratch. </p> </div> <div className="column small-12"> <ul className="template-list"> {TEMPLATES.map(_template => ( <li key={_template.value} className="template-list-item" onClick={() => this.onChangeTemplate(_template.value)} > <h4 className="template-name">{_template.label}</h4> <span className="template-description">{_template.description}</span> </li> ))} </ul> </div> </div> </div > ); } } export default TemplateSelector;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import HeaderTopics from './import-selector'; // constants import { TEMPLATES } from './constants'; class TemplateSelector extends PureComponent { static propTypes = { onChange: PropTypes.func.isRequired } state = { template: TEMPLATES[0].value } onChangeTemplate = (template) => { const { onChange } = this.props; const newTemplate = TEMPLATES.find(_template => _template.value === template); this.setState({ template }); onChange(newTemplate); } render() { const { template } = this.state; return ( <div className="c-dashboard-template-selector"> <div className="row"> <div className="column small-12 medium-6"> <h2 className="c-title -primary -huge">Content</h2> <p>Use a template, clone a topic page into a new dashboard or start a new one from scratch. </p> </div> <div className="column small-12"> <ul className="template-list"> {TEMPLATES.map(_template => ( <li key={_template.value} className='template-list-item' onClick={() => this.onChangeTemplate(_template.value)} > <h4 className="template-name">{_template.label}</h4> <span className="template-description">{_template.description}</span> </li> ))} <HeaderTopics /> </ul> </div> </div> </div > ); } } export default TemplateSelector;
Modify findByName() to call employeeListTpl
// We use an "Immediate Function" to initialize the application to avoid leaving anything behind in the global scope (function () { /* ---------------------------------- Local Variables ---------------------------------- */ var service = new EmployeeService(); var homeTpl = Handlebars.compile($("#home.tpl").html()); var employeeListTpl = Handlebars.compile($("#employee-list-tpl").html()); service.initialize().done(function () { // console.log("Service initialized"); renderHomeView(); }); /* --------------------------------- Event Registration -------------------------------- */ // $('.search-key').on('keyup', findByName); // $('.help-btn').on('click', function() { // alert("Employee Directory v3.4"); // }); document.addEventListener('deviceready', function () { if (navigator.notification) { // Override default HTML alert with native dialog window.alert = function (message) { navigator.notification.alert( message, // message null, // callback "Workshop", // title "OK" // buttonName ); }; } FastClick.attach(document.body); }, false); /* ---------------------------------- Local Functions ---------------------------------- */ function findByName() { service.findByName($('.search-key').val()).done(function (employees) { $('.content').html(employeeListTpl(employees)); }); } function renderHomeView() { $('body').html(homeTpl()); $('.search-key').on('keyup', findByName); } }());
// We use an "Immediate Function" to initialize the application to avoid leaving anything behind in the global scope (function () { /* ---------------------------------- Local Variables ---------------------------------- */ var service = new EmployeeService(); var homeTpl = Handlebars.compile($("#home.tpl").html()); var employeeListTpl = Handlebars.compile($("#employee-list-tpl").html()); service.initialize().done(function () { // console.log("Service initialized"); renderHomeView(); }); /* --------------------------------- Event Registration -------------------------------- */ // $('.search-key').on('keyup', findByName); // $('.help-btn').on('click', function() { // alert("Employee Directory v3.4"); // }); document.addEventListener('deviceready', function () { if (navigator.notification) { // Override default HTML alert with native dialog window.alert = function (message) { navigator.notification.alert( message, // message null, // callback "Workshop", // title "OK" // buttonName ); }; } FastClick.attach(document.body); }, false); /* ---------------------------------- Local Functions ---------------------------------- */ function findByName() { service.findByName($('.search-key').val()).done(function (employees) { var l = employees.length; var e; $('.employee-list').empty(); for (var i = 0; i < l; i++) { e = employees[i]; $('.employee-list').append('<li><a href="#employees/' + e.id + '">' + e.firstName + ' ' + e.lastName + '</a></li>'); } }); } function renderHomeView() { $('body').html(homeTpl()); $('.search-key').on('keyup', findByName); } }());
check_invariant(): Use the same child->parent "formula" used by heapq.py.
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): if pos: # pos 0 has no parent parentpos = (pos-1) >> 1 verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
"""Unittests for heapq.""" from test.test_support import verify, vereq, verbose, TestFailed from heapq import heappush, heappop import random def check_invariant(heap): # Check the heap invariant. for pos, item in enumerate(heap): parentpos = ((pos+1) >> 1) - 1 if parentpos >= 0: verify(heap[parentpos] <= item) def test_main(): # 1) Push 100 random numbers and pop them off, verifying all's OK. heap = [] data = [] check_invariant(heap) for i in range(256): item = random.random() data.append(item) heappush(heap, item) check_invariant(heap) results = [] while heap: item = heappop(heap) check_invariant(heap) results.append(item) data_sorted = data[:] data_sorted.sort() vereq(data_sorted, results) # 2) Check that the invariant holds for a sorted array check_invariant(results) # 3) Naive "N-best" algorithm heap = [] for item in data: heappush(heap, item) if len(heap) > 10: heappop(heap) heap.sort() vereq(heap, data_sorted[-10:]) # Make user happy if verbose: print "All OK" if __name__ == "__main__": test_main()
io: Move plugin tests to io/tests.
#!/usr/bin/env python from scikits.image._build import cython import os.path base_path = os.path.abspath(os.path.dirname(__file__)) def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('io', parent_package, top_path) config.add_data_dir('tests') config.add_data_files('_plugins/*.ini') # This function tries to create C files from the given .pyx files. If # it fails, we build the checked-in .c files. cython(['_plugins/_colormixer.pyx', '_plugins/_histograms.pyx'], working_path=base_path) config.add_extension('_plugins._colormixer', sources=['_plugins/_colormixer.c'], include_dirs=[get_numpy_include_dirs()]) config.add_extension('_plugins._histograms', sources=['_plugins/_histograms.c'], include_dirs=[get_numpy_include_dirs()]) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = 'scikits.image Developers', maintainer_email = '[email protected]', description = 'Image I/O Routines', url = 'http://stefanv.github.com/scikits.image/', license = 'Modified BSD', **(configuration(top_path='').todict()) )
#!/usr/bin/env python from scikits.image._build import cython import os.path base_path = os.path.abspath(os.path.dirname(__file__)) def configuration(parent_package='', top_path=None): from numpy.distutils.misc_util import Configuration, get_numpy_include_dirs config = Configuration('io', parent_package, top_path) config.add_data_dir('tests') config.add_data_dir('_plugins/tests') config.add_data_files('_plugins/*.ini') # This function tries to create C files from the given .pyx files. If # it fails, we build the checked-in .c files. cython(['_plugins/_colormixer.pyx', '_plugins/_histograms.pyx'], working_path=base_path) config.add_extension('_plugins._colormixer', sources=['_plugins/_colormixer.c'], include_dirs=[get_numpy_include_dirs()]) config.add_extension('_plugins._histograms', sources=['_plugins/_histograms.c'], include_dirs=[get_numpy_include_dirs()]) return config if __name__ == '__main__': from numpy.distutils.core import setup setup(maintainer = 'scikits.image Developers', maintainer_email = '[email protected]', description = 'Image I/O Routines', url = 'http://stefanv.github.com/scikits.image/', license = 'Modified BSD', **(configuration(top_path='').todict()) )
Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well.
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_lib', 'build_dir'), ('install_lib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
"""install_ext Implement the Distutils "install_ext" command to install extension modules.""" # created 1999/09/12, Greg Ward __revision__ = "$Id$" from distutils.core import Command from distutils.util import copy_tree class install_ext (Command): description = "install C/C++ extension modules" user_options = [ ('install-dir=', 'd', "directory to install to"), ('build-dir=','b', "build directory (where to install from)"), ] def initialize_options (self): # let the 'install' command dictate our installation directory self.install_dir = None self.build_dir = None def finalize_options (self): self.set_undefined_options ('install', ('build_platlib', 'build_dir'), ('install_platlib', 'install_dir')) def run (self): # Make sure we have built all extension modules first self.run_peer ('build_ext') # Dump the entire "build/platlib" directory (or whatever it really # is; "build/platlib" is the default) to the installation target # (eg. "/usr/local/lib/python1.5/site-packages"). Note that # putting files in the right package dir is already done when we # build. outfiles = self.copy_tree (self.build_dir, self.install_dir) # class InstallExt
Fix typo in option validation.
import { declare } from "@babel/helper-plugin-utils"; import transformTypeScript from "@babel/plugin-transform-typescript"; export default declare( (api, { jsxPragma, allExtensions = false, isTSX = false }) => { api.assertVersion(7); if (typeof allExtensions !== "boolean") { throw new Error(".allExtensions must be a boolean, or undefined"); } if (typeof isTSX !== "boolean") { throw new Error(".isTSX must be a boolean, or undefined"); } if (isTSX && !allExtensions) { throw new Error("isTSX:true requires allExtensions:true"); } return { overrides: allExtensions ? [ { plugins: [[transformTypeScript, { jsxPragma, isTSX }]], }, ] : [ { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.ts$/, plugins: [[transformTypeScript, { jsxPragma }]], }, { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.tsx$/, plugins: [[transformTypeScript, { jsxPragma, isTSX: true }]], }, ], }; }, );
import { declare } from "@babel/helper-plugin-utils"; import transformTypeScript from "@babel/plugin-transform-typescript"; export default declare( (api, { jsxPragma, allExtensions = false, isTSX = false }) => { api.assertVersion(7); if (typeof allExtensions !== "boolean") { throw new Error(".allExtensions must be a boolean, or undefined"); } if (typeof isTSX !== "boolean") { throw new Error(".allExtensions must be a boolean, or undefined"); } if (isTSX && !allExtensions) { throw new Error("isTSX:true requires allExtensions:true"); } return { overrides: allExtensions ? [ { plugins: [[transformTypeScript, { jsxPragma, isTSX }]], }, ] : [ { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.ts$/, plugins: [[transformTypeScript, { jsxPragma }]], }, { // Only set 'test' if explicitly requested, since it requires that // Babel is being called` test: /\.tsx$/, plugins: [[transformTypeScript, { jsxPragma, isTSX: true }]], }, ], }; }, );
Reformat code to PEP-8 standards
# # Copyright 2014-2015 Boundary, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from boundary import ApiCli class PluginGet(ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path = "v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName', action='store', metavar='plugin_name', required=True, help='Plugin name') def getArguments(self): """ Extracts the specific arguments of this CLI """ ApiCli.getArguments(self) if self.args.pluginName is not None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}".format(self.pluginName) def getDescription(self): return "Get the details of a plugin in a Boundary account"
# # Copyright 2014-2015 Boundary, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # from boundary import ApiCli class PluginGet (ApiCli): def __init__(self): ApiCli.__init__(self) self.method = "GET" self.path="v1/plugins" self.pluginName = None def addArguments(self): ApiCli.addArguments(self) self.parser.add_argument('-n', '--plugin-Name', dest='pluginName',action='store',required=True,help='Plugin name') def getArguments(self): ''' Extracts the specific arguments of this CLI ''' ApiCli.getArguments(self) if self.args.pluginName != None: self.pluginName = self.args.pluginName self.path = "v1/plugins/{0}".format(self.pluginName) def getDescription(self): return "Get the details of a plugin in a Boundary account"
Restructure KDS options to be more like Keystone's options Restructure the KDS options to be more closely aligned with the way Keystone options work and allowing movement towards not registering the options on import. This will also prevent KDS options from appearing in the Keystone auto-generated sample config. Change-Id: I073aa58ff3132e2714478f54c88c3a8200ff47da
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from keystone.openstack.common import log CONF = cfg.CONF FILE_OPTIONS = { None: [ cfg.StrOpt('bind_ip', default='0.0.0.0', help='IP for the server to bind to'), cfg.IntOpt('port', default=9109, help='The port for the server')]} def configure(conf=None): if conf is None: conf = CONF for group in FILE_OPTIONS: conf.register_opts(FILE_OPTIONS[group], group=group) def parse_args(args, default_config_files=None): CONF(args=args[1:], project='kds', default_config_files=default_config_files) def prepare_service(argv=[]): cfg.set_defaults(log.log_opts, default_log_levels=['sqlalchemy=WARN', 'eventlet.wsgi.server=WARN' ]) parse_args(argv) log.setup('kds') configure()
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from oslo.config import cfg from keystone.openstack.common import log CONF = cfg.CONF API_SERVICE_OPTS = [ cfg.StrOpt('bind_ip', default='0.0.0.0', help='IP for the server to bind to'), cfg.IntOpt('port', default=9109, help='The port for the server'), ] CONF.register_opts(API_SERVICE_OPTS) def parse_args(args, default_config_files=None): CONF(args=args[1:], project='kds', default_config_files=default_config_files) def prepare_service(argv=[]): cfg.set_defaults(log.log_opts, default_log_levels=['sqlalchemy=WARN', 'eventlet.wsgi.server=WARN' ]) parse_args(argv) log.setup('kds')
Fix broken Yaml fixture dependences parsing
<?php namespace MageTest\Manager\Attributes\Provider\Loader; use Symfony\Component\Yaml\Yaml; /** * Class YmlLoader * * @package MageTest\Manager\Attributes\Provider\Loader */ class YmlLoader implements Loader, ParseFields { /** * @var \Symfony\Component\Yaml\Yaml */ private $yaml; /** * @param Yaml $yaml */ public function __construct(Yaml $yaml = null) { $this->yaml = $yaml ? : new Yaml; } /** * @param $file * @return array */ public function load($file) { return $this->yaml->parse($file); } /** * @param $model * @return array */ public function parseFields($model) { return array( $this->parseModel(key($model)) => array( 'depends' => $this->parseDependencies(key($model)), 'attributes' => reset($model) ) ); } /** * @param $key * @return mixed */ private function parseModel($key) { preg_match("/[^ (]+/", $key, $matches); return reset($matches); } /** * @param $key * @return mixed */ private function parseDependencies($key) { preg_match("/ \((.*)\)/", $key, $matches); if (strstr(end($matches), ' ')) { return explode(" ", end($matches)); } return end($matches); } }
<?php namespace MageTest\Manager\Attributes\Provider\Loader; use Symfony\Component\Yaml\Yaml; /** * Class YmlLoader * * @package MageTest\Manager\Attributes\Provider\Loader */ class YmlLoader implements Loader, ParseFields { /** * @var \Symfony\Component\Yaml\Yaml */ private $yaml; /** * @param Yaml $yaml */ public function __construct(Yaml $yaml = null) { $this->yaml = $yaml ? : new Yaml; } /** * @param $file * @return array */ public function load($file) { return $this->yaml->parse($file); } /** * @param $model * @return array */ public function parseFields($model) { return array( $this->parseModel(key($model)) => array( 'depends' => $this->parseDependencies(key($model)), 'attributes' => reset($model) ) ); } /** * @param $key * @return mixed */ private function parseModel($key) { preg_match("/[^ (]+/", $key, $matches); return reset($matches); } /** * @param $key * @return mixed */ private function parseDependencies($key) { preg_match("/ \((.*)\)/", $key, $matches); return end($matches); } }
Add conditional before wait statement in synchronize block.
package com.novoda.downloadmanager; import android.support.annotation.Nullable; import com.novoda.notils.logger.simple.Log; final class WaitForDownloadServiceThenPerform { interface Action<T> { T performAction(); } private WaitForDownloadServiceThenPerform() { // Uses static factory method. } static <T> WaitForDownloadServiceThenPerformAction<T> waitFor(@Nullable DownloadService downloadService, Object downloadServiceLock) { return new WaitForDownloadServiceThenPerformAction<>(downloadService, downloadServiceLock); } static class WaitForDownloadServiceThenPerformAction<T> { private final DownloadService downloadService; private final Object downloadServiceLock; WaitForDownloadServiceThenPerformAction(DownloadService downloadService, Object downloadServiceLock) { this.downloadService = downloadService; this.downloadServiceLock = downloadServiceLock; } T thenPerform(final Action<T> action) { if (downloadService == null) { waitForLock(); } return action.performAction(); } private void waitForLock() { try { synchronized (downloadServiceLock) { if (downloadService == null) { downloadServiceLock.wait(); } } } catch (InterruptedException e) { Log.e(e, "Interrupted waiting for download service."); } } } }
package com.novoda.downloadmanager; import android.support.annotation.Nullable; import com.novoda.notils.logger.simple.Log; final class WaitForDownloadServiceThenPerform { interface Action<T> { T performAction(); } private WaitForDownloadServiceThenPerform() { // Uses static factory method. } static <T> WaitForDownloadServiceThenPerformAction<T> waitFor(@Nullable DownloadService downloadService, Object downloadServiceLock) { return new WaitForDownloadServiceThenPerformAction<>(downloadService, downloadServiceLock); } static class WaitForDownloadServiceThenPerformAction<T> { private final DownloadService downloadService; private final Object lock; WaitForDownloadServiceThenPerformAction(DownloadService downloadService, Object lock) { this.downloadService = downloadService; this.lock = lock; } T thenPerform(final Action<T> action) { if (downloadService == null) { try { synchronized (lock) { lock.wait(); } } catch (InterruptedException e) { Log.e(e, "Interrupted waiting for download service."); } } return action.performAction(); } } }
Add tests for boundary conditions in HttpClient timeouts
<?php use MessageBird\Client; use MessageBird\Common\HttpClient; class HttpClientTest extends PHPUnit_Framework_TestCase { public function testHttpClient() { $client = new HttpClient(Client::ENDPOINT); $url = $client->getRequestUrl('a', null); $this->assertSame(Client::ENDPOINT.'/a', $url); $url = $client->getRequestUrl('a', array('b' => 1)); $this->assertSame(Client::ENDPOINT.'/a?b=1', $url); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp #^Timeout must be an int > 0, got "integer 0".$# */ public function testHttpClientInvalidTimeout() { new HttpClient(Client::ENDPOINT, 0); } /** * Tests a boundary condition (timeout == 1) */ public function testHttpClientValidTimeoutBoundary() { new HttpClient(Client::ENDPOINT, 1); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp #^Connection timeout must be an int >= 0, got "stdClass".$# */ public function testHttpClientInvalidConnectionTimeout() { new HttpClient(Client::ENDPOINT, 10, new \stdClass()); } /** * Tests a boundary condition (connectionTimeout == 0) */ public function testHttpClientValidConnectionTimeoutBoundary() { new HttpClient(Client::ENDPOINT, 10, 0); } /** * Test that requests can only be made when there is an Authentication set * * @expectedException \MessageBird\Exceptions\AuthenticateException * @expectedExceptionMessageRegExp #Can not perform API Request without Authentication# */ public function testHttpClientWithoutAuthenticationException() { $client = new HttpClient(Client::ENDPOINT); $client->performHttpRequest('foo', 'bar'); } }
<?php use MessageBird\Client; use MessageBird\Common\HttpClient; class HttpClientTest extends PHPUnit_Framework_TestCase { public function testHttpClient() { $client = new HttpClient(Client::ENDPOINT); $url = $client->getRequestUrl('a', null); $this->assertSame(Client::ENDPOINT.'/a', $url); $url = $client->getRequestUrl('a', array('b' => 1)); $this->assertSame(Client::ENDPOINT.'/a?b=1', $url); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp #^Timeout must be an int > 0, got "integer 0".$# */ public function testHttpClientInvalidTimeout() { new HttpClient(Client::ENDPOINT, 0); } /** * @expectedException \InvalidArgumentException * @expectedExceptionMessageRegExp #^Connection timeout must be an int >= 0, got "stdClass".$# */ public function testHttpClientInvalidConnectionTimeout() { new HttpClient(Client::ENDPOINT, 10, new \stdClass()); } /** * Test that requests can only be made when there is an Authentication set * * @test * @expectedException \MessageBird\Exceptions\AuthenticateException * @expectedExceptionMessageRegExp #Can not perform API Request without Authentication# */ public function testHttpClientWithoutAuthenticationException() { $client = new HttpClient(Client::ENDPOINT); $client->performHttpRequest('foo', 'bar'); } }
Update feature: Cleanup admin layout
<div class="container-fluid"> <div class="content row"> <?php if ($sidebar_left || $sidebar_right): ?> <!-- ########## Sidebar start ########## --> <div class="col-sm-3 col-md-2 sidebar"> <?php echo $sidebar_left; ?> <?php echo $sidebar_right; ?> </div> <!-- ########## Sidebar end ########## --> <?php endif; ?> <!-- ########## Content start ############# --> <div class="col-sm-9 col-md-10 main-content"> <div class="wrapper"> <?php if ($title): ?> <div class="page-header"> <h1> <i class="fa fa-info-circle"></i> <?php echo $title;?></h1> </div> <?php endif; ?> <div class="content-wrapper"> <?php if ($messages): ?> <!-- ########## Messages start ########## --> <div id="messages" class="messages"> <?php echo $messages ?> </div> <!-- ########## Messages end ########## --> <?php endif; ?> <?php if ($tabs): ?> <div id="tabs-actions"> <div id="tabs"><?php echo $tabs; ?></div> </div> <?php endif; ?> <div id="content-body" class="<?php echo $tabs ? 'with-tabs' : 'without-tabs'?>"> <?php echo $content; ?> </div> </div> </div> </div> </div> </div>
<div class="container-fluid"> <div class="content row"> <?php if ($sidebar_left || $sidebar_right): ?> <!-- ########## Sidebar start ########## --> <div class="col-sm-3 col-md-2 sidebar"> <?php echo $sidebar_left; ?> <?php echo $sidebar_right; ?> </div> <!-- ########## Sidebar end ########## --> <?php endif; ?> <!-- ########## Content start ############# --> <div class="col-sm-9 col-md-10 main-content"> <?php if ($title): ?> <div class="page-header"> <h1> <i class="fa fa-info-circle"></i> <?php echo $title;?></h1> </div> <?php endif; ?> <div class="content-wrapper"> <?php if ($messages): ?> <!-- ########## Messages start ########## --> <div id="messages" class="messages"> <?php echo $messages ?> </div> <!-- ########## Messages end ########## --> <?php endif; ?> <?php if ($tabs): ?> <div id="tabs-actions"> <div id="tabs"><?php echo $tabs; ?></div> </div> <?php endif;?> <div id="content-body" class="<?php echo $tabs ? 'with-tabs' : 'without-tabs'?>"> <?php echo $content; ?> </div> </div> </div> </div> </div>
[login] Add apps on list that will be used on the test databases Added apps sites and contenttypes to the list. These apps were causing troubles on the test databases. Signed off by: Heitor Reis <[email protected]> Signed off by: Filipe Vaz <[email protected]>
# List of apps that will use the users database USERS_DATABASE_APPS = ['auth', 'login', 'sessions', 'contenttypes', 'sites'] class UserRouter(object): """ A router to control all database operations on models in the login application. """ def db_for_read(self, model, **hints): """ Attempts to read login models go to users. """ if model._meta.app_label in USERS_DATABASE_APPS: return 'users' return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to users. """ if model._meta.app_label in USERS_DATABASE_APPS: return 'users' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the login app is involved. """ if obj1._meta.app_label in USERS_DATABASE_APPS or \ obj2._meta.app_label in USERS_DATABASE_APPS: return True print model._meta.app_label print "BRISA1" return None def allow_syncdb(self, db, model): """ Make sure the login app only appears in the 'users' database. """ if db == 'users': return model._meta.app_label in USERS_DATABASE_APPS elif model._meta.app_label in USERS_DATABASE_APPS: return False print model._meta.app_label print "BRISA" return None
# List of apps that will use the users database USERS_DATABASE_APPS = ['auth','login','sessions'] class UserRouter(object): """ A router to control all database operations on models in the login application. """ def db_for_read(self, model, **hints): """ Attempts to read login models go to users. """ if model._meta.app_label in USERS_DATABASE_APPS: return 'users' print model._meta.app_label print "BRISA" return None def db_for_write(self, model, **hints): """ Attempts to write auth models go to users. """ if model._meta.app_label in USERS_DATABASE_APPS: return 'users' return None def allow_relation(self, obj1, obj2, **hints): """ Allow relations if a model in the login app is involved. """ if obj1._meta.app_label in USERS_DATABASE_APPS or \ obj2._meta.app_label in USERS_DATABASE_APPS: return True return None def allow_syncdb(self, db, model): """ Make sure the login app only appears in the 'users' database. """ if db == 'users': return model._meta.app_label in USERS_DATABASE_APPS elif model._meta.app_label in USERS_DATABASE_APPS: return False return None
Apply touchactive for mouse and touch
(function ($) { $.event.special.touchclick = { setup: function () { if (typeof window.ontouchstart !== "undefined") { $(this).on("touchstart", $.event.special.touchclick.touchstart); $(this).on("touchmove", $.event.special.touchclick.touchmove); $(this).on("touchend", $.event.special.touchclick.touchend); } else { $(this).on("mousedown", $.event.special.touchclick.touchstart); $(this).on("mouseup", $.event.special.touchclick.touchend); } }, click: function (event) { event.type = "touchclick"; $(this).trigger(event.type, arguments); }, teardown: function () { if (typeof window.ontouchstart !== "undefined") { $(this).off("touchstart", $.event.special.touchclick.touchstart); $(this).off("touchmove", $.event.special.touchclick.touchmove); $(this).off("touchend", $.event.special.touchclick.touchend); } else { $(this).off("mousedown", $.event.special.touchclick.touchstart); $(this).off("mouseup", $.event.special.touchclick.touchend); } }, touchstart: function () { this.moved = false; $(this).addClass("touchactive"); }, touchmove: function () { this.moved = true; $(this).removeClass("touchactive"); }, touchend: function () { if (!this.moved) { $.event.special.touchclick.click.apply(this, arguments); } $(this).removeClass("touchactive"); } }; })(jQuery);
(function ($) { $.event.special.touchclick = { setup: function () { if (typeof window.ontouchstart !== "undefined") { $(this).on('touchstart', $.event.special.touchclick.touchstart); $(this).on('touchmove', $.event.special.touchclick.touchmove); $(this).on('touchend', $.event.special.touchclick.touchend); } else { $(this).on("click", $.event.special.touchclick.click); } }, click: function (event) { event.type = "touchclick"; $(this).trigger(event.type, arguments); }, teardown: function () { if (typeof window.ontouchstart !== "undefined") { $(this).off("touchstart", $.event.special.touchclick.touchstart); $(this).off("touchmove", $.event.special.touchclick.touchmove); $(this).off("touchend", $.event.special.touchclick.touchend); } else { $(this).off("click", $.event.special.touchclick.click); } }, touchstart: function () { this.moved = false; $(this).addClass("touchactive"); }, touchmove: function () { this.moved = true; $(this).removeClass("touchactive"); }, touchend: function () { if (!this.moved) { $.event.special.touchclick.click.apply(this, arguments); } $(this).removeClass("touchactive"); } }; })(jQuery);
Ch26: Optimize addition of Tag data in migration.
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models TAGS = ( # ( tag name, tag slug ), ("augmented reality", "augmented-reality"), ("big data", "big-data"), ("django", "django"), ("education", "education"), ("ipython", "ipython"), ("javascript", "javascript"), ("jupyter", "jupyter"), ("mobile", "mobile"), ("node.js", "node-js"), ("php", "php"), ("python", "python"), ("ruby on rails", "ruby-on-rails"), ("ruby", "ruby"), ("video games", "video-games"), ("web", "web"), ("zend", "zend"), ) def add_tag_data(apps, schema_editor): Tag = apps.get_model('organizer', 'Tag') tag_list = [] for tag_name, tag_slug in TAGS: tag_list.append( Tag(name=tag_name, slug=tag_slug)) Tag.objects.bulk_create(tag_list) def remove_tag_data(apps, schema_editor): Tag = apps.get_model('organizer', 'Tag') for _, tag_slug in TAGS: tag = Tag.objects.get(slug=tag_slug) tag.delete() class Migration(migrations.Migration): dependencies = [ ('organizer', '0001_initial'), ] operations = [ migrations.RunPython( add_tag_data, remove_tag_data) ]
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models TAGS = ( # ( tag name, tag slug ), ("augmented reality", "augmented-reality"), ("big data", "big-data"), ("django", "django"), ("education", "education"), ("ipython", "ipython"), ("javascript", "javascript"), ("jupyter", "jupyter"), ("mobile", "mobile"), ("node.js", "node-js"), ("php", "php"), ("python", "python"), ("ruby on rails", "ruby-on-rails"), ("ruby", "ruby"), ("video games", "video-games"), ("web", "web"), ("zend", "zend"), ) def add_tag_data(apps, schema_editor): Tag = apps.get_model('organizer', 'Tag') for tag_name, tag_slug in TAGS: Tag.objects.create( name=tag_name, slug=tag_slug) def remove_tag_data(apps, schema_editor): Tag = apps.get_model('organizer', 'Tag') for _, tag_slug in TAGS: tag = Tag.objects.get(slug=tag_slug) tag.delete() class Migration(migrations.Migration): dependencies = [ ('organizer', '0001_initial'), ] operations = [ migrations.RunPython( add_tag_data, remove_tag_data) ]
Reset current visualizer to dfa
import options from './options' import { getCurrentManipulation } from './manipulation' const nodes = new vis.DataSet([]) const edges = new vis.DataSet([]) const select = $('select') const resetBtn = $('#reset-btn') const testStr = $('input[name="testStr"]') const alphabetPromptText = 'Please enter alphabet string: ' let currentVisualizer = 'DFA' select.material_select() select.change(onVisualizerChange) resetBtn.click(e => start(prompt(alphabetPromptText))) testStr.keypress(e => clickRunBtn(e.which)) start('01') function start(alphabetStr) { if (!alphabetStr) return const alphabet = [ ...new Set(alphabetStr.split('')) ] $('.opt').hide() $('#title').text(currentVisualizer) nodes.clear() edges.clear() new vis.Network(document.getElementById('app'), { nodes, edges}, options(getCurrentManipulation( currentVisualizer, alphabet, { nodes, edges }))) } function onVisualizerChange() { const visSelection = select.val() if (currentVisualizer !== visSelection) { let alphabetStr = prompt(alphabetPromptText) if (!alphabetStr) { select.val(currentVisualizer) return } currentVisualizer = visSelection start(alphabetStr) } } function clickRunBtn(key) { if (key === 13) $('#run-btn').click() }
import options from './options' import { getCurrentManipulation } from './manipulation' const nodes = new vis.DataSet([]) const edges = new vis.DataSet([]) const select = $('select') const resetBtn = $('#reset-btn') const testStr = $('input[name="testStr"]') const alphabetPromptText = 'Please enter alphabet string: ' let currentVisualizer = 'PDA' select.material_select() select.change(onVisualizerChange) resetBtn.click(e => start(prompt(alphabetPromptText))) testStr.keypress(e => clickRunBtn(e.which)) start('01') function start(alphabetStr) { if (!alphabetStr) return const alphabet = [ ...new Set(alphabetStr.split('')) ] $('.opt').hide() $('#title').text(currentVisualizer) nodes.clear() edges.clear() new vis.Network(document.getElementById('app'), { nodes, edges}, options(getCurrentManipulation( currentVisualizer, alphabet, { nodes, edges }))) } function onVisualizerChange() { const visSelection = select.val() if (currentVisualizer !== visSelection) { let alphabetStr = prompt(alphabetPromptText) if (!alphabetStr) { select.val(currentVisualizer) return } currentVisualizer = visSelection start(alphabetStr) } } function clickRunBtn(key) { if (key === 13) $('#run-btn').click() }
Fix some amount, returned one log
const Octokat = require('octokat') const open = require('open') const Promise = require('bluebird') var octo, organization, repository module.exports = function openNotifications (input, opts, token) { octo = new Octokat({ token: token || process.env.GITHUB_OGN_TOKEN }) var amount = opts.amount || 30 if (input[0].split('/').length === 2) { organization = input[0].split('/')[0] repository = input[0].split('/')[1] if (Number.isInteger(input[1])) { amount = input[1] } } else { organization = input[0] repository = input[1] amount = input[2] || amount } return Promise.resolve().then(() => { if (!organization && !repository) { return octo.notifications.fetch({ participating: opts.participating || false }) } else { return octo.repos(organization, repository, 'notifications').fetch() } }).then((result) => { if (result) { if (result.length < amount) { amount = result.length } return Promise.some(result, amount).map((repo) => { var res = repo.subject.url .replace(/(https\:\/\/)api\./, '$1') .replace(/\/repos\//, '/') .replace(/\/pulls\//, '/pull/') open(res) }).then(() => `Opened notifications.`) } else { return `No notifications.` } }).catch((err) => { console.log(err) }) }
const Octokat = require('octokat') const open = require('open') const Promise = require('bluebird') var octo, organization, repository module.exports = function openNotifications (input, opts, token) { octo = new Octokat({ token: token || process.env.GITHUB_OGN_TOKEN }) var amount = opts.amount || 30 if (input[0].split('/').length === 2) { organization = input[0].split('/')[0] repository = input[0].split('/')[1] if (Number.isInteger(input[1])) { amount = input[1] } } else { organization = input[0] repository = input[1] amount = input[2] || amount } return Promise.resolve().then(() => { if (!organization && !repository) { return octo.notifications.fetch({ participating: opts.participating || false }) } else { return octo.repos(organization, repository, 'notifications').fetch() } }).then((result) => { if (result) { return Promise.some(result, amount).map((repo) => { var res = repo.subject.url .replace(/(https\:\/\/)api\./, '$1') .replace(/\/repos\//, '/') .replace(/\/pulls\//, '/pull/') open(res) return `Opened notifications.` }) } else { return `No notifications.` } }).catch((err) => { console.log(err) }) }
Add activityId to each activity object
Template.activityTable.helpers({ 'activities': function () { // Get reference to template instance const instance = Template.instance(); // Get resident activities const activities = instance.data.activities; const activitiesArray = []; activities.forEach(function (activity) { // Create temporary object to get Activity values const activityObject = { activityType: activity.activityType(), activityDate: activity.activityDate, duration: activity.duration, activityId: activity._id }; // Add Activity to activities list activitiesArray.push(activityObject); }); return activitiesArray; }, 'tableSettings': function () { const activityTypeLabel = TAPi18n.__("residentActivityTable-activityTypeLabel"); const durationLabel = TAPi18n.__("residentActivityTable-durationLabel"); const activityDateLabel = TAPi18n.__("residentActivityTable-activityDateLabel"); const tableSettings = { showFilter: false, fields: [ { key: 'activityType', label: activityTypeLabel, sortOrder:1, sortDirection: 'ascending' }, { key: 'duration', label: durationLabel, }, { key: 'activityDate', label: activityDateLabel, tmpl: Template.dateCell, sortOrder: 0, sortDirection: 'descending' }, { key: '_id', label: "", tmpl: Template.editActivityButton, } ], filters: ['activityTypeFilter'] }; return tableSettings; } });
Template.activityTable.helpers({ 'activities': function () { // Get reference to template instance const instance = Template.instance(); // Get resident activities const activities = instance.data.activities; const activitiesArray = []; activities.forEach(function (activity) { // Create temporary object to get Activity values const activityObject = { activityType: activity.activityType(), activityDate: activity.activityDate, duration: activity.duration }; // Add Activity to activities list activitiesArray.push(activityObject); }); return activitiesArray; }, 'tableSettings': function () { const activityTypeLabel = TAPi18n.__("residentActivityTable-activityTypeLabel"); const durationLabel = TAPi18n.__("residentActivityTable-durationLabel"); const activityDateLabel = TAPi18n.__("residentActivityTable-activityDateLabel"); const tableSettings = { showFilter: false, fields: [ { key: 'activityType', label: activityTypeLabel, sortOrder:1, sortDirection: 'ascending' }, { key: 'duration', label: durationLabel, }, { key: 'activityDate', label: activityDateLabel, tmpl: Template.dateCell, sortOrder: 0, sortDirection: 'descending' }, { key: '_id', label: "", tmpl: Template.editActivityButton, } ], filters: ['activityTypeFilter'] }; return tableSettings; } });
Reduce the amount of cars since collision detections does not work properly with this many cars for some reason.
TRAFFICSIM_APP.game = TRAFFICSIM_APP.game || {}; TRAFFICSIM_APP.game.VehicleController = function (worldController) { var self = this; var worldController = worldController; var vehicles = []; this.getWorldController = function () { return this._worldController; }; function initializeRandomCars(numberOfCars) { for (var i = 0; i < numberOfCars; i++) { var car = new TRAFFICSIM_APP.game.Vehicle( worldController, worldController.getGameplayScene().getApplication().getModelContainer().getModelByName("car").clone(), TRAFFICSIM_APP.game.VehicleType.CAR); var nodes = worldController.getRoadController().getNodes(); if (nodes[i * 2]) { var node = nodes[i * 2]; car.setNode(node); car.setPosition(node.position.copy()); vehicles.push(car); worldController.getThreeJSScene().add(car.getModel()); } } } this.initializeCars = function () { initializeRandomCars(5); }; this.update = function (deltaTime) { vehicles.forEach(function (vehicle) { vehicle.update(deltaTime); }); }; this.getVehicles = function () { return vehicles; } };
TRAFFICSIM_APP.game = TRAFFICSIM_APP.game || {}; TRAFFICSIM_APP.game.VehicleController = function (worldController) { var self = this; var worldController = worldController; var vehicles = []; this.getWorldController = function () { return this._worldController; }; function initializeRandomCars(numberOfCars) { for (var i = 0; i < numberOfCars; i++) { var car = new TRAFFICSIM_APP.game.Vehicle( worldController, worldController.getGameplayScene().getApplication().getModelContainer().getModelByName("car").clone(), TRAFFICSIM_APP.game.VehicleType.CAR); var nodes = worldController.getRoadController().getNodes(); if (nodes[i * 2]) { var node = nodes[i * 2]; car.setNode(node); car.setPosition(node.position.copy()); vehicles.push(car); worldController.getThreeJSScene().add(car.getModel()); } } } this.initializeCars = function () { initializeRandomCars(20); }; this.update = function (deltaTime) { vehicles.forEach(function (vehicle) { vehicle.update(deltaTime); }); }; this.getVehicles = function () { return vehicles; } };
Change argument type of regexp binding to ObservableValue<String>
package eu.lestard.advanced_bindings.api; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.value.ObservableValue; /** * This class contains custom binding implementations for Strings. */ public class StringBindings { /** * Creates a boolean binding that is `true` when the given observable string matches the given * RegExp pattern. * * @param text the observable string that is verified. * @param pattern the RegExp pattern that is used. * @return a boolean binding instance. */ public static BooleanBinding matches(final ObservableValue<String> text, final String pattern) { return Bindings.createBooleanBinding(()->{ final String textToVerify = text.getValue(); return textToVerify != null && textToVerify.matches(pattern); }, text); } /** * Creates a boolean binding that is `true` when the given observable string matches the given * RegExp pattern (also given as observable string). * * @param text the observable string that is verified. * @param pattern the observable string with the RegExp pattern that is used. * @return a boolean binding instance. */ public static BooleanBinding matches(final ObservableValue<String> text, final ObservableValue<String> pattern) { return Bindings.createBooleanBinding(()->{ final String textToVerify = text.getValue(); final String patternString = pattern.getValue(); return textToVerify != null && patternString != null && textToVerify.matches(patternString); }, text, pattern); } }
package eu.lestard.advanced_bindings.api; import javafx.beans.binding.Bindings; import javafx.beans.binding.BooleanBinding; import javafx.beans.value.ObservableStringValue; /** * This class contains custom binding implementations for Strings. */ public class StringBindings { /** * Creates a boolean binding that is `true` when the given observable string matches the given * RegExp pattern. * * @param text the observable string that is verified. * @param pattern the RegExp pattern that is used. * @return a boolean binding instance. */ public static BooleanBinding matches(final ObservableStringValue text, final String pattern) { return Bindings.createBooleanBinding(()->{ final String textToVerify = text.get(); return textToVerify != null && textToVerify.matches(pattern); }, text); } /** * Creates a boolean binding that is `true` when the given observable string matches the given * RegExp pattern (also given as observable string). * * @param text the observable string that is verified. * @param pattern the observable string with the RegExp pattern that is used. * @return a boolean binding instance. */ public static BooleanBinding matches(final ObservableStringValue text, final ObservableStringValue pattern) { return Bindings.createBooleanBinding(()->{ final String textToVerify = text.get(); final String patternString = pattern.get(); return textToVerify != null && patternString != null && textToVerify.matches(patternString); }, text, pattern); } }
Add missing assertions on authorizeTransfer test
<?php namespace Omnipay\Skrill\Message; use Omnipay\Tests\TestCase; class AuthorizeTransferRequestTest extends TestCase { /** * @var AuthorizeTransferRequest */ private $request; public function setUp() { parent::setUp(); $this->request = new AuthorizeTransferRequest($this->getHttpClient(), $this->getHttpRequest()); } public function testGetData() { $expectedData = array( 'email' => '[email protected]', 'password' => 'password', 'amount' => '12.34', 'currency' => 'EUR', 'subject' => 'subject', 'note' => 'note', 'customerEmail' => '[email protected]', 'transactionId' => 'transaction_id', ); $this->request->initialize($expectedData); $data = $this->request->getData(); $this->assertSame('prepare', $data['action']); $this->assertSame($expectedData['email'], $data['email']); $this->assertSame($expectedData['password'], $data['password']); $this->assertSame($expectedData['amount'], $data['amount']); $this->assertSame($expectedData['currency'], $data['currency']); $this->assertSame($expectedData['subject'], $data['subject']); $this->assertSame($expectedData['note'], $data['note']); $this->assertSame($expectedData['customerEmail'], $data['bnf_email']); $this->assertSame($expectedData['transactionId'], $data['frn_trn_id']); } }
<?php namespace Omnipay\Skrill\Message; use Omnipay\Tests\TestCase; class AuthorizeTransferRequestTest extends TestCase { /** * @var AuthorizeTransferRequest */ private $request; public function setUp() { parent::setUp(); $this->request = new AuthorizeTransferRequest($this->getHttpClient(), $this->getHttpRequest()); } public function testGetData() { $expectedData = array( 'email' => '[email protected]', 'password' => 'password', 'amount' => '12.34', 'currency' => 'EUR', 'subject' => 'subject', 'note' => 'note', 'customerEmail' => '[email protected]', 'transactionId' => 'transaction_id', ); $this->request->initialize($expectedData); $data = $this->request->getData(); $this->assertSame($expectedData['amount'], $data['amount']); $this->assertSame($expectedData['currency'], $data['currency']); $this->assertSame($expectedData['subject'], $data['subject']); $this->assertSame($expectedData['note'], $data['note']); $this->assertSame($expectedData['customerEmail'], $data['bnf_email']); $this->assertSame($expectedData['transactionId'], $data['frn_trn_id']); } }
Add only_http_implementation and only_websocket_implementation methods
from devicehive import Handler from devicehive import DeviceHive import pytest class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(object): """Test class.""" def __init__(self, transport_url, refresh_token): self._transport_url = transport_url self._refresh_token = refresh_token self._transport_name = DeviceHive.transport_name(self._transport_url) def transport_name(self): return self._transport_name def http_transport(self): return self._transport_name == 'http' def websocket_transport(self): return self._transport_name == 'websocket' def only_http_implementation(self): if self.http_transport(): return pytest.skip('Implemented only for http transport') def only_websocket_implementation(self): if self.websocket_transport(): return pytest.skip('Implemented only for websocket transport') def run(self, handle_connect, handle_event=None): handler_options = {'handle_connect': handle_connect, 'handle_event': handle_event} device_hive = DeviceHive(self._transport_url, TestHandler, handler_options) device_hive.connect(refresh_token=self._refresh_token) exception_info = device_hive.join(print_exception=False) if not exception_info: return raise exception_info[1]
from devicehive import Handler from devicehive import DeviceHive class TestHandler(Handler): """Test handler class.""" def handle_connect(self): if not self.options['handle_connect'](self): self.api.disconnect() def handle_event(self, event): pass class Test(object): """Test class.""" def __init__(self, transport_url, refresh_token): self._transport_url = transport_url self._refresh_token = refresh_token self._transport_name = DeviceHive.transport_name(self._transport_url) def transport_name(self): return self._transport_name def http_transport(self): return self._transport_name == 'http' def websocket_transport(self): return self._transport_name == 'websocket' def run(self, handle_connect, handle_event=None): handler_options = {'handle_connect': handle_connect, 'handle_event': handle_event} device_hive = DeviceHive(self._transport_url, TestHandler, handler_options) device_hive.connect(refresh_token=self._refresh_token) exception_info = device_hive.join(print_exception=False) if not exception_info: return raise exception_info[1]
Allow to pass lazy objects definitions into wrapper as traversable collection
<?php namespace Isolate\LazyObjects; use Isolate\LazyObjects\Exception\InvalidArgumentException; use Isolate\LazyObjects\Proxy\Definition; use Isolate\LazyObjects\Proxy\Factory; use Isolate\LazyObjects\Exception\RuntimeException; class Wrapper { /** * @var array|Definition[] */ private $definitions; /** * @var Factory */ private $factory; /** * @param Factory $factory * @param array $definitions * @throws InvalidArgumentException */ public function __construct(Factory $factory, $definitions = []) { $this->definitions = []; if (!is_array($definitions) && !$definitions instanceof \Traversable) { throw new InvalidArgumentException("Lazy objects definitions collection must be traversable."); } foreach ($definitions as $definition) { if (!$definition instanceof Definition) { throw new InvalidArgumentException("Lazy object definition must be an instance of Isolate\\LazyObjects\\Proxy\\Definition"); } $this->definitions[] = $definition; } $this->factory = $factory; } /** * @param $object * @return bool */ public function canWrap($object) { foreach ($this->definitions as $proxyDefinition) { if ($proxyDefinition->describeProxyFor($object)) { return true; } } return false; } /** * @param $object * @return WrappedObject * @throws RuntimeException */ public function wrap($object) { foreach ($this->definitions as $proxyDefinition) { if ($proxyDefinition->describeProxyFor($object)) { return $this->factory->createProxy($object, $proxyDefinition); } } throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition."); } }
<?php namespace Isolate\LazyObjects; use Isolate\LazyObjects\Proxy\Definition; use Isolate\LazyObjects\Proxy\Factory; use Isolate\LazyObjects\Exception\RuntimeException; class Wrapper { /** * @var array|Definition[] */ private $definitions; /** * @var Factory */ private $factory; /** * @param Factory $factory * @param array $definitions */ public function __construct(Factory $factory, array $definitions = []) { $this->definitions = $definitions; $this->factory = $factory; } /** * @param $object * @return bool */ public function canWrap($object) { foreach ($this->definitions as $proxyDefinition) { if ($proxyDefinition->describeProxyFor($object)) { return true; } } return false; } /** * @param $object * @return WrappedObject * @throws RuntimeException */ public function wrap($object) { foreach ($this->definitions as $proxyDefinition) { if ($proxyDefinition->describeProxyFor($object)) { return $this->factory->createProxy($object, $proxyDefinition); } } throw new RuntimeException("Can\"t wrap objects that does\"t fit any proxy definition."); } }
Remove empty route and controller
/* Copyright, 2013, by Tomas Korcak. <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function (global) { require ( ["ember", "app"], function (Ember, App) { App.ApplicationView = Ember.View.extend({ classNames: ['app-view'], templateName: "application", /** * Called when inserted to DOM. * @memberof Application.ApplicationView * @instance */ didInsertElement: function () { console.log("App.ApplicationView.didInsertElement()"); } }); } ); })(this);
/* Copyright, 2013, by Tomas Korcak. <[email protected]> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function (global) { require ( ["ember", "app"], function (Ember, App) { App.ApplicationRoute = Ember.Route.extend({ title: "Microscratch", model: function() { }, setupController: function(controller, model) { } }); App.ApplicationController = Ember.Controller.extend({ }); App.ApplicationView = Ember.View.extend({ classNames: ['app-view'], templateName: "application", /** * Called when inserted to DOM. * @memberof Application.ApplicationView * @instance */ didInsertElement: function () { console.log("App.ApplicationView.didInsertElement()"); } }); } ); })(this);
Update `istanbul` to report on `untested` code
'use strict'; /*global jasmine:true */ var clean = require('./lib/clean'), middle = require('@whitneyit/middle'), gulp = require('gulp'), eslint = require('gulp-eslint'), istanbul = require('gulp-istanbul'), jasmine = require('gulp-jasmine'), jscs = require('gulp-jscs'), serve = require('gulp-serve'); gulp.task('clean:coverage', function (done) { clean('coverage', done); }); gulp.task('lint', function () { return gulp.src(['gulpfile.js', 'index.js', 'lib/**/*.js', 'tests/**/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(jscs()); }); gulp.task('serve:coverage', serve({ 'middleware' : middle('coverage'), 'port' : 3333, 'root' : 'coverage' })); gulp.task('test', ['clean:coverage'], function (done) { gulp.src(['lib/**/*.js']) .pipe(istanbul({ 'includeUntested' : true })) .pipe(istanbul.hookRequire()) .on('finish', function () { gulp.src(['tests/specs/**/*.spec.js']) .pipe(jasmine()) .pipe(istanbul.writeReports({ 'dir' : 'coverage/lcov', 'reporters' : ['lcov', 'text-summary'] })) .on('end', done); }); }); gulp.task('default', ['lint', 'test']);
'use strict'; /*global jasmine:true */ var clean = require('./lib/clean'), middle = require('@whitneyit/middle'), gulp = require('gulp'), eslint = require('gulp-eslint'), istanbul = require('gulp-istanbul'), jasmine = require('gulp-jasmine'), jscs = require('gulp-jscs'), serve = require('gulp-serve'); gulp.task('clean:coverage', function (done) { clean('coverage', done); }); gulp.task('lint', function () { return gulp.src(['gulpfile.js', 'index.js', 'lib/**/*.js', 'tests/**/*.js']) .pipe(eslint()) .pipe(eslint.format()) .pipe(jscs()); }); gulp.task('serve:coverage', serve({ 'middleware' : middle('coverage'), 'port' : 3333, 'root' : 'coverage' })); gulp.task('test', ['clean:coverage'], function (done) { gulp.src(['lib/**/*.js']) .pipe(istanbul()) .pipe(istanbul.hookRequire()) .on('finish', function () { gulp.src(['tests/specs/**/*.spec.js']) .pipe(jasmine()) .pipe(istanbul.writeReports({ 'dir' : 'coverage/lcov', 'reporters' : ['lcov', 'text-summary'] })) .on('end', done); }); }); gulp.task('default', ['lint', 'test']);
Add test for failing to find credentials
import os import requests import requests_mock import unittest from .. import Client from ..exceptions import AcquiaCloudException @requests_mock.Mocker() class TestClient(unittest.TestCase): """Tests the Acquia Cloud API client class.""" req = None """ def setup(self, ): " "" Set up the tests with the mock requests handler. " "" session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) """ def test_find_credentials(self, m): """ Tests finding the credentials in environment variables """ os.environ['ACQUIA_CLOUD_API_USER'] = 'user' os.environ['ACQUIA_CLOUD_API_TOKEN'] = 'token' client = Client(cache=None) (user, token) = client._Client__find_credentials() self.assertEqual(user, 'user') self.assertEqual(token, 'token') def test_find_credentials_none_set(self, m): """ Tests finding the credentials in environment variables with empty credentials """ os.environ['ACQUIA_CLOUD_API_USER'] = '' os.environ['ACQUIA_CLOUD_API_TOKEN'] = '' with self.assertRaises(AcquiaCloudException) as cm: client = Client(cache=None) self.assertEqual(str(cm.exception), 'Credentials not provided') def test_user(self, m): email = '[email protected]' m.register_uri('GET', 'https://cloudapi.acquia.com/v1/me.json', json={"authenticated_as": email} ) client = Client(email, 'token') user = client.user().get() self.assertEqual(user['authenticated_as'], email) if __name__ == '__main__': unittest.main()
import os import requests import requests_mock import unittest from .. import Client @requests_mock.Mocker() class TestClient(unittest.TestCase): """Tests the Acquia Cloud API client class.""" req = None """ def setup(self, ): " "" Set up the tests with the mock requests handler. " "" session = requests.Session() adapter = requests_mock.Adapter() session.mount('mock', adapter) """ def test_find_credentials(self, m): """ Tests finding the credentials in environment variables """ os.environ['ACQUIA_CLOUD_API_USER'] = 'user' os.environ['ACQUIA_CLOUD_API_TOKEN'] = 'token' client = Client(cache=None) (user, token) = client._Client__find_credentials() self.assertEqual(user, 'user') self.assertEqual(token, 'token') def test_user(self, m): email = '[email protected]' m.register_uri('GET', 'https://cloudapi.acquia.com/v1/me.json', json={"authenticated_as": email} ) client = Client(email, 'token') user = client.user().get() self.assertEqual(user['authenticated_as'], email) if __name__ == '__main__': unittest.main()
Allow JDK 15 in prep for 20.9.0
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.gocd; import java.util.Arrays; import java.util.TreeSet; public class AssertJava { private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList( JavaVersion.VERSION_11, JavaVersion.VERSION_12, JavaVersion.VERSION_13, JavaVersion.VERSION_14, JavaVersion.VERSION_15 )); public static void assertVMVersion() { checkSupported(JavaVersion.current()); } private static void checkSupported(JavaVersion currentJavaVersion) { if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) { System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() + " and <= " + SUPPORTED_VERSIONS.last() + ". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!"); System.exit(1); } } }
/* * Copyright 2020 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.gocd; import java.util.Arrays; import java.util.TreeSet; public class AssertJava { private static TreeSet<JavaVersion> SUPPORTED_VERSIONS = new TreeSet<>(Arrays.asList( JavaVersion.VERSION_11, JavaVersion.VERSION_12, JavaVersion.VERSION_13, JavaVersion.VERSION_14 )); public static void assertVMVersion() { checkSupported(JavaVersion.current()); } private static void checkSupported(JavaVersion currentJavaVersion) { if (!SUPPORTED_VERSIONS.contains(currentJavaVersion)) { System.err.println("Running GoCD requires Java version >= " + SUPPORTED_VERSIONS.first().name() + " and <= " + SUPPORTED_VERSIONS.last() + ". You are currently running with Java version " + currentJavaVersion + ". GoCD will now exit!"); System.exit(1); } } }
Change Finding Aids homepage to show more collections than two.
<?php $collections = get_records('Collection'); ?> <h1><?php echo __('Welcome'); ?></h1> <div class="row"> <?php foreach($collections as $collection): ?> <div class="col-sm-6"> <h3> <?php $title = metadata($collection, array('Dublin Core', 'Title')); $queryParams = array( 'collection' => $collection->id, 'sort_field' => 'Dublin Core,Title' ); echo link_to('items', 'browse', $title, array(), $queryParams); ?> </h3> <?php if ($description = metadata($collection, array('Dublin Core', 'Description'))): ?> <p><?php echo $description; ?></p> <?php endif; ?> <h4>Browse Sub-Collections</h4> <ul> <?php foreach (metadata($collection, array('Dublin Core', 'Subject'), array('all' => true)) as $subject): ?> <li> <?php $queryParams = array( 'tags' => $subject, 'collection' => $collection->id, 'sort_field' => 'Dublin Core,Title' ); echo link_to('items', 'browse', $subject, array(), $queryParams); ?> </li> <?php endforeach; ?> </ul> </div> <?php endforeach; ?> </div> <script src="https://lib.bgsu.edu/assets/js/masonry.pkgd.js"></script> <script> jQuery(window).load(function() { new Masonry( 'main .row', {'percentPosition': true, transitionDuration: 0} ); }); </script>
<h1><?php echo __('Welcome'); ?></h1> <div class="row"> <?php foreach(get_recent_collections(2) as $collection): ?> <div class="col-sm-6"> <h3> <?php $title = metadata($collection, array('Dublin Core', 'Title')); $queryParams = array( 'collection' => $collection->id, 'sort_field' => 'Dublin Core,Title' ); echo link_to('items', 'browse', $title, array(), $queryParams); ?> </h3> <?php if ($description = metadata($collection, array('Dublin Core', 'Description'))): ?> <p><?php echo $description; ?></p> <?php endif; ?> <h4>Browse Sub-Collections</h4> <ul> <?php foreach (metadata($collection, array('Dublin Core', 'Subject'), array('all' => true)) as $subject): ?> <li> <?php $queryParams = array( 'tags' => $subject, 'collection' => $collection->id, 'sort_field' => 'Dublin Core,Title' ); echo link_to('items', 'browse', $subject, array(), $queryParams); ?> </li> <?php endforeach; ?> </ul> </div> <?php endforeach; ?> </div>
Load namespaced Celery configuration in healthcheck In bed52d9c60b00be751a6a9a6fc78b333fc5bccf6, I had to change the configuration to be compatible with Django. I completely missed this part. Unfortunately, the test for this module starts with mocking the `get_stats()` function, where this code exists, so I am at loss at how to test this. For now, I think we can expose `/healthcheck.json` on the staging environment which would have helped detect this problem. In the long-term, we will use a separate healthcheck for the worker processes. There is still the question whether the "webapp" can connect to the "broker" which I feel could be tackled by this app's healthcheck. Thoughts for later, I suppose.
from django.conf import settings from moj_irat.healthchecks import HealthcheckResponse, UrlHealthcheck, registry def get_stats(): from celery import Celery app = Celery("laalaa") app.config_from_object("django.conf:settings", namespace="CELERY") return app.control.inspect().stats() class CeleryWorkersHealthcheck(object): def __init__(self, name): self.name = name def __call__(self, *args, **kwargs): try: stats = get_stats() if not stats: return self.error_response("No running workers were found.") workers = stats.values() if not workers: return self.error_response("No workers running.") except IOError as e: msg = str(e) msg += ". Check that the message broker is running." return self.error_response(msg) except ImportError as e: return self.error_response(str(e)) return self.success_response() def error_response(self, error): return HealthcheckResponse(self.name, False, error=error) def success_response(self): return HealthcheckResponse(self.name, True) registry.register_healthcheck( UrlHealthcheck(name="postcodes.io", url="{}/postcodes/SW1A1AA".format(settings.POSTCODES_IO_URL)) ) registry.register_healthcheck(CeleryWorkersHealthcheck(name="workers"))
from django.conf import settings from moj_irat.healthchecks import HealthcheckResponse, UrlHealthcheck, registry def get_stats(): from celery import Celery app = Celery("laalaa") app.config_from_object("django.conf:settings") return app.control.inspect().stats() class CeleryWorkersHealthcheck(object): def __init__(self, name): self.name = name def __call__(self, *args, **kwargs): try: stats = get_stats() if not stats: return self.error_response("No running workers were found.") workers = stats.values() if not workers: return self.error_response("No workers running.") except IOError as e: msg = str(e) msg += ". Check that the message broker is running." return self.error_response(msg) except ImportError as e: return self.error_response(str(e)) return self.success_response() def error_response(self, error): return HealthcheckResponse(self.name, False, error=error) def success_response(self): return HealthcheckResponse(self.name, True) registry.register_healthcheck( UrlHealthcheck(name="postcodes.io", url="{}/postcodes/SW1A1AA".format(settings.POSTCODES_IO_URL)) ) registry.register_healthcheck(CeleryWorkersHealthcheck(name="workers"))
Set cov-core dependency to 1.10
import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='[email protected]', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.10'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing'])
import setuptools setuptools.setup(name='pytest-cov', version='1.6', description='py.test plugin for coverage reporting with ' 'support for both centralised and distributed testing, ' 'including subprocesses and multiprocessing', long_description=open('README.rst').read().strip(), author='Marc Schlaich', author_email='[email protected]', url='https://github.com/schlamar/pytest-cov', py_modules=['pytest_cov'], install_requires=['pytest>=2.5.2', 'cov-core>=1.9'], entry_points={'pytest11': ['pytest_cov = pytest_cov']}, license='MIT License', zip_safe=False, keywords='py.test pytest cover coverage distributed parallel', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2.4', 'Programming Language :: Python :: 2.5', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.0', 'Programming Language :: Python :: 3.1', 'Topic :: Software Development :: Testing'])
Remove redundant item from test config
"use strict"; module.exports = function( grunt ) { grunt.initConfig({ jscs: { fail: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/fail.json" } }, broken: { files: { src: [ "../fixtures/broken.js", "../fixtures/fixture.js" ] }, options: { config: "../configs/fail.json", force: true } }, force: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/fail.json", force: true } }, success: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/success.json" } }, inline: { files: { src: "../fixtures/fixture.js" }, options: { "requireCurlyBraces": [ "while" ], force: true } } } }); grunt.loadTasks( "../../tasks" ); grunt.registerTask( "default", "jscs" ); };
"use strict"; module.exports = function( grunt ) { grunt.initConfig({ jscs: { fail: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/fail.json" } }, broken: { files: { src: [ "../fixtures/broken.js", "../fixtures/fixture.js", "../fixtures/fixture.js" ] }, options: { config: "../configs/fail.json", force: true } }, force: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/fail.json", force: true } }, success: { files: { src: "../fixtures/fixture.js" }, options: { config: "../configs/success.json" } }, inline: { files: { src: "../fixtures/fixture.js" }, options: { "requireCurlyBraces": [ "while" ], force: true } } } }); grunt.loadTasks( "../../tasks" ); grunt.registerTask( "default", "jscs" ); };
Fix error on Firefox 6 where pages are not open if this preference is True (default).
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from selenium.webdriver import Firefox from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement from splinter.driver.webdriver.cookie_manager import CookieManager class WebDriver(BaseWebDriver): def __init__(self, profile=None, extensions=None): self.old_popen = subprocess.Popen firefox_profile = FirefoxProfile(profile) firefox_profile.set_preference('extensions.logging.enabled', False) firefox_profile.set_preference('network.dns.disableIPv6', False) if extensions: for extension in extensions: firefox_profile.add_extension(extension) self._patch_subprocess() self.driver = Firefox(firefox_profile) self._unpatch_subprocess() self.element_class = WebDriverElement self._cookie_manager = CookieManager(self.driver) super(WebDriver, self).__init__() class WebDriverElement(BaseWebDriverElement): def mouseover(self): """ Firefox doesn't support mouseover. """ raise NotImplementedError("Firefox doesn't support mouse over") def mouseout(self): """ Firefox doesn't support mouseout. """ raise NotImplementedError("Firefox doesn't support mouseout") def double_click(self): """ Firefox doesn't support doubleclick. """ raise NotImplementedError("Firefox doesn't support doubleclick")
#!/usr/bin/env python # -*- coding: utf-8 -*- import subprocess from selenium.webdriver import Firefox from selenium.webdriver.firefox.firefox_profile import FirefoxProfile from splinter.driver.webdriver import BaseWebDriver, WebDriverElement as BaseWebDriverElement from splinter.driver.webdriver.cookie_manager import CookieManager class WebDriver(BaseWebDriver): def __init__(self, profile=None, extensions=None): self.old_popen = subprocess.Popen firefox_profile = FirefoxProfile(profile) firefox_profile.set_preference('extensions.logging.enabled', False) if extensions: for extension in extensions: firefox_profile.add_extension(extension) self._patch_subprocess() self.driver = Firefox(firefox_profile) self._unpatch_subprocess() self.element_class = WebDriverElement self._cookie_manager = CookieManager(self.driver) super(WebDriver, self).__init__() class WebDriverElement(BaseWebDriverElement): def mouseover(self): """ Firefox doesn't support mouseover. """ raise NotImplementedError("Firefox doesn't support mouse over") def mouseout(self): """ Firefox doesn't support mouseout. """ raise NotImplementedError("Firefox doesn't support mouseout") def double_click(self): """ Firefox doesn't support doubleclick. """ raise NotImplementedError("Firefox doesn't support doubleclick")
Update fenced block parsing for spec change See commonmark/commonmark.js@59980020
<?php /* * This file is part of the league/commonmark package. * * (c) Colin O'Dell <[email protected]> * * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\CommonMark\Block\Parser; use League\CommonMark\Block\Element\FencedCode; use League\CommonMark\ContextInterface; use League\CommonMark\Cursor; class FencedCodeParser implements BlockParserInterface { /** * @param ContextInterface $context * @param Cursor $cursor * * @return bool */ public function parse(ContextInterface $context, Cursor $cursor): bool { if ($cursor->isIndented()) { return false; } $indent = $cursor->getIndent(); $fence = $cursor->match('/^[ \t]*(?:`{3,}(?!.*`)|^~{3,})/'); if ($fence === null) { return false; } // fenced code block $fence = \ltrim($fence, " \t"); $fenceLength = \strlen($fence); $context->addBlock(new FencedCode($fenceLength, $fence[0], $indent)); return true; } }
<?php /* * This file is part of the league/commonmark package. * * (c) Colin O'Dell <[email protected]> * * Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) * - (c) John MacFarlane * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace League\CommonMark\Block\Parser; use League\CommonMark\Block\Element\FencedCode; use League\CommonMark\ContextInterface; use League\CommonMark\Cursor; class FencedCodeParser implements BlockParserInterface { /** * @param ContextInterface $context * @param Cursor $cursor * * @return bool */ public function parse(ContextInterface $context, Cursor $cursor): bool { if ($cursor->isIndented()) { return false; } $indent = $cursor->getIndent(); $fence = $cursor->match('/^[ \t]*(?:`{3,}(?!.*`)|^~{3,}(?!.*~))/'); if ($fence === null) { return false; } // fenced code block $fence = \ltrim($fence, " \t"); $fenceLength = \strlen($fence); $context->addBlock(new FencedCode($fenceLength, $fence[0], $indent)); return true; } }
Make <PromptBuffer> a special case of <Prompt>
// @flow import * as React from "react"; /** * Generate what text goes inside the prompt based on the props to the prompt */ export function promptText(props: PromptProps): string { if (props.running) { return "[*]"; } if (props.queued) { return "[…]"; } if (typeof props.counter === "number") { return `[${props.counter}]`; } return "[ ]"; } type PromptProps = { counter: number | null, running: boolean, queued: boolean, blank: boolean }; export class Prompt extends React.Component<PromptProps, null> { static defaultProps = { counter: null, running: false, queued: false, blank: false }; render() { return ( <React.Fragment> <div className="prompt"> {this.props.blank ? null : promptText(this.props)} </div> <style jsx>{` .prompt { font-family: monospace; font-size: 12px; line-height: 22px; width: var(--prompt-width, 50px); padding: 9px 0; text-align: center; color: var(--theme-cell-prompt-fg, black); background-color: var(--theme-cell-prompt-bg, #fafafa); } `}</style> </React.Fragment> ); } } export const PromptBuffer = () => <Prompt blank />;
// @flow import * as React from "react"; import css from "styled-jsx/css"; const promptStyle = css` .prompt { font-family: monospace; font-size: 12px; line-height: 22px; width: var(--prompt-width, 50px); padding: 9px 0; text-align: center; color: var(--theme-cell-prompt-fg, black); background-color: var(--theme-cell-prompt-bg, #fafafa); } `; // Totally fake component for consistency with indents of the editor area export function promptText(props: PromptProps) { if (props.running) { return "[*]"; } if (props.queued) { return "[…]"; } if (typeof props.counter === "number") { return `[${props.counter}]`; } return "[ ]"; } type PromptProps = { counter: number | null, running: boolean, queued: boolean }; export class Prompt extends React.Component<PromptProps, null> { static defaultProps = { counter: null, running: false, queued: false }; render() { return ( <React.Fragment> <div className="prompt">{promptText(this.props)}</div> <style jsx>{promptStyle}</style> </React.Fragment> ); } } export class PromptBuffer extends React.Component<any, null> { render() { return ( <React.Fragment> <div className="prompt" /> <style jsx>{promptStyle}</style> </React.Fragment> ); } }
Put a tool tip on the first player token.
"use strict"; define(["create-react-class", "prop-types", "react-dom-factories"], function(createReactClass, PropTypes, DOM) { var AgentLabel = createReactClass( { render: function() { var firstAgentToken = DOM.div( { className: (this.props.isFirstAgent ? "" : "dn"), title: "First Player", }, DOM.img( { className: "dtc tc", src: this.props.resourceBase + "token/FirstPlayerToken32.png", })); var label = DOM.div( { key: "agentLabel", className: "b dtc f5 tc v-mid", }, "Agent: " + this.props.agentName); var threat = DOM.div( { key: "agentThreat", className: "b dtc f5 tc v-mid", }, "Threat Level: " + this.props.threatLevel); var panel = DOM.div( { key: "panel", className: "bg-lotr-dark dt lotr-light w-100", }, firstAgentToken, label, threat); return DOM.div( { key: "agentLabel", }, panel); }, }); AgentLabel.propTypes = { agentName: PropTypes.string.isRequired, isFirstAgent: PropTypes.bool.isRequired, resourceBase: PropTypes.string.isRequired, threatLevel: PropTypes.number.isRequired, }; return AgentLabel; });
"use strict"; define(["create-react-class", "prop-types", "react-dom-factories"], function(createReactClass, PropTypes, DOM) { var AgentLabel = createReactClass( { render: function() { var firstAgentToken = DOM.div( { className: (this.props.isFirstAgent ? "" : "dn"), }, DOM.img( { className: "dtc tc", src: this.props.resourceBase + "token/FirstPlayerToken32.png", })); var label = DOM.div( { key: "agentLabel", className: "b dtc f5 tc v-mid", }, "Agent: " + this.props.agentName); var threat = DOM.div( { key: "agentThreat", className: "b dtc f5 tc v-mid", }, "Threat Level: " + this.props.threatLevel); var panel = DOM.div( { key: "panel", className: "bg-lotr-dark dt lotr-light w-100", }, firstAgentToken, label, threat); return DOM.div( { key: "agentLabel", }, panel); }, }); AgentLabel.propTypes = { agentName: PropTypes.string.isRequired, isFirstAgent: PropTypes.bool.isRequired, resourceBase: PropTypes.string.isRequired, threatLevel: PropTypes.number.isRequired, }; return AgentLabel; });
webhooks/dialogflow: Remove default value for email parameter. The webhook view used a default value for the email, which gave non-informative errors when the webhook is incorrectly configured without the email parameter.
# Webhooks for external integrations. from typing import Any, Dict from django.http import HttpRequest, HttpResponse from zerver.decorator import api_key_only_webhook_view from zerver.lib.actions import check_send_private_message from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.models import UserProfile, get_user_profile_by_email @api_key_only_webhook_view("dialogflow") @has_request_variables def api_dialogflow_webhook(request: HttpRequest, user_profile: UserProfile, payload: Dict[str, Any]=REQ(argument_type='body'), email: str=REQ()) -> HttpResponse: status = payload["status"]["code"] if status == 200: result = payload["result"]["fulfillment"]["speech"] if not result: alternate_result = payload["alternateResult"]["fulfillment"]["speech"] if not alternate_result: body = "DialogFlow couldn't process your query." else: body = alternate_result else: body = result else: error_status = payload["status"]["errorDetails"] body = "{} - {}".format(status, error_status) profile = get_user_profile_by_email(email) check_send_private_message(user_profile, request.client, profile, body) return json_success()
# Webhooks for external integrations. from typing import Any, Dict from django.http import HttpRequest, HttpResponse from zerver.decorator import api_key_only_webhook_view from zerver.lib.actions import check_send_private_message from zerver.lib.request import REQ, has_request_variables from zerver.lib.response import json_success from zerver.models import UserProfile, get_user_profile_by_email @api_key_only_webhook_view("dialogflow") @has_request_variables def api_dialogflow_webhook(request: HttpRequest, user_profile: UserProfile, payload: Dict[str, Any]=REQ(argument_type='body'), email: str=REQ(default='foo')) -> HttpResponse: status = payload["status"]["code"] if status == 200: result = payload["result"]["fulfillment"]["speech"] if not result: alternate_result = payload["alternateResult"]["fulfillment"]["speech"] if not alternate_result: body = "DialogFlow couldn't process your query." else: body = alternate_result else: body = result else: error_status = payload["status"]["errorDetails"] body = "{} - {}".format(status, error_status) profile = get_user_profile_by_email(email) check_send_private_message(user_profile, request.client, profile, body) return json_success()
Fix undefined reported as error on fetch configuration
import { connect } from './wsActions' import { setDashboards, play, } from './dashboardsActions' import { notifySuccess, notifyError, } from './notificationsActions' export const FETCH_CONFIGURATION = 'FETCH_CONFIGURATION' export const FETCH_CONFIGURATION_SUCCESS = 'FETCH_CONFIGURATION_SUCCESS' export const FETCH_CONFIGURATION_FAILURE = 'FETCH_CONFIGURATION_FAILURE' export const fetchConfigurationSuccess = configuration => ({ type: FETCH_CONFIGURATION_SUCCESS, configuration, }) const fetchConfigurationFailure = error => ({ type: FETCH_CONFIGURATION_FAILURE, error, }) export const fetchConfiguration = () => { return dispatch => { dispatch({ type: FETCH_CONFIGURATION }) // http://localhost:5000/config return fetch('/config') .then(res => { if (res.status !== 200) { return Promise.reject(new Error( `Unable to fetch configuration: ${res.statusText} (${res.status})`)) } return res.json() }) .then(configuration => { dispatch(fetchConfigurationSuccess(configuration)) dispatch(connect(configuration)) dispatch(notifySuccess({ message: 'configuration loaded', ttl: 2000, })) dispatch(setDashboards(configuration.dashboards)) dispatch(play()) }) .catch(err => { dispatch(notifyError({ message: `An error occurred while fetching configuration: ${err.message}`, ttl: -1, })) dispatch(fetchConfigurationFailure(err.message)) }) } }
import { connect } from './wsActions' import { setDashboards, play, } from './dashboardsActions' import { notifySuccess, notifyError, } from './notificationsActions' export const FETCH_CONFIGURATION = 'FETCH_CONFIGURATION' export const FETCH_CONFIGURATION_SUCCESS = 'FETCH_CONFIGURATION_SUCCESS' export const FETCH_CONFIGURATION_FAILURE = 'FETCH_CONFIGURATION_FAILURE' export const fetchConfigurationSuccess = configuration => ({ type: FETCH_CONFIGURATION_SUCCESS, configuration, }) const fetchConfigurationFailure = error => ({ type: FETCH_CONFIGURATION_FAILURE, error, }) export const fetchConfiguration = () => { return dispatch => { dispatch({ type: FETCH_CONFIGURATION }) // http://localhost:5000/config return fetch('/config') .then(res => { if (res.status !== 200) { return Promise.reject(`Unable to fetch configuration: ${res.statusText} (${res.status})`) } return res.json() }) .then(configuration => { dispatch(fetchConfigurationSuccess(configuration)) dispatch(connect(configuration)) dispatch(notifySuccess({ message: 'configuration loaded', ttl: 2000, })) dispatch(setDashboards(configuration.dashboards)) dispatch(play()) }) .catch(err => { dispatch(notifyError({ message: `An error occurred while fetching configuration: ${err.message}`, ttl: -1, })) dispatch(fetchConfigurationFailure(err.message)) }) } }
Format date when tooltip template is used.
define(['moment', 'nvd3', 'underscore', 'views/chart-view'], function(moment, nvd3, _, ChartView) { 'use strict'; /** * TrendsView renders several threads of timeline data over a period of * time on the x axis. */ var TrendsView = ChartView.extend({ defaults: _.extend({}, ChartView.prototype.defaults, { showLegend: false }), getChart: function() { return nvd3.models.lineChart(); }, initChart: function(chart) { var self = this; ChartView.prototype.initChart.call(this, chart); chart.showLegend(this.options.showLegend) .useInteractiveGuideline(true); if (_(self.options).has('interactiveTooltipHeaderTemplate')) { self.chart.interactiveLayer.tooltip.headerFormatter(function(d) { return self.options.interactiveTooltipHeaderTemplate({value: self.formatXTick(d)}); }); } }, formatXTick: function(d) { // overriding default to display a formatted date return moment.utc(d).format('D MMM YYYY'); }, parseXData: function(d) { var self = this; return Date.parse(d[self.options.x.key]); } }); return TrendsView; } );
define(['moment', 'nvd3', 'underscore', 'views/chart-view'], function(moment, nvd3, _, ChartView) { 'use strict'; /** * TrendsView renders several threads of timeline data over a period of * time on the x axis. */ var TrendsView = ChartView.extend({ defaults: _.extend({}, ChartView.prototype.defaults, { showLegend: false }), getChart: function() { return nvd3.models.lineChart(); }, initChart: function(chart) { var self = this; ChartView.prototype.initChart.call(this, chart); chart.showLegend(this.options.showLegend) .useInteractiveGuideline(true); if (_(self.options).has('interactiveTooltipHeaderTemplate')) { self.chart.interactiveLayer.tooltip.headerFormatter(function(d) { return self.options.interactiveTooltipHeaderTemplate({value: d}); }); } }, formatXTick: function(d) { // overriding default to display a formatted date return moment.utc(d).format('D MMM YYYY'); }, parseXData: function(d) { var self = this; return Date.parse(d[self.options.x.key]); } }); return TrendsView; } );
Add backbone.hal to js module config.
requirejs.config({ baseUrl: '/static', paths: { antibodies: 'modules/antibodies', app: 'modules/app', assert: 'modules/assert', base: 'modules/base', home: 'modules/home', navbar: 'modules/navbar', // Plugins text: 'libs/text', // Libraries backbone: 'libs/backbone', 'backbone.hal': 'libs/backbone.hal', bootstrap: 'libs/bootstrap.min', jquery: 'libs/jquery.min', modernizr: 'libs/modernizr.min', underscore: 'libs/underscore.min' }, shim: { backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, bootstrap: { deps: ['jquery'] }, // Modernizr loads later than normal with Require.js, so don't use the // new HTML5 elements in the HTML file itself. modernizr: { exports: 'Modernizr' }, underscore: { exports: '_' } } }); if (!window.TESTRUNNER) require(['jquery', 'app', 'bootstrap', 'modernizr'], function main($, app) { // Treat the jQuery ready function as the entry point to the application. // Inside this function, kick-off all initialization, everything up to this // point should be definitions. $(function ready() { app.start(); // Simplify debugging window.app = app; }); });
requirejs.config({ baseUrl: '/static', paths: { antibodies: 'modules/antibodies', app: 'modules/app', assert: 'modules/assert', base: 'modules/base', home: 'modules/home', navbar: 'modules/navbar', // Plugins text: 'libs/text', // Libraries backbone: 'libs/backbone', bootstrap: 'libs/bootstrap.min', jquery: 'libs/jquery.min', modernizr: 'libs/modernizr.min', underscore: 'libs/underscore.min' }, shim: { backbone: { deps: ['underscore', 'jquery'], exports: 'Backbone' }, bootstrap: { deps: ['jquery'] }, // Modernizr loads later than normal with Require.js, so don't use the // new HTML5 elements in the HTML file itself. modernizr: { exports: 'Modernizr' }, underscore: { exports: '_' } } }); if (!window.TESTRUNNER) require(['jquery', 'app', 'bootstrap', 'modernizr'], function main($, app) { // Treat the jQuery ready function as the entry point to the application. // Inside this function, kick-off all initialization, everything up to this // point should be definitions. $(function ready() { app.start(); // Simplify debugging window.app = app; }); });
Use getRecord to get a record in unit test
<?php /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Handler; use Monolog\Logger; use Monolog\TestCase; class ZendMonitorHandlerTest extends TestCase { protected $zendMonitorHandler; public function setUp() { if (!function_exists('zend_monitor_custom_event')) { $this->markTestSkipped('ZendServer is not installed'); } } /** * @covers \Monolog\Handler\ZendMonitor::__construct * @covers \Monolog\Handler\ZendMonitor::isZendServer */ public function testIsZendServerReturnsTrue() { $zendMonitor = new ZendMonitorHandler(); $this->assertTrue($zendMonitor->isZendServer()); } /** * @covers \Monolog\Handler\ZendMonitor::write */ public function testWrite() { $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler') ->setMethods(array('writeZendMonitorCustomEvent')) ->getMock(); $zendMonitor->expects($this->once()) ->method('writeZendMonitorCustomEvent'); $zendMonitor->handle($this->getRecord()); } }
<?php /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <[email protected]> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Monolog\Handler; use Monolog\Logger; use Monolog\TestCase; class ZendMonitorHandlerTest extends TestCase { protected $zendMonitorHandler; public function setUp() { if (!function_exists('zend_monitor_custom_event')) { $this->markTestSkipped('ZendServer is not installed'); } } /** * @covers \Monolog\Handler\ZendMonitor::__construct * @covers \Monolog\Handler\ZendMonitor::isZendServer */ public function testIsZendServerReturnsTrue() { $zendMonitor = new ZendMonitorHandler(); $this->assertTrue($zendMonitor->isZendServer()); } /** * @covers \Monolog\Handler\ZendMonitor::write */ public function testWrite() { $zendMonitor = $this->getMockBuilder('Monolog\Handler\ZendMonitorHandler') ->setMethods(array('writeZendMonitorCustomEvent')) ->getMock(); $zendMonitor->expects($this->once()) ->method('writeZendMonitorCustomEvent'); $zendMonitor->handle( array( 'message' => 'addDebug Message', 'context' => array(), 'level' => Logger::DEBUG, 'level_name' => 'DEBUG', 'channel' => 'zendmonitor', 'extra' => array(), 'formatted' => '[2013-01-30 19:07:32] zendmonitor.DEBUG: addDebug Message [] []' ) ); } }
Fix path to setup file on windows
/* * mocaccino.js * * Copyright (c) 2014 Maximilian Antoni <[email protected]> * * @license MIT */ 'use strict'; var through = require('through'); var resolve = require('resolve'); var path = require('path'); var fs = require('fs'); module.exports = function (b, opts) { if (!opts) { opts = {}; } var reporter = opts.reporter || opts.R || 'tap'; var yields = opts.yields || opts.y || 250; var setupFile; if (opts.node) { b.exclude('mocha'); setupFile = 'setup-node.js'; } else { b.noParse(require.resolve('mocha/mocha')); setupFile = 'setup-browser.js'; } setupFile = path.join(__dirname, setupFile); // Transform must be global to make sure it is applied last: b.transform({ global : true }, function (file) { if (file === setupFile) { var content = ''; return through(function (buf) { content += buf; }, function () { this.queue(content.replace('{{REPORTER}}', reporter) .replace('{{YIELDS}}', yields)); this.queue(null); }); } if (b.files.indexOf(file) === -1) { return through(); } return through(function (data) { this.queue('require(' + JSON.stringify(setupFile) + ');'); this.queue(data); }); }); };
/* * mocaccino.js * * Copyright (c) 2014 Maximilian Antoni <[email protected]> * * @license MIT */ 'use strict'; var through = require('through'); var resolve = require('resolve'); var path = require('path'); var fs = require('fs'); module.exports = function (b, opts) { if (!opts) { opts = {}; } var reporter = opts.reporter || opts.R || 'tap'; var yields = opts.yields || opts.y || 250; var setupFile; if (opts.node) { b.exclude('mocha'); setupFile = 'setup-node.js'; } else { b.noParse(require.resolve('mocha/mocha')); setupFile = 'setup-browser.js'; } setupFile = path.join(__dirname, setupFile); // Transform must be global to make sure it is applied last: b.transform({ global : true }, function (file) { if (file === setupFile) { var content = ''; return through(function (buf) { content += buf; }, function () { this.queue(content.replace('{{REPORTER}}', reporter) .replace('{{YIELDS}}', yields)); this.queue(null); }); } if (b.files.indexOf(file) === -1) { return through(); } return through(function (data) { this.queue('require("' + setupFile + '");'); this.queue(data); }); }); };
Add custom JSON serialize for Python datetime This adds a custom JSON serializer class which stringifies Python datetime objects in to ISO 8601. JSON does not specify a date/time format, and many parsers break trying to parse a Date() javascript object. 8601 seems a resonable compromise.
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json class encoder( json.JSONEncoder ): # JSON Serializer with datetime support def default(self,obj): if isinstance(obj, datetime.datetime): return obj.isoformat() return json.JSONEncoder.default( self,obj) from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result},cls=encoder)) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
from functools import partial from pyws.errors import BadRequest from pyws.functions.args.types.complex import List from pyws.response import Response from pyws.utils import json from pyws.protocols.base import Protocol __all__ = ('RestProtocol', 'JsonProtocol', ) create_response = partial(Response, content_type='application/json') create_error_response = partial(create_response, status=Response.STATUS_ERROR) class RestProtocol(Protocol): name = 'rest' def get_function(self, request): return request.tail def get_arguments(self, request, arguments): result = {} for field in arguments.fields: value = request.GET.get(field.name) if issubclass(field.type, List): result[field.name] = value elif field.name in request.GET: result[field.name] = value[0] return result def get_response(self, result, name, return_type): return create_response(json.dumps({'result': result})) def get_error_response(self, error): return create_error_response( json.dumps({'error': self.get_error(error)})) class JsonProtocol(RestProtocol): name = 'json' def get_arguments(self, request, arguments): try: return json.loads(request.text) except ValueError: raise BadRequest()
Add placeable to javascript context
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChanged(self): print "-----------------------------------" ent = r.getEntity(self.comp.GetParentEntityId()) datastr = self.comp.GetAttribute() #print "GetAttr got:", datastr data = json.loads(datastr) js_src = data.get('js_src', None) if not self.jsloaded and js_src is not None: jscode = self.loadjs(js_src) print jscode ctx = { #'entity'/'this': self.entity 'component': self.comp } try: ent.touchable except AttributeError: pass else: ctx['touchable'] = ent.touchable try: ent.placeable except: pass else: ctx['placeable'] = ent.placeable naali.runjs(jscode, ctx) print "-- done with js" self.jsloaded = True def loadjs(self, srcurl): print "js source url:", srcurl f = urllib2.urlopen(srcurl) return f.read()
import json import rexviewer as r import naali import urllib2 from componenthandler import DynamiccomponentHandler class JavascriptHandler(DynamiccomponentHandler): GUINAME = "Javascript Handler" def __init__(self): DynamiccomponentHandler.__init__(self) self.jsloaded = False def onChanged(self): print "-----------------------------------" ent = r.getEntity(self.comp.GetParentEntityId()) datastr = self.comp.GetAttribute() #print "GetAttr got:", datastr data = json.loads(datastr) js_src = data.get('js_src', None) if not self.jsloaded and js_src is not None: jscode = self.loadjs(js_src) print jscode ctx = { #'entity'/'this': self.entity 'component': self.comp } try: ent.touchable except AttributeError: pass else: ctx['touchable'] = ent.touchable naali.runjs(jscode, ctx) print "-- done with js" self.jsloaded = True def loadjs(self, srcurl): print "js source url:", srcurl f = urllib2.urlopen(srcurl) return f.read()
Support updating rather than recreate for domains
import React from 'react' import shallowEqual from 'shallowequal' export const withDomain = ({ domainClass, mapPropsToArg, mapPropsToArgsArray = props => mapPropsToArg ? [mapPropsToArg(props)] : [], createDomain = props => new domainClass(...mapPropsToArgsArray(props)), // eslint-disable-line new-cap propName = 'domain', shouldRecreateDomain = (currentProps, nextProps) => ! shallowEqual(mapPropsToArgsArray(currentProps), mapPropsToArgsArray(nextProps)), }) => Component => class DomainProvider extends React.Component { domain componentWillMount() { this.domain = createDomain(this.props) } componentWillUpdate(nextProps) { if (shouldRecreateDomain(this.props, nextProps)) { this.stop() this.domain = createDomain(nextProps) } else if (this.domain && typeof this.domain.update === 'function') { this.domain.update(...mapPropsToArgsArray(nextProps)) } } componentWillUnmount() { this.stop() this.domain = null } stop() { if (this.domain && typeof this.domain.stop === 'function') { this.domain.stop() } } render() { return React.createElement(Component, { ...this.props, [propName]: this.domain }) } }
import React from 'react' import shallowEqual from 'shallowequal' export const withDomain = ({ domainClass, mapPropsToArg, mapPropsToArgsArray = props => mapPropsToArg ? [mapPropsToArg(props)] : [], createDomain = props => new domainClass(...mapPropsToArgsArray(props)), // eslint-disable-line new-cap propName = 'domain', shouldRecreateDomain = (currentProps, nextProps) => ! shallowEqual(mapPropsToArgsArray(currentProps), mapPropsToArgsArray(nextProps)), }) => Component => class DomainProvider extends React.Component { domain componentWillMount() { this.domain = createDomain(this.props) } componentWillUpdate(nextProps) { if (shouldRecreateDomain(this.props, nextProps)) { this.stop() this.domain = createDomain(nextProps) } else if (this.domain && typeof this.domain.update === 'function') { this.domain.update(nextProps) } } componentWillUnmount() { this.stop() this.domain = null } stop() { if (this.domain && typeof this.domain.stop === 'function') { this.domain.stop() } } render() { return React.createElement(Component, { ...this.props, [propName]: this.domain }) } }
Fix merging objects with prototypes
function clone(obj) { return Object.setPrototypeOf(Object.assign({}, obj), Object.getPrototypeOf(obj)); } function merge(...args) { let output = null, items = [...args]; while (items.length > 0) { const nextItem = items.shift(); if (!output) { output = clone(nextItem); } else { output = mergeObjects(output, nextItem); } } return output; } function mergeObjects(obj1, obj2) { const output = clone(obj1); Object.keys(obj2).forEach(key => { if (!output.hasOwnProperty(key)) { output[key] = obj2[key]; return; } if (Array.isArray(obj2[key])) { output[key] = Array.isArray(output[key]) ? [...output[key], ...obj2[key]] : [...obj2[key]]; } else if (typeof obj2[key] === "object" && !!obj2[key]) { output[key] = typeof output[key] === "object" && !!output[key] ? mergeObjects(output[key], obj2[key]) : clone(obj2[key]); } else { output[key] = obj2[key]; } }); return output; } module.exports = { merge };
function merge(...args) { let output = null, items = [...args]; while (items.length > 0) { const nextItem = items.shift(); if (!output) { output = Object.assign({}, nextItem); } else { output = mergeObjects(output, nextItem); } } return output; } function mergeObjects(obj1, obj2) { const output = Object.assign({}, obj1); Object.keys(obj2).forEach(key => { if (!output.hasOwnProperty(key)) { output[key] = obj2[key]; return; } if (Array.isArray(obj2[key])) { output[key] = Array.isArray(output[key]) ? [...output[key], ...obj2[key]] : [...obj2[key]]; } else if (typeof obj2[key] === "object" && !!obj2[key]) { output[key] = typeof output[key] === "object" && !!output[key] ? mergeObjects(output[key], obj2[key]) : Object.assign({}, obj2[key]); } else { output[key] = obj2[key]; } }); return output; } module.exports = { merge };
Add slugify with / _ support
<?php namespace Metrique\Building\Contracts; interface PageRepositoryInterface { /** * Get all pages. * @return Illuminate\Support\Collection */ public function all(); /** * Find a page. * @return mixed */ public function find($id); /** * Create a page from an array. * @return mixed */ public function create(array $data); /** * Create a page from the request object. * @return mixed */ public function createWithRequest(); /** * Destroy a page. * @param int $id * @return mixed */ public function destroy($id); /** * Update a page from an array. * @return mixed */ public function update($id, array $data); /** * Create a page from the request object. * @return mixed */ public function updateWithRequest($id); /** * Get the page and meta by slug. * @param strint $slug * @return mixed */ public function bySlug($slug); /** * Get the page and full formatted content by slug. * @param string $slug * @return $mixed */ public function contentBySlug($slug); /** * Converts a string to slug/url format. * Underscore represents a path separator. * Dash is used as a word separator. * * @param $string * @param string $delimiter * @param string $directorySeparator * @return string */ public function slugify($string, $delimiter = '-', $directorySeparator = '_'); /** * Converts a slug back to a path. * * @param string $string * @return string */ public function unslugify($string, $directorySeparator = '_'); }
<?php namespace Metrique\Building\Contracts; interface PageRepositoryInterface { /** * Get all pages. * @return Illuminate\Support\Collection */ public function all(); /** * Find a page. * @return mixed */ public function find($id); /** * Create a page from an array. * @return mixed */ public function create(array $data); /** * Create a page from the request object. * @return mixed */ public function createWithRequest(); /** * Destroy a page. * @param int $id * @return mixed */ public function destroy($id); /** * Update a page from an array. * @return mixed */ public function update($id, array $data); /** * Create a page from the request object. * @return mixed */ public function updateWithRequest($id); /** * Get the page and meta by slug. * @param strint $slug * @return mixed */ public function bySlug($slug); /** * Get the page and full formatted content by slug. * @param string $slug * @return $mixed */ public function contentBySlug($slug); /** * Get meta data from page meta json. * For this to be populated the bySlug($slug) method should be called first. * By default this will return a blank string. * * @param string * @return string */ public function getMeta($key); }
fix(Loaders): Make css loader rule work on *all* css files.
module.exports = [ { test: /\.svg$/, loader: 'svg-sprite', exclude: /fonts/, },{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=60000&mimetype=application/font-woff', },{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=60000', include: /fonts/, },{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192', },{ test: /\.css$/, loader: 'style!css!postcss', },{ test: /\.mcss$/, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]!postcss', },{ test: /\.c$/i, loader: "shader", },{ test: /\.json$/, loader: 'json-loader', },{ test: /\.html$/, loader: 'html-loader', },{ test: /\.js$/, include: /node_modules\/paraviewweb\//, loader: 'babel?presets[]=es2015,presets[]=react', },{ test: /\.js$/, exclude: /node_modules/, loader: 'babel?presets[]=es2015,presets[]=react', }, ]
module.exports = [ { test: /\.svg$/, loader: 'svg-sprite', exclude: /fonts/, },{ test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=60000&mimetype=application/font-woff', },{ test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: 'url-loader?limit=60000', include: /fonts/, },{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192', },{ test: /\.css$/, include: /node_modules/, loader: 'style!css!postcss', },{ test: /\.mcss$/, loader: 'style!css?modules&importLoaders=1&localIdentName=[name]_[local]_[hash:base64:5]!postcss', },{ test: /\.c$/i, loader: "shader", },{ test: /\.json$/, loader: 'json-loader', },{ test: /\.html$/, loader: 'html-loader', },{ test: /\.js$/, include: /node_modules\/paraviewweb\//, loader: 'babel?presets[]=es2015,presets[]=react', },{ test: /\.js$/, exclude: /node_modules/, loader: 'babel?presets[]=es2015,presets[]=react', }, ]
Fix bug in VectorName, caused by new Command arguments
# -*- coding: utf-8 -*- """ pylatex.numpy ~~~~~~~~~~~~~ This module implements the classes that deals with numpy objects. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ import numpy as np from pylatex.base_classes import BaseLaTeXClass from pylatex.package import Package from pylatex.command import Command class VectorName(Command): def __init__(self, name): super().__init__('mathbf', arguments=name) class Matrix(BaseLaTeXClass): def __init__(self, matrix, name='', mtype='p', alignment=None): self.mtype = mtype self.matrix = matrix self.alignment = alignment self.name = name super().__init__(packages=[Package('amsmath')]) def dumps(self): string = r'\begin{' mtype = self.mtype + 'matrix' if self.alignment is not None: mtype += '*' alignment = '{' + self.alignment + '}' else: alignment = '' string += mtype + '}' + alignment string += '\n' shape = self.matrix.shape for (y, x), value in np.ndenumerate(self.matrix): if x: string += '&' string += str(value) if x == shape[1] - 1 and y != shape[0] - 1: string += r'\\' + '\n' string += '\n' string += r'\end{' + mtype + '}' super().dumps() return string
# -*- coding: utf-8 -*- """ pylatex.numpy ~~~~~~~~~~~~~ This module implements the classes that deals with numpy objects. :copyright: (c) 2014 by Jelte Fennema. :license: MIT, see License for more details. """ import numpy as np from pylatex.base_classes import BaseLaTeXClass from pylatex.package import Package from pylatex.command import Command class VectorName(Command): def __init__(self, name): super().__init__('mathbf', argument=name) class Matrix(BaseLaTeXClass): def __init__(self, matrix, name='', mtype='p', alignment=None): self.mtype = mtype self.matrix = matrix self.alignment = alignment self.name = name super().__init__(packages=[Package('amsmath')]) def dumps(self): string = r'\begin{' mtype = self.mtype + 'matrix' if self.alignment is not None: mtype += '*' alignment = '{' + self.alignment + '}' else: alignment = '' string += mtype + '}' + alignment string += '\n' shape = self.matrix.shape for (y, x), value in np.ndenumerate(self.matrix): if x: string += '&' string += str(value) if x == shape[1] - 1 and y != shape[0] - 1: string += r'\\' + '\n' string += '\n' string += r'\end{' + mtype + '}' super().dumps() return string
Fix template helper errors for accounts with no payments or donations arrays in their profiles
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import './receipts.html'; Meteor.subscribe('donations'); Meteor.subscribe('purchases'); Template.receiptsList.helpers({ donations: () => { if (Meteor.user() && Meteor.user().payments instanceof Array) { return Meteor.user().payments.map((donation) => { // Subscriptions don't have descriptions if (!donation.description || /WCASA Donation/i.test(donation.description)) { return donation; } return undefined; }).filter(el => el); // remove empty items } return undefined; }, purchases: () => { if (Meteor.user() && Meteor.user().payments instanceof Array) { return Meteor.user().payments.map((purchase) => { if (purchase.description && !/WCASA Donation/i.test(purchase.description)) { return purchase; } return undefined; }).filter(el => el); // remove empty items } return undefined; }, headingDonations: 'Donations', headingPurchases: 'Purchases', noneDonations: 'No donations yet.', nonePurchases: 'No purchases have been made.', }); Template.receiptItem.helpers({ timestamp() { return this.created * 1000; }, timestampUTC() { return new Date(this.created * 1000).toISOString(); }, description() { if (this.object === 'subscription') return this.plan.nickname; return `$${this.amount / 100} ${this.description}`; }, });
import { Meteor } from 'meteor/meteor'; import { Template } from 'meteor/templating'; import './receipts.html'; Meteor.subscribe('donations'); Meteor.subscribe('purchases'); Template.receiptsList.helpers({ donations: () => { if (Meteor.user()) { return Meteor.user().payments.map((donation) => { // Subscriptions don't have descriptions if (!donation.description || /WCASA Donation/i.test(donation.description)) { return donation; } return undefined; }).filter(el => el); // remove empty items } return undefined; }, purchases: () => { if (Meteor.user()) { return Meteor.user().payments.map((purchase) => { if (purchase.description && !/WCASA Donation/i.test(purchase.description)) { return purchase; } return undefined; }).filter(el => el); // remove empty items } return undefined; }, headingDonations: 'Donations', headingPurchases: 'Purchases', noneDonations: 'No donations yet.', nonePurchases: 'No purchases have been made.', }); Template.receiptItem.helpers({ timestamp() { return this.created * 1000; }, timestampUTC() { return new Date(this.created * 1000).toISOString(); }, description() { if (this.object === 'subscription') return this.plan.nickname; return `$${this.amount / 100} ${this.description}`; }, });
Enable CORS ignore orgin header
const Hapi = require('@hapi/hapi'); const routes = require('./routes'); const auth = require('./auth'); module.exports = async (elastic, config, cb) => { const server = new Hapi.Server({ port: config.port, routes: { cors: { origin: 'ignore' }, log: { collect: true } } }); server.route(routes(elastic, config)); if (config.auth) { server.route(auth()); await server.register(require('hapi-auth-jwt2')); await server.register(require('./auth/authentication')); } try { await server.register([ { plugin: require('good'), options: { reporters: { console: [{ module: 'good-console' }, 'stdout'] } } }, require('inert'), require('vision'), require('h2o2'), { plugin: require('./routes/plugins/error'), options: { config: config } } ]); } catch (err) { return cb(err); } server.views({ engines: { html: { module: require('handlebars'), compileMode: 'sync' } }, relativeTo: __dirname, path: './templates/pages', layout: 'default', layoutPath: './templates/layouts', partialsPath: './templates/partials', helpersPath: './templates/helpers' }); cb(null, { server, elastic }); };
const Hapi = require('@hapi/hapi'); const routes = require('./routes'); const auth = require('./auth'); module.exports = async (elastic, config, cb) => { const server = new Hapi.Server({ port: config.port, routes: { cors: { origin: "ignore" }, log: { collect: true } } }); server.route(routes(elastic, config)); if (config.auth) { server.route(auth()); await server.register(require('hapi-auth-jwt2')); await server.register(require('./auth/authentication')); } try { await server.register([ { plugin: require('good'), options: { reporters: { console: [{ module: 'good-console' }, 'stdout'] } } }, require('inert'), require('vision'), require('h2o2'), { plugin: require('./routes/plugins/error'), options: { config: config } } ]); } catch (err) { return cb(err); } server.views({ engines: { html: { module: require('handlebars'), compileMode: 'sync' } }, relativeTo: __dirname, path: './templates/pages', layout: 'default', layoutPath: './templates/layouts', partialsPath: './templates/partials', helpersPath: './templates/helpers' }); cb(null, { server, elastic }); };
Sort room table by room name by default
from web.blueprints.helpers.table import BootstrapTable, Column class SiteTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('site', 'Site', formatter='table.linkFormatter'), Column('buildings', 'Buildings', formatter='table.multiBtnFormatter'), ], **kw) class BuildingLevelRoomTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('room', 'Raum', formatter='table.linkFormatter'), Column('inhabitants', 'Bewohner', formatter='table.multiBtnFormatter'), ], table_args={ 'data-sort-name': 'room', 'data-query-params': 'perhaps_all_users_query_params', }, **kw) def generate_toolbar(self): """Generate a toolbar with a "Display all users" button """ yield '<a href="#" id="rooms-toggle-all-users" class="btn btn-default" role="button">' yield '<span class="glyphicon glyphicon-user"></span>' yield 'Display all users' yield '</a>' class RoomLogTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('created_at', 'Erstellt um'), Column('user', 'Nutzer', formatter='table.linkFormatter'), Column('message', 'Nachricht'), ], **kw)
from web.blueprints.helpers.table import BootstrapTable, Column class SiteTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('site', 'Site', formatter='table.linkFormatter'), Column('buildings', 'Buildings', formatter='table.multiBtnFormatter'), ], **kw) class BuildingLevelRoomTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('room', 'Raum', formatter='table.linkFormatter'), Column('inhabitants', 'Bewohner', formatter='table.multiBtnFormatter'), ], table_args={ 'data-query-params': 'perhaps_all_users_query_params', }, **kw) def generate_toolbar(self): """Generate a toolbar with a "Display all users" button """ yield '<a href="#" id="rooms-toggle-all-users" class="btn btn-default" role="button">' yield '<span class="glyphicon glyphicon-user"></span>' yield 'Display all users' yield '</a>' class RoomLogTable(BootstrapTable): def __init__(self, *a, **kw): super().__init__(*a, columns=[ Column('created_at', 'Erstellt um'), Column('user', 'Nutzer', formatter='table.linkFormatter'), Column('message', 'Nachricht'), ], **kw)
Use route attribute tenant resolver
<?php namespace Tenantable\UserHasTenant\Providers; use Illuminate\Support\ServiceProvider; use Tenantable\UserHasTenant\TenantResolver\EloquentTenantResolver; use Tenantable\UserHasTenant\TenantResolver\RequestAttributeTenantResolver; use Tenantable\UserHasTenant\UserHasTenant; use Tenantable\UserHasTenant\UserResolver\EloquentUserResolver; class UserHasTenantServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('Tenantable\UserHasTenant\TenantResolver\TenantResolverInterface', function ($app){ return new RequestAttributeTenantResolver($app['request']); }); $this->app->bind('Tenantable\UserHasTenant\UserResolver\UserResolverInterface', function($app){ return new EloquentUserResolver($app['Illuminate\Contracts\Auth\Guard'], $app['config']); }); $this->app->bind('Tenantable\Tenantable', function($app) { return new UserHasTenant($app['Tenantable\UserHasTenant\TenantResolver\TenantResolverInterface'], $app['Tenantable\UserHasTenant\UserResolver\UserResolverInterface']); }); } public function boot() { $this->publishes([ __DIR__.'/../Config/laravel.php' => config_path('tenantable.php') ]); } }
<?php namespace Tenantable\UserHasTenant\Providers; use Illuminate\Support\ServiceProvider; use Tenantable\UserHasTenant\TenantResolver\EloquentTenantResolver; use Tenantable\UserHasTenantTenantable; use Tenantable\UserHasTenant\UserResolver\EloquentUserResolver; class UserHasTenantServiceProvider extends ServiceProvider { /** * Register the service provider. * * @return void */ public function register() { $this->app->bind('Tenantable\UserHasTenant\TenantResolver\TenantResolverInterface', function ($app){ return new EloquentTenantResolver($app['config'], $app, $app['request']); }); $this->app->bind('Tenantable\UserHasTenant\UserResolver\UserResolverInterface', function($app){ return new EloquentUserResolver($app['Illuminate\Contracts\Auth\Guard'], $app['config']); }); $this->app->bind('Tenantable\Tenantable', function($app) { return new UserHasTenant($app['Tenantable\UserHasTenant\TenantResolver\TenantResolverInterface'], $app['Tenantable\UserHasTenant\UserResolver\UserResolverInterface']); }); } public function boot() { $this->publishes([ __DIR__.'/../Config/laravel.php' => config_path('tenantable.php') ]); } }
Update rxjs in GTN to latest version
System.config({ map : { 'app': 'app', 'rxjs': 'https://unpkg.com/[email protected]', '@angular/common': 'https://unpkg.com/@angular/[email protected]', '@angular/compiler': 'https://unpkg.com/@angular/[email protected]', '@angular/core': 'https://unpkg.com/@angular/[email protected]', '@angular/platform-browser': 'https://unpkg.com/@angular/[email protected]', '@angular/platform-browser-dynamic': 'https://unpkg.com/@angular/[email protected]' }, packages:{ 'app': { main: 'main.ts', defaultExtension: 'ts' }, '@angular/common': { main: 'bundles/common.umd.js', defaultExtension: 'js' }, '@angular/compiler': { main: 'bundles/compiler.umd.js', defaultExtension: 'js' }, '@angular/core': { main: 'bundles/core.umd.js', defaultExtension: 'js' }, '@angular/platform-browser': { main: 'bundles/platform-browser.umd.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'bundles/platform-browser-dynamic.umd.js', defaultExtension: 'js' }, }, // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true } });
System.config({ map : { 'app': 'app', 'rxjs': 'https://unpkg.com/[email protected]', '@angular/common': 'https://unpkg.com/@angular/[email protected]', '@angular/compiler': 'https://unpkg.com/@angular/[email protected]', '@angular/core': 'https://unpkg.com/@angular/[email protected]', '@angular/platform-browser': 'https://unpkg.com/@angular/[email protected]', '@angular/platform-browser-dynamic': 'https://unpkg.com/@angular/[email protected]' }, packages:{ 'app': { main: 'main.ts', defaultExtension: 'ts' }, '@angular/common': { main: 'bundles/common.umd.js', defaultExtension: 'js' }, '@angular/compiler': { main: 'bundles/compiler.umd.js', defaultExtension: 'js' }, '@angular/core': { main: 'bundles/core.umd.js', defaultExtension: 'js' }, '@angular/platform-browser': { main: 'bundles/platform-browser.umd.js', defaultExtension: 'js' }, '@angular/platform-browser-dynamic': { main: 'bundles/platform-browser-dynamic.umd.js', defaultExtension: 'js' }, }, // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true } });
Fix logger for php 5.3
<?php /* * Copyright (c) Ouzo contributors, http://ouzoframework.org * This file is made available under the MIT License (view the LICENSE file for more information). */ namespace Ouzo\Logger; use Ouzo\Config; use Ouzo\Utilities\Arrays; /** * Logger class is used to obtain reference to current logger * based on configuration entry $config['logger']['default']['class']. * * Sample usage: * <code> * Logger::getLogger(__CLASS__)->debug('message'); * Logger::getLogger('logger name')->debug('message'); * Logger::getLogger('logger name', 'user_custom_config')->debug('message'); * </code> */ class Logger { private static $loggers = array(); /** * @param $name * @param string $configuration * @return LoggerInterface */ public static function getLogger($name, $configuration = 'default') { $logger = Arrays::getNestedValue(self::$loggers, array($name, $configuration)); if (!$logger) { $logger = self::loadLogger($name, $configuration); Arrays::setNestedValue(self::$loggers, array($name, $configuration), $logger); } return $logger; } private static function loadLogger($name, $configuration) { $logger = Config::getValue('logger', $configuration); if (!$logger || !isset($logger['class'])) { return new SyslogLogger($name, $configuration); } return new $logger['class']($name, $configuration); } }
<?php /* * Copyright (c) Ouzo contributors, http://ouzoframework.org * This file is made available under the MIT License (view the LICENSE file for more information). */ namespace Ouzo\Logger; use Ouzo\Config; use Ouzo\Utilities\Arrays; /** * Logger class is used to obtain reference to current logger * based on configuration entry $config['logger']['default']['class']. * * Sample usage: * <code> * Logger::getLogger(__CLASS__)->debug('message'); * Logger::getLogger('logger name')->debug('message'); * Logger::getLogger('logger name', 'user_custom_config')->debug('message'); * </code> */ class Logger { private static $loggers = array(); /** * @param $name * @param string $configuration * @return LoggerInterface */ public static function getLogger($name, $configuration = 'default') { $logger = Arrays::getNestedValue(self::$loggers, [$name, $configuration]); if (!$logger) { $logger = self::loadLogger($name, $configuration); Arrays::setNestedValue(self::$loggers, [$name, $configuration], $logger); } return $logger; } private static function loadLogger($name, $configuration) { $logger = Config::getValue('logger', $configuration); if (!$logger || !isset($logger['class'])) { return new SyslogLogger($name, $configuration); } return new $logger['class']($name, $configuration); } }
Remove unnecessary login during build model frontend test
casper.test.begin('build model', function suite(test) { casper.start('http://localhost:5000', function() { this.page.viewportSize = { width: 1920, height: 1080 }; // Build model casper.then(function(){ this.evaluate(function() { document.querySelector('#buildmodel_project_name_select').selectedIndex = 0; document.querySelector('#modelbuild_featset_name_select').selectedIndex = 0; document.querySelector('#model_type_select').selectedIndex = 0; return true; }); this.click('#model_build_submit_button'); }); casper.then(function(){ casper.waitForText( "New model successfully created", function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, 10000); }); }); casper.run(function() { test.done(); }); });
casper.test.begin('build model', function suite(test) { casper.start('http://localhost:5000', function() { this.page.viewportSize = { width: 1920, height: 1080 }; if(this.exists('form.login-form')){ this.fill('form.login-form', { 'login': '[email protected]', 'password': 'TestPass15' }, true); } // Build model casper.then(function(){ this.evaluate(function() { document.querySelector('#buildmodel_project_name_select').selectedIndex = 0; document.querySelector('#modelbuild_featset_name_select').selectedIndex = 0; document.querySelector('#model_type_select').selectedIndex = 0; return true; }); this.click('#model_build_submit_button'); }); casper.then(function(){ casper.waitForText( "New model successfully created", function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, function(){ test.assertTextExists("New model successfully created", "New model successfully created"); }, 10000); }); }); casper.run(function() { test.done(); }); });
Upgrade taskcluster client for nice slugids This fixes e.g. this failure: * https://tools.taskcluster.net/task-inspector/#2AAxnGTzSeGLTX_Hwp_PVg/ due to the TaskGroupId starting with a '-', by upgrading taskcluster client. From version 0.0.26 of python taskcluster client onwards, 'nice' slugs are returned that start with [A-Za-f].
from setuptools import setup setup( name="funsize", version="0.42", description="Funsize Scheduler", author="Mozilla Release Engineering", packages=["funsize"], include_package_data=True, # Not zip safe because we have data files in the package zip_safe=False, entry_points={ "console_scripts": [ "funsize-scheduler = funsize.scheduler:main", ], }, install_requires=[ "amqp", "anyjson", "argparse", "cffi", # PGPy depends on this _specific_ version of cryptography "cryptography==0.6", "enum34", "kombu", "more_itertools", "PGPy", "pycparser", "PyHawk-with-a-single-extra-commit", "Jinja2", "PyYAML", "redo", # Because taskcluster hard pins this version... "requests==2.4.3", "singledispatch", "six", "taskcluster>=0.0.26", "wsgiref", ], tests_require=[ 'hypothesis', 'pytest', 'mock', ], )
from setuptools import setup setup( name="funsize", version="0.42", description="Funsize Scheduler", author="Mozilla Release Engineering", packages=["funsize"], include_package_data=True, # Not zip safe because we have data files in the package zip_safe=False, entry_points={ "console_scripts": [ "funsize-scheduler = funsize.scheduler:main", ], }, install_requires=[ "amqp", "anyjson", "argparse", "cffi", # PGPy depends on this _specific_ version of cryptography "cryptography==0.6", "enum34", "kombu", "more_itertools", "PGPy", "pycparser", "PyHawk-with-a-single-extra-commit", "Jinja2", "PyYAML", "redo", # Because taskcluster hard pins this version... "requests==2.4.3", "singledispatch", "six", "taskcluster>=0.0.24", "wsgiref", ], tests_require=[ 'hypothesis', 'pytest', 'mock', ], )
Use isoformat in datetime logs, rather than asctime Change-Id: Ic11a70e28288517b6f174d7066f71a12efd5f4f1
import os import datetime import pwd from .utils import effective_user class Tool(object): USER_NAME_PATTERN = 'tools.%s' class InvalidToolException(Exception): pass def __init__(self, name, username, uid, gid, home): self.name = name self.uid = uid self.gid = gid self.username = username self.home = home @classmethod def from_name(cls, name): """ Create a Tool instance from a tool name """ username = Tool.USER_NAME_PATTERN % (name, ) try: user_info = pwd.getpwnam(username) except KeyError: # No such user was found raise Tool.InvalidToolException("No tool with name %s" % (name, )) if user_info.pw_uid < 50000: raise Tool.InvalidToolException("uid of tools should be < 50000, %s has uid %s" % (name, user_info.pw_uid)) return cls(name, user_info.pw_name, user_info.pw_uid, user_info.pw_gid, user_info.pw_dir) def log(self, message): """ Write to a log file in the tool's homedir """ log_line = "%s %s" % (datetime.datetime.now().isoformat(), message) log_path = os.path.join(self.home, 'service.log') with effective_user(self.uid, self.gid): with open(log_path, 'a') as f: f.write(log_line + '\n')
import os import time import pwd from .utils import effective_user class Tool(object): USER_NAME_PATTERN = 'tools.%s' class InvalidToolException(Exception): pass def __init__(self, name, username, uid, gid, home): self.name = name self.uid = uid self.gid = gid self.username = username self.home = home @classmethod def from_name(cls, name): """ Create a Tool instance from a tool name """ username = Tool.USER_NAME_PATTERN % (name, ) try: user_info = pwd.getpwnam(username) except KeyError: # No such user was found raise Tool.InvalidToolException("No tool with name %s" % (name, )) if user_info.pw_uid < 50000: raise Tool.InvalidToolException("uid of tools should be < 50000, %s has uid %s" % (name, user_info.pw_uid)) return cls(name, user_info.pw_name, user_info.pw_uid, user_info.pw_gid, user_info.pw_dir) def log(self, message): """ Write to a log file in the tool's homedir """ log_line = "%s %s" % (time.asctime(), message) log_path = os.path.join(self.home, 'service.log') with effective_user(self.uid, self.gid): with open(log_path, 'a') as f: f.write(log_line + '\n')
Test that we can go to the edit page of a tag from the index
<?php namespace Backend\Modules\Blog\Tests\Action; use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags; use Backend\Modules\Tags\DataFixtures\LoadTagsTags; use Common\WebTestCase; class EditTest extends WebTestCase { public function setUp(): void { parent::setUp(); if (!defined('APPLICATION')) { define('APPLICATION', 'Backend'); } $client = self::createClient(); $this->loadFixtures( $client, [ LoadTagsTags::class, LoadTagsModulesTags::class, ] ); } public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/tags/edit?id=1'); // we should get redirected to authentication with a reference to the wanted page $this->assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1', $client->getHistory()->current()->getUri() ); } public function testWeCanGoToEditFromTheIndexPage(): void { $client = static::createClient(); $this->login($client); $crawler = $client->request('GET', '/private/en/tags/index'); $this->assertContains( 'most used', $client->getResponse()->getContent() ); $link = $crawler->selectLink('most used')->link(); $client->click($link); $this->assertEquals(200, $client->getResponse()->getStatusCode()); $this->assertContains( '&id=2', $client->getHistory()->current()->getUri() ); } }
<?php namespace Backend\Modules\Blog\Tests\Action; use Backend\Modules\Tags\DataFixtures\LoadTagsModulesTags; use Backend\Modules\Tags\DataFixtures\LoadTagsTags; use Common\WebTestCase; class EditTest extends WebTestCase { public function setUp(): void { parent::setUp(); if (!defined('APPLICATION')) { define('APPLICATION', 'Backend'); } $client = self::createClient(); $this->loadFixtures( $client, [ LoadTagsTags::class, LoadTagsModulesTags::class, ] ); } public function testAuthenticationIsNeeded(): void { $client = static::createClient(); $this->logout($client); $client->setMaxRedirects(1); $client->request('GET', '/private/en/tags/edit?id=1'); // we should get redirected to authentication with a reference to the wanted page $this->assertStringEndsWith( '/private/en/authentication?querystring=%2Fprivate%2Fen%2Ftags%2Fedit%3Fid%3D1', $client->getHistory()->current()->getUri() ); } }
Determine menu base path from request base path and backend mount prefix instead of generating url. Fixes #6139 The base url generated could have query params or fragment which breaks urls that are concatenated to it.
<?php namespace Bolt\Provider; use Bolt\Menu\AdminMenuBuilder; use Bolt\Menu\MenuBuilder; use Bolt\Menu\MenuEntry; use Silex\Application; use Silex\ServiceProviderInterface; class MenuServiceProvider implements ServiceProviderInterface { /** * {@inheritdoc} */ public function register(Application $app) { $app['menu'] = $app->share( function ($app) { $builder = new MenuBuilder($app); return $builder; } ); /** * @internal Backwards compatibility not guaranteed on this provider presently. */ $app['menu.admin'] = $app->share( function ($app) { // This service should not be invoked until request cycle since it depends // on url generation and request base path. Probably should be refactored somehow. $baseUrl = ''; if (($request = $app['request_stack']->getCurrentRequest()) !== null) { $baseUrl = $request->getBasePath(); } $baseUrl .= '/' . trim($app['controller.backend.mount_prefix'], '/'); $adminMenu = new AdminMenuBuilder(new MenuEntry('root', $baseUrl)); $rootEntry = $adminMenu->build($app); return $rootEntry; } ); } /** * {@inheritdoc} */ public function boot(Application $app) { } }
<?php namespace Bolt\Provider; use Bolt\Menu\AdminMenuBuilder; use Bolt\Menu\MenuBuilder; use Bolt\Menu\MenuEntry; use Silex\Application; use Silex\ServiceProviderInterface; class MenuServiceProvider implements ServiceProviderInterface { /** * {@inheritdoc} */ public function register(Application $app) { $app['menu'] = $app->share( function ($app) { $builder = new MenuBuilder($app); return $builder; } ); /** * @internal Backwards compatibility not guaranteed on this provider presently. */ $app['menu.admin'] = $app->share( function ($app) { // This service should not be invoked until request cycle since it depends // on url generation. Probably should be refactored somehow. $baseUrl = $app['url_generator']->generate('dashboard'); $adminMenu = new AdminMenuBuilder(new MenuEntry('root', $baseUrl)); $rootEntry = $adminMenu->build($app); return $rootEntry; } ); } /** * {@inheritdoc} */ public function boot(Application $app) { } }
Remove use as it's not used.
<?php namespace Avh\Network; final class Visitor { /** * Get the user's IP * * @return string */ public static function getUserIp() { $ip = array(); foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $_key) { if (array_key_exists($_key, $_SERVER) === true) { foreach (explode(',', $_SERVER[$_key]) as $_visitors_ip) { $ip[] = str_replace(' ', '', $_visitors_ip); } } } // If for some strange reason we don't get an IP we return imemdiately with 0.0.0.0 if (empty($ip)) { return '0.0.0.0'; } $ip = array_values(array_unique($ip)); $return = null; // In PHP 5.3 and up the function filter_var can be used, much quicker as the regular expression check foreach ($ip as $_i) { if (filter_var($_i, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) { $return = $_i; break; } } if (null === $return) { $return = '0.0.0.0'; } return $return; } }
<?php namespace Avh\Network; use Avh\Utility\Common; final class Visitor { /** * Get the user's IP * * @return string */ public static function getUserIp() { $ip = array(); foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR') as $_key) { if (array_key_exists($_key, $_SERVER) === true) { foreach (explode(',', $_SERVER[$_key]) as $_visitors_ip) { $ip[] = str_replace(' ', '', $_visitors_ip); } } } // If for some strange reason we don't get an IP we return imemdiately with 0.0.0.0 if (empty($ip)) { return '0.0.0.0'; } $ip = array_values(array_unique($ip)); $return = null; // In PHP 5.3 and up the function filter_var can be used, much quicker as the regular expression check foreach ($ip as $_i) { if (filter_var($_i, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_PRIV_RANGE)) { $return = $_i; break; } } if (null === $return) { $return = '0.0.0.0'; } return $return; } }
Set a title to the default page
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace MyCompany\MyWebsite\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Initializes a new instance of the `Page` class. */ public function Page() { $this->Title = 'TemPHPlate'; $this->Template = new BootstrapTemplate($this); } /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <h1>'.$this->Title.'</h1> <p> <img src="./meme.jpg" /> </p> <p> Next you may wanna edit your menu-bar.<br /> Open up <code>/Properties/MenuBar.json</code> for doing so. </p>'; } } } ?>
<?php /** * @author Manuel Thalmann <[email protected]> * @license Apache-2.0 */ namespace MyCompany\MyWebsite\Pages; use System\Web; use System\Web\Forms\Rendering\PaintEventArgs; use System\Web\Forms\MenuItem; use ManuTh\TemPHPlate\Templates\BootstrapTemplate; { /** * A page */ class Page extends Web\Page { /** * Initializes a new instance of the `Page` class. */ public function Page() { $this->Template = new BootstrapTemplate($this); } /** * Draws the object. * * @return void */ protected function DrawInternal() { echo ' <h1>TemPHPlate</h1> <p> <img src="./meme.jpg" /> </p> <p> Next you may wanna edit your menu-bar.<br /> Open up <code>/Properties/MenuBar.json</code> for doing so. </p>'; } } } ?>
Use logger to record exception instead of printStackTrace.
package uk.ac.ebi.quickgo.common.loader; import java.io.*; import java.util.zip.GZIPOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * To test the GZIPFiles class, create a gzip'd file with known test in a temporary location. * The client is expected to clean up the file after it's finished with it. * * @author Tony Wardell * Date: 17/05/2016 * Time: 15:38 * Created with IntelliJ IDEA. */ class GZIPFileMocker { private static final Logger logger = LoggerFactory.getLogger(GZIPFileMocker.class); static final String TEXT = "Mary had a little lamb, it's fleece was white as snow"; static File createTestFile() { BufferedWriter bufferedWriter = null; File temp = null; try { temp = File.createTempFile("temp-file-name", "txt.gz"); //Construct the BufferedWriter object bufferedWriter = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(temp)) )); // from the input file to the GZIP output file bufferedWriter.write(TEXT); bufferedWriter.newLine(); } catch (IOException e) { logger.error("Error: ", e); } finally { //Close the BufferedWrter if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { logger.error("Error: ", e); } } } return temp; } }
package uk.ac.ebi.quickgo.common.loader; import java.io.*; import java.util.zip.GZIPOutputStream; /** * To test the GZIPFiles class, create a gzip'd file with known test in a temporary location. * The client is expected to clean up the file after it's finished with it. * * @author Tony Wardell * Date: 17/05/2016 * Time: 15:38 * Created with IntelliJ IDEA. */ public class GZIPFileMocker{ public static final String TEXT = "Mary had a little lamb, it's fleece was white as snow"; public static final File createTestFile(){ BufferedWriter bufferedWriter = null; File temp = null; try { temp = File.createTempFile("temp-file-name", "txt.gz"); //Construct the BufferedWriter object bufferedWriter = new BufferedWriter( new OutputStreamWriter( new GZIPOutputStream(new FileOutputStream(temp)) )); // from the input file to the GZIP output file bufferedWriter.write(TEXT); bufferedWriter.newLine(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { //Close the BufferedWrter if (bufferedWriter != null) { try { bufferedWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } return temp; } }
Remove the useless import of redisx
package db_manager import ( "fmt" "log" "github.com/garyburd/redigo/redis" "encoding/json" "../entities" ) var connection redis.Conn const ( HOSTNAME = "localhost" PORT = 6379 NETWORK = "tcp" ) func init() { var err error log.Print("Initializing database connection... ") connection, err = connect() if err != nil { log.Fatal(err) } } func connect() (redis.Conn, error) { return redis.Dial("tcp", fmt.Sprintf("%v:%v", HOSTNAME, PORT)) } func Finalize() { log.Print("Closing database connection... ") err := connection.Close() if err != nil { log.Fatal(err) } } func SetEntity(entity entities.Entity) bool { key, prepared_entity := entity.Serialize() send_err := connection.Send("SET", key, prepared_entity) if send_err != nil { log.Print(send_err) return false } flush_err := connection.Flush() if flush_err != nil { log.Print(flush_err) return false } return true } func GetEntity(key string) entity.Entity { result, err := redis.Bytes(connection.Do("GET", key)) if err != nil { log.Print(err) return nil } return Construct(key, result) }
package db_manager import ( "fmt" "log" "github.com/garyburd/redigo/redis" "encoding/json" "../entities" // "github.com/garyburd/redigo/redisx" ) var connection redis.Conn const ( HOSTNAME = "localhost" PORT = 6379 NETWORK = "tcp" ) func init() { var err error log.Print("Initializing database connection... ") connection, err = connect() if err != nil { log.Fatal(err) } } func connect() (redis.Conn, error) { return redis.Dial("tcp", fmt.Sprintf("%v:%v", HOSTNAME, PORT)) } func Finalize() { log.Print("Closing database connection... ") err := connection.Close() if err != nil { log.Fatal(err) } } func SetEntity(entity entities.Entity) bool { key, prepared_entity := entity.Serialize() send_err := connection.Send("SET", key, prepared_entity) if send_err != nil { log.Print(send_err) return false } flush_err := connection.Flush() if flush_err != nil { log.Print(flush_err) return false } return true } func GetEntity(key string) entity.Entity { result, err := redis.Bytes(connection.Do("GET", key)) if err != nil { log.Print(err) return nil } return Construct(key, result) }
Remove old pycharm icon support.
package com.iselsoft.ptest.runLineMarker; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.iselsoft.ptest.runConfiguration.PTestConfigurationProducer; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import org.jetbrains.annotations.Nullable; public class PTestRunLineMarkerContributor extends RunLineMarkerContributor { private static final PTestConfigurationProducer CONFIG_PRODUCER = new PTestConfigurationProducer(); private static final Function<PsiElement, String> TOOLTIP_PROVIDER = new Function<PsiElement, String>() { @Override public String fun(PsiElement psiElement) { return "Run ptest"; } }; @Nullable @Override public Info getInfo(PsiElement psiElement) { if (psiElement instanceof PyFunction && CONFIG_PRODUCER.isPTestMethod(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } else if (psiElement instanceof PyClass && CONFIG_PRODUCER.isPTestClass(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run_run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } return null; } }
package com.iselsoft.ptest.runLineMarker; import com.intellij.execution.lineMarker.RunLineMarkerContributor; import com.intellij.icons.AllIcons; import com.intellij.psi.PsiElement; import com.intellij.util.Function; import com.iselsoft.ptest.runConfiguration.PTestConfigurationProducer; import com.jetbrains.python.psi.PyClass; import com.jetbrains.python.psi.PyFunction; import org.jetbrains.annotations.Nullable; public class PTestRunLineMarkerContributor extends RunLineMarkerContributor { private static final PTestConfigurationProducer CONFIG_PRODUCER = new PTestConfigurationProducer(); private static final Function<PsiElement, String> TOOLTIP_PROVIDER = new Function<PsiElement, String>() { @Override public String fun(PsiElement psiElement) { return "Run ptest"; } }; @Nullable @Override public Info getInfo(PsiElement psiElement) { if (psiElement instanceof PyFunction && CONFIG_PRODUCER.isPTestMethod(psiElement, null)) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } else if (psiElement instanceof PyClass && CONFIG_PRODUCER.isPTestClass(psiElement, null)) { try { return new Info(AllIcons.RunConfigurations.TestState.Run_run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } catch (NoSuchFieldError e) { return new Info(AllIcons.RunConfigurations.TestState.Run, TOOLTIP_PROVIDER, PTestRunLineMarkerAction.getActions()); } } return null; } }
Update the search container when terms change. [Fixes #126799709](https://www.pivotaltracker.com/story/show/126799709)
import React, { PropTypes } from 'react' import Promotion from '../assets/Promotion' import SearchControl from '../forms/SearchControl' import StreamContainer from '../../containers/StreamContainer' import { TabListButtons } from '../tabs/TabList' import { MainView } from '../views/MainView' export const Search = ({ coverDPI, isLoggedIn, onChange, onClickTrackCredits, onSubmit, promotion, streamAction, streamKey, tabs, terms, type, }) => <MainView className="Search"> <Promotion coverDPI={coverDPI} isLoggedIn={isLoggedIn} onClickTrackCredits={onClickTrackCredits} promotion={promotion} /> <form className="SearchBar" onSubmit={onSubmit}> <SearchControl key={terms} onChange={onChange} text={terms} /> <TabListButtons activeType={type} className="SearchTabList" onTabClick={onChange} tabClasses="LabelTab SearchLabelTab" tabs={tabs} /> </form> <StreamContainer key={streamKey} action={streamAction} /> </MainView> Search.propTypes = { coverDPI: PropTypes.string.isRequired, isLoggedIn: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired, onClickTrackCredits: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, promotion: PropTypes.object, streamAction: PropTypes.object, streamKey: PropTypes.string.isRequired, tabs: PropTypes.array.isRequired, terms: PropTypes.string.isRequired, type: PropTypes.string.isRequired, } export default Search
import React, { PropTypes } from 'react' import Promotion from '../assets/Promotion' import SearchControl from '../forms/SearchControl' import StreamContainer from '../../containers/StreamContainer' import { TabListButtons } from '../tabs/TabList' import { MainView } from '../views/MainView' export const Search = ({ coverDPI, isLoggedIn, onChange, onClickTrackCredits, onSubmit, promotion, streamAction, streamKey, tabs, terms, type, }) => <MainView className="Search"> <Promotion coverDPI={coverDPI} isLoggedIn={isLoggedIn} onClickTrackCredits={onClickTrackCredits} promotion={promotion} /> <form className="SearchBar" onSubmit={onSubmit}> <SearchControl onChange={onChange} text={terms} /> <TabListButtons activeType={type} className="SearchTabList" onTabClick={onChange} tabClasses="LabelTab SearchLabelTab" tabs={tabs} /> </form> <StreamContainer key={streamKey} action={streamAction} /> </MainView> Search.propTypes = { coverDPI: PropTypes.string.isRequired, isLoggedIn: PropTypes.bool.isRequired, onChange: PropTypes.func.isRequired, onClickTrackCredits: PropTypes.func.isRequired, onSubmit: PropTypes.func.isRequired, promotion: PropTypes.object, streamAction: PropTypes.object, streamKey: PropTypes.string.isRequired, tabs: PropTypes.array.isRequired, terms: PropTypes.string.isRequired, type: PropTypes.string.isRequired, } export default Search
WebRTC: Switch remaining chromium.webrtc builders to chromium recipe. Linux was switched in https://codereview.chromium.org/1508933002/ This switches the rest over to the chromium recipe. BUG=538259 [email protected] Review URL: https://codereview.chromium.org/1510853002 . git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@297886 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factory m_annotator = annotator_factory.AnnotatorFactory() def Update(c): c['schedulers'].append( SingleBranchScheduler(name='chromium_scheduler', change_filter=ChangeFilter(project='chromium', branch='master'), treeStableTimer=60, builderNames=[ 'Win Builder', 'Mac Builder', 'Linux Builder', ]), ) specs = [ {'name': 'Win Builder', 'category': 'win'}, {'name': 'WinXP Tester', 'category': 'win'}, {'name': 'Win7 Tester', 'category': 'win'}, {'name': 'Win8 Tester', 'category': 'win'}, {'name': 'Win10 Tester', 'category': 'win'}, {'name': 'Mac Builder', 'category': 'mac'}, {'name': 'Mac Tester', 'category': 'mac'}, {'name': 'Linux Builder', 'category': 'linux'}, {'name': 'Linux Tester', 'category': 'linux'}, ] c['builders'].extend([ { 'name': spec['name'], 'factory': m_annotator.BaseFactory('chromium'), 'category': spec['category'], 'notify_on_missing': True, } for spec in specs ])
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from buildbot.changes.filter import ChangeFilter from buildbot.schedulers.basic import SingleBranchScheduler from master.factory import annotator_factory m_annotator = annotator_factory.AnnotatorFactory() def Update(c): c['schedulers'].append( SingleBranchScheduler(name='chromium_scheduler', change_filter=ChangeFilter(project='chromium', branch='master'), treeStableTimer=60, builderNames=[ 'Win Builder', 'Mac Builder', 'Linux Builder', ]), ) specs = [ {'name': 'Win Builder', 'category': 'win'}, {'name': 'WinXP Tester', 'category': 'win'}, {'name': 'Win7 Tester', 'category': 'win'}, {'name': 'Win8 Tester', 'category': 'win'}, {'name': 'Win10 Tester', 'category': 'win'}, {'name': 'Mac Builder', 'category': 'mac'}, {'name': 'Mac Tester', 'category': 'mac'}, {'name': 'Linux Builder', 'recipe': 'chromium', 'category': 'linux'}, {'name': 'Linux Tester', 'recipe': 'chromium', 'category': 'linux'}, ] c['builders'].extend([ { 'name': spec['name'], 'factory': m_annotator.BaseFactory(spec.get('recipe', 'webrtc/chromium')), 'category': spec['category'], 'notify_on_missing': True, } for spec in specs ])
Update invalid URI to correctly throw exception
/* * $Id: AltRepTest.java [23-Apr-2004] * * Copyright (c) 2004, Ben Fortuna All rights reserved. */ package net.fortuna.ical4j.model.parameter; import java.net.URI; import java.net.URISyntaxException; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; import junit.framework.TestCase; /** * Test case for AltRep. * @author benfortuna */ public class AltRepTest extends TestCase { /* * Class to test for void AltRep(String) */ public void testAltRepString() throws URISyntaxException { try { new AltRep("<mailto:../:...invalid...>"); fail("URISyntaxException not thrown!"); } catch (URISyntaxException use) { // test success. } AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, "mailto:[email protected]"); assertNotNull(ar.getUri()); } /* * Class to test for void AltRep(URI) */ public void testAltRepURI() throws URISyntaxException { AltRep ar = new AltRep(new URI("mailto:[email protected]")); assertNotNull(ar.getUri()); } }
/* * $Id: AltRepTest.java [23-Apr-2004] * * Copyright (c) 2004, Ben Fortuna All rights reserved. */ package net.fortuna.ical4j.model.parameter; import java.net.URI; import java.net.URISyntaxException; import net.fortuna.ical4j.model.Parameter; import net.fortuna.ical4j.model.ParameterFactoryImpl; import junit.framework.TestCase; /** * Test case for AltRep. * @author benfortuna */ public class AltRepTest extends TestCase { /* * Class to test for void AltRep(String) */ public void testAltRepString() throws URISyntaxException { try { new AltRep("::...invalid..."); fail("URISyntaxException not thrown!"); } catch (URISyntaxException use) { // test success. } AltRep ar = (AltRep) ParameterFactoryImpl.getInstance().createParameter(Parameter.ALTREP, "mailto:[email protected]"); assertNotNull(ar.getUri()); } /* * Class to test for void AltRep(URI) */ public void testAltRepURI() throws URISyntaxException { AltRep ar = new AltRep(new URI("mailto:[email protected]")); assertNotNull(ar.getUri()); } }
Fix to audit record map
(function(window) { var Gitana = window.Gitana; Gitana.AuditRecordMap = Gitana.AbstractMap.extend( /** @lends Gitana.AuditRecordMap.prototype */ { /** * @constructs * @augments Gitana.AbstractMap * * @class Map of audit record objects * * @param {Object} datastore * @param [Object] object */ constructor: function(datastore, object) { this.objectType = "Gitana.AuditRecordMap"; this.datastore = datastore; ////////////////////////////////////////////////////////////////////////////////////////////// // // CALL THROUGH TO BASE CLASS (at the end) // ////////////////////////////////////////////////////////////////////////////////////////////// this.base(datastore.getDriver(), object); }, /** * @override */ clone: function() { return this.getFactory().auditRecordMap(this.datastore, this.object); }, /** * @param json */ buildObject: function(json) { return this.getFactory().auditRecord(this.datastore, json); } }); })(window);
(function(window) { var Gitana = window.Gitana; Gitana.AuditRecordMap = Gitana.AbstractMap.extend( /** @lends Gitana.AuditRecordMap.prototype */ { /** * @constructs * @augments Gitana.AbstractMap * * @class Map of audit record objects * * @param {Object} datastore * @param [Object] object */ constructor: function(datastore, object) { this.objectType = "Gitana.AuditRecordMap"; this.datastore = datastore; ////////////////////////////////////////////////////////////////////////////////////////////// // // CALL THROUGH TO BASE CLASS (at the end) // ////////////////////////////////////////////////////////////////////////////////////////////// this.base(datastore.getCluster(), object); }, /** * @override */ clone: function() { return this.getFactory().auditRecordMap(this.datastore, this.object); }, /** * @param json */ buildObject: function(json) { return this.getFactory().auditRecord(this.datastore, json); } }); })(window);
Fix use command argument validation
<?php namespace PhpBrew\Command; use CLIFramework\Command; use PhpBrew\Config; use Exception; class UseCommand extends Command { public function arguments($args) { $args->add('php version') ->validValues(function() { return array_merge(\PhpBrew\Config::getInstalledPhpVersions(), array('latest')); }) ; } public function brief() { return 'Use php, switch version temporarily'; } public function execute($buildName) { $root = Config::getPhpbrewRoot(); $home = Config::getPhpbrewHome(); $foundBuildName = null; if (strtolower(trim($buildName)) == 'latest') { $foundBuildName = Config::findLatestBuild(false); } else { $foundBuildName = Config::findFirstMatchedBuild($buildName, false); } $phpDir = $root . DIRECTORY_SEPARATOR . 'php'; if (!$foundBuildName) { // TODO: list possible build names here... throw new Exception("$buildName does not exist in $phpDir directory."); } $this->logger->info("Found $foundBuildName, setting environment variables..."); // update environment putenv("PHPBREW_ROOT=$root"); putenv("PHPBREW_HOME=$home"); putenv("PHPBREW_PHP=$foundBuildName"); Config::putPathEnvFor($foundBuildName); $this->logger->warning("You should not see this, if you see this, it means you didn't load the ~/.phpbrew/bashrc script, please check if bashrc is sourced in your shell."); } }
<?php namespace PhpBrew\Command; use CLIFramework\Command; use PhpBrew\Config; use Exception; class UseCommand extends Command { public function arguments($args) { $args->add('php version') ->validValues(function() { return \PhpBrew\Config::getInstalledPhpVersions(); }) ; } public function brief() { return 'Use php, switch version temporarily'; } public function execute($buildName) { $root = Config::getPhpbrewRoot(); $home = Config::getPhpbrewHome(); $foundBuildName = null; if (strtolower(trim($buildName)) == 'latest') { $foundBuildName = Config::findLatestBuild(false); } else { $foundBuildName = Config::findFirstMatchedBuild($buildName, false); } $phpDir = $root . DIRECTORY_SEPARATOR . 'php'; if (!$foundBuildName) { // TODO: list possible build names here... throw new Exception("$buildName does not exist in $phpDir directory."); } $this->logger->info("Found $foundBuildName, setting environment variables..."); // update environment putenv("PHPBREW_ROOT=$root"); putenv("PHPBREW_HOME=$home"); putenv("PHPBREW_PHP=$foundBuildName"); Config::putPathEnvFor($foundBuildName); $this->logger->warning("You should not see this, if you see this, it means you didn't load the ~/.phpbrew/bashrc script, please check if bashrc is sourced in your shell."); } }
Add help_text to interface 'expire' field
from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ created = models.DateTimeField(auto_now_add=True, null=True) modified = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True get_latest_by = 'created' @classproperty @classmethod def pretty_type(cls): return cls.__name__.lower() @property def pretty_name(self): return unicode(self) def unique_error_message(self, model_class, unique_check): error = super(BaseModel, self).unique_error_message( model_class, unique_check) kwargs = {} for field in unique_check: kwargs[field] = getattr(self, field) obj = model_class.objects.filter(**kwargs) if obj and hasattr(obj.get(), 'get_detail_url'): error = error[:-1] + ' at <a href={0}>{1}.</a>'.format( obj.get().get_detail_url(), obj.get()) error = mark_safe(error) return error class ExpirableMixin(models.Model): expire = models.DateTimeField(null=True, blank=True, help_text='Format: MM/DD/YYYY') class Meta: abstract = True
from django.db import models from django.utils.safestring import mark_safe from cyder.base.utils import classproperty class BaseModel(models.Model): """ Base class for models to abstract some common features. * Adds automatic created and modified fields to the model. """ created = models.DateTimeField(auto_now_add=True, null=True) modified = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True get_latest_by = 'created' @classproperty @classmethod def pretty_type(cls): return cls.__name__.lower() @property def pretty_name(self): return unicode(self) def unique_error_message(self, model_class, unique_check): error = super(BaseModel, self).unique_error_message( model_class, unique_check) kwargs = {} for field in unique_check: kwargs[field] = getattr(self, field) obj = model_class.objects.filter(**kwargs) if obj and hasattr(obj.get(), 'get_detail_url'): error = error[:-1] + ' at <a href={0}>{1}.</a>'.format( obj.get().get_detail_url(), obj.get()) error = mark_safe(error) return error class ExpirableMixin(models.Model): expire = models.DateTimeField(null=True, blank=True) class Meta: abstract = True
Fix fixture loading with API keys.
<?php namespace App\Entity\Fixture; use App\Entity; use App\Security\SplitToken; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; class ApiKey extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $em): void { $demo_api_key = getenv('INIT_DEMO_API_KEY'); if (!empty($demo_api_key) && $this->hasReference('demo_user')) { /** @var Entity\User $demo_user */ $demo_user = $this->getReference('demo_user'); $api_key = new Entity\ApiKey($demo_user, SplitToken::fromKeyString($demo_api_key)); $api_key->setComment('Demo User'); $em->persist($api_key); } $admin_api_key = getenv('INIT_ADMIN_API_KEY'); if (!empty($admin_api_key) && $this->hasReference('admin_user')) { /** @var Entity\User $admin_user */ $admin_user = $this->getReference('admin_user'); $api_key = new Entity\ApiKey($admin_user, SplitToken::fromKeyString($admin_api_key)); $api_key->setComment('Administrator'); $em->persist($api_key); } $em->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ User::class, ]; } }
<?php namespace App\Entity\Fixture; use App\Entity; use Doctrine\Common\DataFixtures\AbstractFixture; use Doctrine\Common\DataFixtures\DependentFixtureInterface; use Doctrine\Persistence\ObjectManager; class ApiKey extends AbstractFixture implements DependentFixtureInterface { public function load(ObjectManager $em): void { $demo_api_key = getenv('INIT_DEMO_API_KEY'); if (!empty($demo_api_key) && $this->hasReference('demo_user')) { /** @var Entity\User $demo_user */ $demo_user = $this->getReference('demo_user'); $api_key = new Entity\ApiKey($demo_user, $demo_api_key); $api_key->setComment('Demo User'); $em->persist($api_key); } $admin_api_key = getenv('INIT_ADMIN_API_KEY'); if (!empty($admin_api_key) && $this->hasReference('admin_user')) { /** @var Entity\User $admin_user */ $admin_user = $this->getReference('admin_user'); $api_key = new Entity\ApiKey($admin_user, $admin_api_key); $api_key->setComment('Administrator'); $em->persist($api_key); } $em->flush(); } /** * @return string[] */ public function getDependencies(): array { return [ User::class, ]; } }
Revert "Do not re-evalute sasl every time connection is built" This reverts commit 3f073c556c007fc1adcc4b4cee6608a1128c8231.
const Connection = require('../network/connection') const { KafkaJSConnectionError } = require('../errors') const validateBrokers = brokers => { if (!brokers || brokers.length === 0) { throw new KafkaJSConnectionError(`Failed to connect: expected brokers array and got nothing`) } } module.exports = ({ socketFactory, brokers, ssl, sasl, clientId, requestTimeout, enforceRequestTimeout, connectionTimeout, maxInFlightRequests, retry, logger, instrumentationEmitter = null, }) => { return { build: async ({ host, port, rack } = {}) => { if (!host) { const list = typeof brokers === 'function' ? await brokers() : brokers validateBrokers(list) const randomBroker = list[Math.floor(Math.random() * list.length)] host = randomBroker.split(':')[0] port = Number(randomBroker.split(':')[1]) } return new Connection({ host, port, rack, sasl: typeof sasl === 'function' ? await sasl() : sasl, ssl, clientId, socketFactory, connectionTimeout, requestTimeout, enforceRequestTimeout, maxInFlightRequests, instrumentationEmitter, retry, logger, }) }, } }
const Connection = require('../network/connection') const { KafkaJSConnectionError } = require('../errors') const validateBrokers = brokers => { if (!brokers || brokers.length === 0) { throw new KafkaJSConnectionError(`Failed to connect: expected brokers array and got nothing`) } } module.exports = ({ socketFactory, brokers, ssl, sasl, clientId, requestTimeout, enforceRequestTimeout, connectionTimeout, maxInFlightRequests, retry, logger, instrumentationEmitter = null, }) => { return { build: async ({ host, port, rack } = {}) => { if (!host) { const list = typeof brokers === 'function' ? await brokers() : brokers validateBrokers(list) const randomBroker = list[Math.floor(Math.random() * list.length)] host = randomBroker.split(':')[0] port = Number(randomBroker.split(':')[1]) } if (typeof sasl === 'function') { sasl = await sasl() } return new Connection({ host, port, rack, sasl, ssl, clientId, socketFactory, connectionTimeout, requestTimeout, enforceRequestTimeout, maxInFlightRequests, instrumentationEmitter, retry, logger, }) }, } }
Add package_dir which uses project.repo_url.
#!/usr/bin/env python import os import sys import {{ project.repo_name }} try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst', 'rt').read() history = open('HISTORY.rst', 'rt').read() setup( name='{{ project.repo_name }}', version={{ project.repo_name }}.__version__, description='{{ project.project_short_description }}', long_description=readme + '\n\n' + history, author='{{ project.full_name }}', author_email='{{ project.email }}', url='https://github.com/{{ project.github_username }}/{{ project.repo_name }}', packages=[ '{{ project.repo_name }}', ], package_dir={'{{ project.repo_name }}': '{{ project.repo_name }}'}, include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='{{ project.repo_name }}', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
#!/usr/bin/env python import os import sys import {{ project.repo_name }} try: from setuptools import setup except ImportError: from distutils.core import setup if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() readme = open('README.rst', 'rt').read() history = open('HISTORY.rst', 'rt').read() setup( name='{{ project.repo_name }}', version={{ project.repo_name }}.__version__, description='{{ project.project_short_description }}', long_description=readme + '\n\n' + history, author='{{ project.full_name }}', author_email='{{ project.email }}', url='https://github.com/{{ project.github_username }}/{{ project.repo_name }}', packages=[ '{{ project.repo_name }}', ], include_package_data=True, install_requires=[ ], license="BSD", zip_safe=False, keywords='{{ project.repo_name }}', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', "Programming Language :: Python :: 2", 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], test_suite='tests', )
Tests: Make valid-jsdoc an error (instead of warning) Now that the documentation is updated, this makes it an error.
module.exports = { root: true, extends: ['eslint:recommended', 'prettier'], plugins: ['prettier'], parserOptions: { ecmaVersion: 2017, sourceType: 'module', }, env: { browser: true, }, rules: { 'prettier/prettier': ['error', { singleQuote: true, trailingComma: 'es5', printWidth: 100, }], }, overrides: [ { files: ['index.js'], excludedFiles: ['addon-test-support/**', 'tests/**'], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }), }, { files: ['tests/**/*.js'], env: { qunit: true } }, { files: ['index.js', 'addon-test-support/**/*.js', 'config/**/*.js'], plugins: [ 'disable-features', ], rules: { 'disable-features/disable-async-await': 'error', 'disable-features/disable-generator-functions': 'error', } }, { files: ['addon-test-support/**/*.js'], rules: { 'valid-jsdoc': 'error', } }, ] };
module.exports = { root: true, extends: ['eslint:recommended', 'prettier'], plugins: ['prettier'], parserOptions: { ecmaVersion: 2017, sourceType: 'module', }, env: { browser: true, }, rules: { 'prettier/prettier': ['error', { singleQuote: true, trailingComma: 'es5', printWidth: 100, }], }, overrides: [ { files: ['index.js'], excludedFiles: ['addon-test-support/**', 'tests/**'], parserOptions: { sourceType: 'script', }, env: { browser: false, node: true, }, plugins: ['node'], rules: Object.assign({}, require('eslint-plugin-node').configs.recommended.rules, { // add your custom rules and overrides for node files here }), }, { files: ['tests/**/*.js'], env: { qunit: true } }, { files: ['index.js', 'addon-test-support/**/*.js', 'config/**/*.js'], plugins: [ 'disable-features', ], rules: { 'disable-features/disable-async-await': 'error', 'disable-features/disable-generator-functions': 'error', } }, { files: ['addon-test-support/**/*.js'], rules: { 'valid-jsdoc': 'warn', } }, ] };
Upgrade HAProxy to version 2.0.3
from foreman import define_parameter from templates import pods (define_parameter('image-version') .with_doc('HAProxy image version.') .with_default('2.0.3')) @pods.app_specifier def haproxy_app(_): return pods.App( name='haproxy', exec=[ '/usr/local/sbin/haproxy', '-f', '/etc/haproxy/haproxy.cfg', ], volumes=[ pods.Volume( name='etc-hosts-volume', path='/etc/hosts', host_path='/etc/hosts', ), pods.Volume( name='haproxy-volume', path='/etc/haproxy', data='haproxy-volume/haproxy-config.tar.gz', ), ], ports=[ pods.Port( name='web', protocol='tcp', port=8443, host_port=443, ), ], ) @pods.image_specifier def haproxy_image(parameters): return pods.Image( image_build_uri='docker://haproxy:%s' % parameters['image-version'], name='haproxy', app=parameters['haproxy_app'], ) haproxy_image.specify_image.depend('haproxy_app/specify_app') haproxy_image.build_image.depend('//host/docker2aci:install')
from foreman import define_parameter from templates import pods (define_parameter('image-version') .with_doc('HAProxy image version.') .with_default('1.8.9')) @pods.app_specifier def haproxy_app(_): return pods.App( name='haproxy', exec=[ '/usr/local/sbin/haproxy', '-f', '/etc/haproxy/haproxy.cfg', ], volumes=[ pods.Volume( name='etc-hosts-volume', path='/etc/hosts', host_path='/etc/hosts', ), pods.Volume( name='haproxy-volume', path='/etc/haproxy', data='haproxy-volume/haproxy-config.tar.gz', ), ], ports=[ pods.Port( name='web', protocol='tcp', port=8443, host_port=443, ), ], ) @pods.image_specifier def haproxy_image(parameters): return pods.Image( image_build_uri='docker://haproxy:%s' % parameters['image-version'], name='haproxy', app=parameters['haproxy_app'], ) haproxy_image.specify_image.depend('haproxy_app/specify_app') haproxy_image.build_image.depend('//host/docker2aci:install')
Disable tests until new repo is stable Change-Id: Ic6932c1028c72b5600d03ab59102d1c1cff1b36c
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) @testtools.skip class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. import testtools import heat_cfnclient import os import subprocess basepath = os.path.join(heat_cfnclient.__path__[0], os.path.pardir) class CliTest(testtools.TestCase): def test_heat_cfn(self): self.bin_run('heat-cfn') def test_heat_boto(self): self.bin_run('heat-boto') def test_heat_watch(self): self.bin_run('heat-watch') def bin_run(self, bin): fullpath = basepath + '/bin/' + bin proc = subprocess.Popen(fullpath, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout, stderr = proc.communicate() if proc.returncode: print('Error executing %s:\n %s %s ' % (bin, stdout, stderr)) raise subprocess.CalledProcessError(proc.returncode, bin)
Change postcode from Integer to String.
package au.com.auspost.api.postcode.search.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; /** * A single post code locality */ @XmlAccessorType(XmlAccessType.FIELD) public class Locality { @XmlElement private String category; @XmlElement private Integer id; @XmlElement private String location; @XmlElement private String postcode; @XmlElement private AustralianState state; @XmlElement private Float latitude; @XmlElement private Float longitude; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getPostcode() { return postcode; } public void setPostcode(String postcode) { this.postcode = postcode; } public AustralianState getState() { return state; } public void setState(AustralianState state) { this.state = state; } public Float getLatitude() { return latitude; } public void setLatitude(Float latitude) { this.latitude = latitude; } public Float getLongitude() { return longitude; } public void setLongitude(Float longitude) { this.longitude = longitude; } }
package au.com.auspost.api.postcode.search.model; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; /** * A single post code locality */ @XmlAccessorType(XmlAccessType.FIELD) public class Locality { @XmlElement private String category; @XmlElement private Integer id; @XmlElement private String location; @XmlElement private Integer postcode; @XmlElement private AustralianState state; @XmlElement private Float latitude; @XmlElement private Float longitude; public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public Integer getPostcode() { return postcode; } public void setPostcode(Integer postcode) { this.postcode = postcode; } public AustralianState getState() { return state; } public void setState(AustralianState state) { this.state = state; } public Float getLatitude() { return latitude; } public void setLatitude(Float latitude) { this.latitude = latitude; } public Float getLongitude() { return longitude; } public void setLongitude(Float longitude) { this.longitude = longitude; } }
Make active tab rules stricter
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[role='tab'][data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget, eventName = "activeTabPress"; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; var tabid = el.id; //Checks if the active tab wasn't pressed if (this.activeTabId !== tabid) { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; eventName = "tabChange"; } xtag.fireEvent(this, eventName, {detail: this.activeTabId}); } }, accessors: { role: { attribute: {} } }, methods: { } }); })();
(function(){ "use strict"; xtag.register("sam-tabbar", { lifecycle: { created: function() { if (!this.role) { this.role = "tablist"; } }, inserted: function() { this.activeTabId = this.querySelector("[data-start-active]").id; }, removed: function() {}, attributeChanged: function() {} }, events: { "press": function (event) { var el = event.originalTarget, eventName = "activeTabPress"; //Checks if a tab was pressed if (!el || el.getAttribute("role") !== "tab") return; var tabid = el.id; //Checks if the active tab wasn't pressed if (this.activeTabId !== tabid) { document.getElementById(this.activeTabId).dataset.active = false; this.activeTabId = tabid; document.getElementById(this.activeTabId).dataset.active = true; eventName = "tabChange"; } xtag.fireEvent(this, eventName, {detail: this.activeTabId}); } }, accessors: { role: { attribute: {} } }, methods: { } }); })();
Make it easier to clean up tests by closing db sessions Also added a convenience test base class
import gc import sys import unittest PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection from .._util import closing class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute( """ select pg_terminate_backend(pid) from pg_stat_activity where datname = %s """, (self.dbname,)) self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close() class TestCase(DBSetup, unittest.TestCase): pass
import gc import sys PYPY = hasattr(sys, 'pypy_version_info') from .. import pg_connection class DBSetup(object): maxDiff = None @property def dsn(self): return 'postgresql://localhost/' + self.dbname def setUp(self, call_super=True): self.dbname = self.__class__.__name__.lower() + '_newt_test_database' self.base_conn = pg_connection('') self.base_conn.autocommit = True self.base_cursor = self.base_conn.cursor() self.drop_db() self.base_cursor.execute('create database ' + self.dbname) self.call_super = call_super if call_super: super(DBSetup, self).setUp() def drop_db(self): self.base_cursor.execute('drop database if exists ' + self.dbname) def tearDown(self): if self.call_super: super(DBSetup, self).tearDown() if PYPY: # Make sure there aren't any leaked connections around # that would keep us from dropping the DB # (https://travis-ci.org/newtdb/db/jobs/195267673) # This needs a fix from RelStorage post 2.0.0. gc.collect() gc.collect() self.drop_db() self.base_cursor.close() self.base_conn.close()
Add methods to delete a connection
<?php namespace Forestry\Orm; class Storage { /** * @var array */ private static $instances = ['default' => []]; /** * Set a new connection with the given name. * * @param string $name * @param array $config * @return mixed * @throws \LogicException * @throws \PDOException */ public static function set($name = 'default', array $config = []) { if(isset(self::$instances[$name]) && self::$instances[$name] instanceof \PDO) { throw new \LogicException(sprintf('Connection "%s" already set', $name)); } self::$instances[$name] = new \PDO( isset($config['dsn']) ? $config['dsn'] : 'mysql:host=localhost', isset($config['user']) ? $config['user'] : 'root', isset($config['password']) ? $config['password']: '', isset($config['option']) ? $config['option'] : array() ); return self::$instances[$name]; } /** * Creates a new instance of PDO or returns an existing one. * * @param string $name * @return \PDO * @throws \OutOfBoundsException */ public static function get($name) { if(!isset(self::$instances[$name])) { throw new \OutOfBoundsException(sprintf('Storage "%s" not set', $name)); } return self::$instances[$name]; } /** * Closes the connection. * * @param string $name * @return bool * @throws \OutOfBoundsException */ public static function delete($name) { if(!isset(self::$instances[$name])) { throw new \OutOfBoundsException(sprintf('Storage "%s" not set', $name)); } self::$instances[$name] = null; return true; } }
<?php namespace Forestry\Orm; class Storage { /** * @var array */ private static $instances = ['default' => []]; /** * Set a new connection with the given name. * * @param string $name * @param array $config * @return mixed * @throws \LogicException * @throws \PDOException */ public static function set($name = 'default', array $config = []) { if(isset(self::$instances[$name]) && self::$instances[$name] instanceof \PDO) { throw new \LogicException(sprintf('Connection "%s" already set', $name)); } self::$instances[$name] = new \PDO( isset($config['dsn']) ? $config['dsn'] : 'mysql:host=localhost', isset($config['user']) ? $config['user'] : 'root', isset($config['password']) ? $config['password']: '', isset($config['option']) ? $config['option'] : array() ); return self::$instances[$name]; } /** * Creates a new instance of PDO or returns an existing one. * * @param string $name * @return \PDO * @throws \OutOfBoundsException */ public static function get($name) { if(!isset(self::$instances[$name])) { throw new \OutOfBoundsException(sprintf('Storage "%s" not set', $name)); } return self::$instances[$name]; } }