text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Fix Bugs in module when using -O option
#--coding:utf-8-- #Platform class BasePrompt(object): pass class ErrPrompt(BasePrompt): """ Define some of Err Prompts Usually print to sys.stderr """ def PrintErr(self, content): import sys """ Automous write content to sys.stderr and add '\n' to the end """ sys.stderr.write(content + '\n') sys.stderr.flush() def IllegalURL(self): """ For URL with illegal characters """ self.PrintErr("Error: URL include illegal characters!") def FileExist(self, File = "File"): """ return True if want to replace, and False for the other """ self.PrintErr("Warning: '%s' already exists, replace?(y/n)" %(File)) tmp = raw_input() if tmp == 'y' or tmp == 'Y': return True return False def Exit(self): self.PrintErr("Info: Terminated") if __name__ == '__main__': raise EnvironmentError ("DO NOT DIRECTLY RUN THIS TEMPLATE!")
#--coding:utf-8-- #Platform class BasePrompt(object): pass class ErrPrompt(BasePrompt): """ Define some of Err Prompts Usually print to sys.stderr """ def PrintErr(self, content): import sys """ Automous write content to sys.stderr and add '\n' to the end """ sys.stderr.write(content + '\n') sys.stderr.flush() def IllegalURL(self): """ For URL with illegal characters """ self.PrintErr("Error: URL include illegal characters!") def FileExist(self, File = "File"): """ return True if want to replace, and False for the other """ self.PrintErr("Warning: '%s' already exists, replace?(y/n)" %(Files)) tmp = raw_input() if tmp == 'y' or tmp == 'Y': return True return False def Exit(self): self.PrintErr("Info: Terminated") if __name__ == '__main__': raise EnvironmentError ("DO NOT DIRECTLY RUN THIS TEMPLATE!")
Add mock X-Forwarded-For header in trackable tests
# -*- coding: utf-8 -*- """ test_trackable ~~~~~~~~~~~~~~ Trackable tests """ import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'}) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == '127.0.0.1' assert user.login_count == 2
# -*- coding: utf-8 -*- """ test_trackable ~~~~~~~~~~~~~~ Trackable tests """ import pytest from utils import authenticate, logout pytestmark = pytest.mark.trackable() def test_trackable_flag(app, client): e = 'matt@lp.com' authenticate(client, email=e) logout(client) authenticate(client, email=e) with app.app_context(): user = app.security.datastore.find_user(email=e) assert user.last_login_at is not None assert user.current_login_at is not None assert user.last_login_ip == 'untrackable' assert user.current_login_ip == 'untrackable' assert user.login_count == 2
Cover every case for CaseInsensitiveBooleanFilter
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field].lower() if val == 'true': boolean_filters[field] = True elif val == 'false': boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
from rest_framework import filters class CaseInsensitiveBooleanFilter(filters.BaseFilterBackend): """Set a boolean_fields tuple on the viewset and set this class as a filter_backend to filter listed fields through a case-insensitive transformation to be used for filtering. i.e. query params such as 'true' become boolean True, and params with a value 'false' become boolean False.""" def filter_queryset(self, request, queryset, view): boolean_fields = getattr(view, 'boolean_fields', None) if not boolean_fields: return queryset boolean_filters = {} for field in boolean_fields: if field in request.QUERY_PARAMS: val = request.QUERY_PARAMS[field] if val in ['true', 'True']: boolean_filters[field] = True elif val in ['false', 'False']: boolean_filters[field] = False if len(boolean_filters) > 0: return queryset.filter(**boolean_filters) return queryset
Move flow webpack plugin to only development
const path = require('path'); const ELECTRON_RENDERER_PROCESS_ROOT = path.resolve(__dirname, 'src/renderer/'); module.exports = { // This rule is temporarily necessary until https://github.com/electron-userland/electron-webpack/issues/60 is fixed. module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', options: { presets: ['env', 'react', 'stage-2'] } } ] }, // This allows imports to be made from the renderer process root (https://moduscreate.com/blog/es6-es2015-import-no-relative-path-webpack/). resolve: { modules: [ELECTRON_RENDERER_PROCESS_ROOT, 'node_modules', __dirname], extensions: ['.js', '.jsx', '.scss'] } }; if (process.env.NODE_ENV === 'development') { const FLOW_BABEL_WEBPACK_PLUGIN = require('./src/renderer/flowtype-plugin'); module.exports.plugins = [ new FLOW_BABEL_WEBPACK_PLUGIN({ warn: true }) ] }
const path = require('path'); const FlowBabelWebpackPlugin = require('./src/renderer/flowtype-plugin'); const ELECTRON_RENDERER_PROCESS_ROOT = path.resolve(__dirname, 'src/renderer/'); module.exports = { // This rule is temporarily necessary until https://github.com/electron-userland/electron-webpack/issues/60 is fixed. module: { rules: [ { test: /\.jsx?$/, loader: 'babel-loader', options: { presets: ['env', 'react', 'stage-2'] } } ] }, // This allows imports to be made from the renderer process root (https://moduscreate.com/blog/es6-es2015-import-no-relative-path-webpack/). resolve: { modules: [ELECTRON_RENDERER_PROCESS_ROOT, 'node_modules', __dirname], extensions: ['.js', '.jsx', '.scss'] }, plugins: [ new FlowBabelWebpackPlugin({ warn: true }) ] };
Remove unknown sources from SM
"use strict"; const path = require("path"); const { SourceMapConsumer } = require("source-map"); const getBytesPerFileUsingSourceMap = (bundleId, code, map, dir) => { const modules = Object.create(null); let line = 1; let column = 0; for (let i = 0; i < code.length; i++, column++) { const { source } = map.originalPositionFor({ line, column, }); if (source != null) { const id = path.resolve(path.dirname(path.join(dir, bundleId)), source); modules[id] = modules[id] || { renderedLength: 0 }; modules[id].renderedLength += 1; } if (code[i] === "\n") { line += 1; column = -1; } } return modules; }; const getSourcemapModules = (id, { map, code }, dir) => { return SourceMapConsumer.with(map, null, (map) => { return getBytesPerFileUsingSourceMap(id, code, map, dir); }); }; module.exports = getSourcemapModules;
"use strict"; const path = require("path"); const { SourceMapConsumer } = require("source-map"); const UNKNOWN_SOURCE = "\u0000unknown"; const getBytesPerFileUsingSourceMap = (bundleId, code, map, dir) => { const modules = Object.create(null); let line = 1; let column = 0; for (let i = 0; i < code.length; i++, column++) { const { source } = map.originalPositionFor({ line, column, }); const id = source == null ? `${UNKNOWN_SOURCE}-${bundleId}` : path.resolve(path.dirname(path.join(dir, bundleId)), source); modules[id] = modules[id] || { renderedLength: 0 }; modules[id].renderedLength += 1; if (code[i] === "\n") { line += 1; column = -1; } } return modules; }; const getSourcemapModules = (id, { map, code }, dir) => { return SourceMapConsumer.with(map, null, (map) => { return getBytesPerFileUsingSourceMap(id, code, map, dir); }); }; module.exports = getSourcemapModules;
Make message object types strict
/* eslint-disable no-unused-vars */ type ConnectMessage = {| type: 'CONNECT', chorusClientId: string, description: string, |} type PublishStepMessage = {| type: 'PUBLISH_STEP', chorusClientId: string, stepId: string, pattern: string, pendingMessage?: string, technicalDescription?: string, |} type StepsAlignedMessage = {| type: 'STEPS_ALIGNED', chorusClientId: string, |} type StepSucceededMessage = {| type: 'STEP_SUCCEEDED', chorusClientId: string, stepId: string, executionId: string, result?: number | string | void, contextVariables: Object, |} type StepFailedMessage = {| type: 'STEP_FAILED', chorusClientId: string, stepId: string, executionId: string, description?: string, errorText?: string, |} type OutgoingMessage = ConnectMessage | PublishStepMessage | StepsAlignedMessage | StepSucceededMessage | StepFailedMessage; type ExecuteStepMessage = {| type: 'EXECUTE_STEP', chorusClientId: string, stepId: string, executionId: string, pattern: string, arguments: Array<string>, timeoutPeriodSeconds: number, contextVariables: Object, |}
/* eslint-disable no-unused-vars */ type ConnectMessage = { type: 'CONNECT', chorusClientId: string, description: string, } type PublishStepMessage = { type: 'PUBLISH_STEP', chorusClientId: string, stepId: string, pattern: string, pendingMessage?: string, technicalDescription?: string, } type StepsAlignedMessage = { type: 'STEPS_ALIGNED', chorusClientId: string, } type StepSucceededMessage = { type: 'STEP_SUCCEEDED', chorusClientId: string, stepId: string, executionId: string, result?: number | string | void, contextVariables: Object, } type StepFailedMessage = { type: 'STEP_FAILED', chorusClientId: string, stepId: string, executionId: string, description?: string, errorText?: string, } type OutgoingMessage = ConnectMessage | PublishStepMessage | StepsAlignedMessage | StepSucceededMessage | StepFailedMessage; type ExecuteStepMessage = { type: 'EXECUTE_STEP', chorusClientId: string, stepId: string, executionId: string, pattern: string, arguments: Array<string>, timeoutPeriodSeconds: number, contextVariables: Object, }
Fix 414 url too long
<?php /** * Created by PhpStorm. * User: anton * Date: 22.02.17 * Time: 10:49 * * * @property string[] $paragraphesArray */ namespace frontend\models; class Work extends \common\models\Work { private $parDelimiter = "\r\n"; public function getTitleShort() { return (empty($this->title_short)) ? $this->title : $this->title_short; } public function getDescriptionShort() { return (empty($this->description_short)) ? $this->getTitleShort() : $this->description_short; } public function getParagraphesArray() { $paragraphesRaw = $this->description; $paragraphesArray = explode($this->parDelimiter, $paragraphesRaw); return $paragraphesArray; } public function getSocialDescription() { return mb_substr(str_replace("\r\n", " ", $this->description), 0, 400) . "..."; } }
<?php /** * Created by PhpStorm. * User: anton * Date: 22.02.17 * Time: 10:49 * * * @property string[] $paragraphesArray */ namespace frontend\models; class Work extends \common\models\Work { private $parDelimiter = "\r\n"; public function getTitleShort() { return (empty($this->title_short)) ? $this->title : $this->title_short; } public function getDescriptionShort() { return (empty($this->description_short)) ? $this->getTitleShort() : $this->description_short; } public function getParagraphesArray() { $paragraphesRaw = $this->description; $paragraphesArray = explode($this->parDelimiter, $paragraphesRaw); return $paragraphesArray; } public function getSocialDescription() { return str_replace("\r\n", " ", $this->description); } }
Fix user cart recalculation listener
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\EventListener; use Sylius\Bundle\UserBundle\Event\UserEvent; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Order\Context\CartContextInterface; use Sylius\Component\Order\Context\CartNotFoundException; use Sylius\Component\Order\Processor\OrderProcessorInterface; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Webmozart\Assert\Assert; final class UserCartRecalculationListener { /** @var CartContextInterface */ private $cartContext; /** @var OrderProcessorInterface */ private $orderProcessor; public function __construct(CartContextInterface $cartContext, OrderProcessorInterface $orderProcessor) { $this->cartContext = $cartContext; $this->orderProcessor = $orderProcessor; } /** * @param InteractiveLoginEvent|UserEvent $event */ public function recalculateCartWhileLogin(object $event): void { try { $cart = $this->cartContext->getCart(); } catch (CartNotFoundException $exception) { return; } Assert::isInstanceOf($cart, OrderInterface::class); $this->orderProcessor->process($cart); } }
<?php /* * This file is part of the Sylius package. * * (c) Paweł Jędrzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ declare(strict_types=1); namespace Sylius\Bundle\CoreBundle\EventListener; use Sylius\Component\Core\Model\OrderInterface; use Sylius\Component\Order\Context\CartContextInterface; use Sylius\Component\Order\Context\CartNotFoundException; use Sylius\Component\Order\Processor\OrderProcessorInterface; use Symfony\Contracts\EventDispatcher\Event; use Webmozart\Assert\Assert; final class UserCartRecalculationListener { /** @var CartContextInterface */ private $cartContext; /** @var OrderProcessorInterface */ private $orderProcessor; public function __construct(CartContextInterface $cartContext, OrderProcessorInterface $orderProcessor) { $this->cartContext = $cartContext; $this->orderProcessor = $orderProcessor; } public function recalculateCartWhileLogin(Event $event): void { try { $cart = $this->cartContext->getCart(); } catch (CartNotFoundException $exception) { return; } Assert::isInstanceOf($cart, OrderInterface::class); $this->orderProcessor->process($cart); } }
Improve tests on the post render.
/*global window*/ (function(NS) { NS = NS || {}; var isInBrowser = typeof module === 'undefined' && typeof window !== 'undefined'; //Container for all the post renderings functions. var postRenderingHelpers = {}; //Register a helper inside the application. var registerHelper = function registerHelper(helper) { postRenderingHelpers[helper.name] = {fn: helper.fn, options: helper.options}; }; //Options must have a selector property and a helperName one. var callHelper = function( config) { //If there is nothing selected. if(config.selector === undefined || config.selector.size() === 0){ return; } //If the function desn not exist on the selection. if(config.selector[postRenderingHelpers[config.helperName].fn] === undefined){ return; } config.selector[postRenderingHelpers[config.helperName].fn](postRenderingHelpers[config.helperName].options); //config.selector[config.helperName](options); }; var mdl = { registerHelper: registerHelper, callHelper: callHelper }; // Differenciating export for node or browser. if (isInBrowser) { NS.Helpers = NS.Helpers || {}; NS.Helpers.postRenderingHelper = mdl; } else { module.exports = mdl; } })(typeof module === 'undefined' && typeof window !== 'undefined' ? window.Fmk : module.exports);
/*global window*/ (function(NS) { NS = NS || {}; var isInBrowser = typeof module === 'undefined' && typeof window !== 'undefined'; //Container for all the post renderings functions. var postRenderingHelpers = {}; //Register a helper inside the application. var registerHelper = function registerHelper(helper) { postRenderingHelpers[helper.name] = {fn: helper.fn, options: helper.options}; }; //Options must have a selector property and a helperName one. var callHelper = function( config) { if(config.selector === undefined || config.selector.size() === 0){ return; } config.selector[postRenderingHelpers[config.helperName].fn](postRenderingHelpers[config.helperName].options); //config.selector[config.helperName](options); }; var mdl = { registerHelper: registerHelper, callHelper: callHelper }; // Differenciating export for node or browser. if (isInBrowser) { NS.Helpers = NS.Helpers || {}; NS.Helpers.postRenderingHelper = mdl; } else { module.exports = mdl; } })(typeof module === 'undefined' && typeof window !== 'undefined' ? window.Fmk : module.exports);
Fix bug with crud creation
<?php namespace Ubiquity\devtools\cmd\commands; use Ubiquity\devtools\core\ConsoleScaffoldController; use Ubiquity\devtools\cmd\ConsoleFormatter; use Ubiquity\cache\CacheManager; class CrudCmd extends AbstractCmdModel{ public static function run(&$config,$options,$what){ $resource=self::answerModel($options, 'r', 'resource', 'crud-controller', $config); if(class_exists($resource)){ CacheManager::start($config); $scaffold=new ConsoleScaffoldController(); $crudDatas=self::getOption($options, 'd', 'datas',true); $crudViewer=self::getOption($options, 'v', 'viewer',true); $crudEvents=self::getOption($options, 'e', 'events',true); $crudViews=self::getOption($options, 't', 'templates','index,form,display'); $routePath=self::getOption($options, 'p', 'path',''); $scaffold->addCrudController($what, $resource,$crudDatas,$crudViewer,$crudEvents,$crudViews,$routePath); }else{ echo ConsoleFormatter::showMessage("The models class <b>{$resource}</b> does not exists!",'error','crud-controller'); } } }
<?php namespace Ubiquity\devtools\cmd\commands; use Ubiquity\devtools\core\ConsoleScaffoldController; use Ubiquity\devtools\cmd\ConsoleFormatter; class CrudCmd extends AbstractCmdModel{ public static function run(&$config,$options,$what){ $resource=self::answerModel($options, 'r', 'resource', 'crud-controller', $config); if(class_exists($resource)){ $scaffold=new ConsoleScaffoldController(); $crudDatas=self::getOption($options, 'd', 'datas',true); $crudViewer=self::getOption($options, 'v', 'viewer',true); $crudEvents=self::getOption($options, 'e', 'events',true); $crudViews=self::getOption($options, 't', 'templates','index,form,display'); $routePath=self::getOption($options, 'p', 'path',''); $scaffold->addCrudController($what, $resource,$crudDatas,$crudViewer,$crudEvents,$crudViews,$routePath); }else{ echo ConsoleFormatter::showMessage("The models class <b>{$resource}</b> does not exists!",'error','crud-controller'); } } }
Make minor formatting change in tests
package tokenizer import ( "io/ioutil" "testing" ) func TestEnglish001(t *testing.T) { files := []string{ "testdata/input-org-syn.txt", "testdata/input-te-wiki.txt", } for _, fn := range files { t.Logf("%-8s : %s", "TEST", fn) bs, err := ioutil.ReadFile(fn) if err != nil { t.Fatalf("%-8s : Input data file '%s' could not be read : %s", "FATAL", fn, err.Error()) } size := len(bs) ti := NewTextTokenIterator(string(bs)) var toks []*TextToken for err = ti.MoveNext(); err == nil; err = ti.MoveNext() { toks = append(toks, ti.Item()) } lt := toks[len(toks)-1] if lt.End() != size - 1 { t.Errorf("%-8s : Token offset drift by EOF. Expected : %d, observed : %d", "FAIL", size, lt.End()) } t.Logf("%-8s : %s", "SUCCESS", fn) } }
package tokenizer import ( "io/ioutil" "testing" ) func TestEnglish001(t *testing.T) { files := []string{ "testdata/input-org-syn.txt", "testdata/input-te-wiki.txt", } for _, fn := range files { t.Logf("TEST : %s", fn) bs, err := ioutil.ReadFile(fn) if err != nil { t.Fatalf("FATAL : Input data file '%s' could not be read : %s", fn, err.Error()) } size := len(bs) ti := NewTextTokenIterator(string(bs)) var toks []*TextToken for err = ti.MoveNext(); err == nil; err = ti.MoveNext() { toks = append(toks, ti.Item()) } lt := toks[len(toks)-1] if lt.End() != size - 1 { t.Errorf("FAIL : Token offset drift by EOF. Expected : %d, observed : %d", size, lt.End()) } t.Logf("SUCCESS : %s", fn) } }
Fix http keep-alive connection timeout event error
<?php /** * Aurora - A HTTP Application Server of PHP Script * * @author panlatent@gmail.com * @link https://github.com/panlatent/aurora * @license https://opensource.org/licenses/MIT */ namespace Aurora\Http\Client; use Aurora\Http\ServerTimestampType; use Aurora\Timer\TimestampMarker; class Events extends \Aurora\Client\Events { /** * @var \Aurora\Http\Client */ protected $bind; public function register() { parent::register(); /** * @todo Client connection execute timeout * @todo Client request execute timeout */ $this->timer->insert(function() { $timestamp = $this->bind->timestamp(); if ($requestLastUT = $timestamp->get(ServerTimestampType::RequestLast)) { // HTTP Connection keep-alive timeout $interval = TimestampMarker::interval($requestLastUT); $timeout = $this->bind->config()->permanent_connection_wait_timeout; if ($interval >= $timeout || TimestampMarker::intervalEqual($timeout, $interval, 0.25)) { $this->bind->declareClose(); } } }); } }
<?php /** * Aurora - A HTTP Application Server of PHP Script * * @author panlatent@gmail.com * @link https://github.com/panlatent/aurora * @license https://opensource.org/licenses/MIT */ namespace Aurora\Http\Client; use Aurora\Http\ServerTimestampType; use Aurora\Timer\TimestampMarker; class Events extends \Aurora\Client\Events { /** * @var \Aurora\Http\Client */ protected $bind; public function register() { parent::register(); /** * @todo Client connection execute timeout * @todo Client request execute timeout */ $this->timer->insert(function() { $timestamp = $this->bind->timestamp(); if ($requestLastUT = $timestamp->get(ServerTimestampType::RequestLast)) { // HTTP Connection keep-alive timeout $interval = TimestampMarker::interval($requestLastUT); $timeout = $this->bind->config()->permanent_connection_wait_timeout; if ($interval >= $timeout || TimestampMarker::intervalEqual($timeout, $interval, 0.25)) { $this->bind->close(); } } }); } }
Add option to get week day
<?php /** * Created by PhpStorm. * User: mirel * Date: 04.10.2016 * Time: 11:26 */ namespace mpf\helpers; use mpf\base\LogAwareObject; class CalendarDay extends LogAwareObject { public $date, $time, $callBacks, $inCurrentMonth, $dayNumber; public function __get($name) { if (isset($this->callBacks[$name])) return call_user_func($this->callBacks[$name], $this); $this->error("Unknown attribute '$name'!"); } /** * @return bool */ public function isToday() { return date('Y-m-d') == $this->date; } public function getWeekDay(){ return date('l', $this->time); } }
<?php /** * Created by PhpStorm. * User: mirel * Date: 04.10.2016 * Time: 11:26 */ namespace mpf\helpers; use mpf\base\LogAwareObject; class CalendarDay extends LogAwareObject { public $date, $time, $callBacks, $inCurrentMonth, $dayNumber; public function __get($name) { if (isset($this->callBacks[$name])) return call_user_func($this->callBacks[$name], $this); $this->error("Unknown attribute '$name'!"); } /** * @return bool */ public function isToday() { return date('Y-m-d') == $this->date; } }
Increase loglevel during test execution
# Copyright 2015 SAP SE. # # 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 logging from sqlalchemy import event, Column, Sequence from sqlalchemy.dialects import registry logging.getLogger('sqlalchemy.engine').setLevel(logging.DEBUG) registry.register("hana", "sqlalchemy_hana.dialect", "HANAHDBCLIDialect") registry.register("hana.hdbcli", "sqlalchemy_hana.dialect", "HANAHDBCLIDialect") registry.register("hana.pyhdb", "sqlalchemy_hana.dialect", "HANAPyHDBDialect") @event.listens_for(Column, "after_parent_attach") def add_test_seq(column, table): if column.info.get('test_needs_autoincrement', False): column._init_items( Sequence(table.name + '_' + column.name + '_seq') ) from sqlalchemy.testing.plugin.pytestplugin import *
# Copyright 2015 SAP SE. # # 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 sqlalchemy import event, Column, Sequence from sqlalchemy.dialects import registry registry.register("hana", "sqlalchemy_hana.dialect", "HANAHDBCLIDialect") registry.register("hana.hdbcli", "sqlalchemy_hana.dialect", "HANAHDBCLIDialect") registry.register("hana.pyhdb", "sqlalchemy_hana.dialect", "HANAPyHDBDialect") @event.listens_for(Column, "after_parent_attach") def add_test_seq(column, table): if column.info.get('test_needs_autoincrement', False): column._init_items( Sequence(table.name + '_' + column.name + '_seq') ) from sqlalchemy.testing.plugin.pytestplugin import *
Use specified version or increment current version.
module.exports = function (grunt) { var curver = require('../../package.json').version; var semver = require('semver'); var version = grunt.option('version'); function bump () { return version ? version : semver.inc(curver); } function file (path) { return { dest: path, src: path }; } return { release: { options: { patterns: [ { match: new RegExp(curver), replacement: bump } ] }, files: [ file('src/version.js'), file('bower.json'), file('package.json') ] } }; };
module.exports = function (grunt) { var semver = require('semver'); var version = grunt.option('version'); function bump () { //console.log(arguments[0][0]); } function file (path) { return { dest: path, src: path }; } function pattern (find) { return { match: find, replacement: bump }; } return { release: { options: { patterns: [ pattern(/version: '([^\']+)';/), pattern(/"version": "([^\']+)"/) ] }, files: [ file('src/version.js'), file('bower.json'), file('package.json') ] } }; };
Fix incorrect service name in compiler pass
<?php namespace Palmtree\CanonicalUrlBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class CompilerPass implements CompilerPassInterface { /** * @inheritDoc */ public function process(ContainerBuilder $container) { $bundleConfig = $container->getParameter('palmtree_canonical_url.config'); $definition = $container->getDefinition('palmtree_canonical_url.url_generator'); $definition->addArgument($bundleConfig); $definition = $container->getDefinition('palmtree_canonical_url.request_listener'); $definition->addArgument($bundleConfig); $definition = $container->getDefinition('palmtree_canonical_url.exception_listener'); $definition->addArgument($bundleConfig); } }
<?php namespace Palmtree\CanonicalUrlBundle\DependencyInjection\Compiler; use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface; use Symfony\Component\DependencyInjection\ContainerBuilder; class CompilerPass implements CompilerPassInterface { /** * @inheritDoc */ public function process(ContainerBuilder $container) { $bundleConfig = $container->getParameter('palmtree_canonical_url.config'); $definition = $container->getDefinition('palmtree_canonical_url.url_generator'); $definition->addArgument($bundleConfig); $definition = $container->getDefinition('palmtree_canonical_url.kernel_event_listener'); $definition->addArgument($bundleConfig); } }
Set up database according to environment
import os import peewee class IBModel(peewee.Model): class Meta: database = db class User(IBModel): user_id = peewee.CharField(max_length=128, primary_key=True) auth_token = peewee.TextField() class Module(IBModel): module_id = peewee.TextField() module_code = peewee.CharField(max_length=16) acad_year = peewee.CharField(max_length=16) semester = peewee.IntegerField() class Meta: primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester') def setup_database(): db.connect() try: db.create_tables([User, Module]) except peewee.OperationalError as e: print(e) if __name__ == '__main__': if 'HEROKU' in os.environ: import urlparse urlparse.uses_netloc.append('postgres') url = urlparse.urlparse(os.environ["DATABASE_URL"]) db = PostgresqlDatabase(database=url.path[1:], user=url.username, password=url.password, host=url.hostname, port=url.port) else: db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres') setup_database()
import peewee db = peewee.PostgresqlDatabase('ivle_bot_test', user='postgres') class IBModel(peewee.Model): class Meta: database = db class User(IBModel): user_id = peewee.CharField(max_length=128, primary_key=True) auth_token = peewee.TextField() class Module(IBModel): module_id = peewee.TextField() module_code = peewee.CharField(max_length=16) acad_year = peewee.CharField(max_length=16) semester = peewee.IntegerField() class Meta: primary_key = peewee.CompositeKey('module_code', 'acad_year', 'semester') def setup_database(): db.connect() try: db.create_tables([User, Module]) except peewee.OperationalError as e: print(e)
Insert new player data into db
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) insert_sql = "INSERT INTO players (auto_pin) VALUES ('%s')" id_sql = "SELECT LAST_INSERT_ID()" cursor.execute(insert_sql, (new_pin)) cursor.execute(id_sql) insert_data = cursor.fetchone() return jsonify({ 'id' : insert_data[0], 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500) finally: cursor.close()
"""This module provides views for application.""" from tof_server import app, versioning, mysql from flask import jsonify, make_response import string, random @app.route('/') def index(): """Server information""" return jsonify({ 'server-version' : versioning.SERVER_VERSION, 'client-versions' : versioning.CLIENT_VERSIONS }) @app.route('/players', methods=['POST']) def generate_new_id(): """Method for generating new unique player ids""" try: cursor = mysql.connection.cursor() new_pin = '' characters_pool = string.ascii_uppercase + string.digits for _ in range(8): new_pin = new_pin + random.SystemRandom().choice(characters_pool) return jsonify({ 'id' : 'somestubid', 'pin' : new_pin }) except Exception as er_msg: return make_response(jsonify({ 'error' : str(er_msg) }), 500) finally: cursor.close()
Rename Util.prep Util.escape. Deprecate former.
define([ 'underscore' ], function (_) { var Util = {}; /** * @return {string} empty string if s is null or undefined, otherwise result of _.escape(s) */ Util.escape = function (s) { if (s == undefined || s == null) return ""; return _.escape(s); }; /** @deprecated Since 0.6. Use Util.escape */ Util.prep = Util.escape; function isWholeNumber(v) { return (Math.abs(Math.round(v) - v) < 0.000000000001); } Util.roundIfNumberToNumDecimalPlaces = function (v, mantissa) { if (!_.isNumber(v) || mantissa < 0) return v; if (isWholeNumber(v)) return Math.round(v); var vk = v, xp = 1; for (var i=0; i < mantissa; i++) { vk *= 10; xp *= 10; if (isWholeNumber(vk)) { return Math.round(vk)/xp; } } return Number(v.toFixed(mantissa)) }; return Util; });
define([ 'underscore' ], function (_) { var Util = {}; // TODO: Also rename /** preps data for output */ Util.prep = function (s) { if (s==null) return ""; return _.escape(s); }; function isWholeNumber(v) { return (Math.abs(Math.round(v) - v) < 0.000000000001); } Util.roundIfNumberToNumDecimalPlaces = function (v, mantissa) { if (!_.isNumber(v) || mantissa < 0) return v; if (isWholeNumber(v)) return Math.round(v); var vk = v, xp = 1; for (var i=0; i < mantissa; i++) { vk *= 10; xp *= 10; if (isWholeNumber(vk)) { return Math.round(vk)/xp; } } return Number(v.toFixed(mantissa)) }; return Util; });
Use HTTPS fallback for reverse proxies When using a reverse proxy, like CloudFlare, detecting HTTPS with $_SERVER["HTTPS"] does not work. Instead, HTTPS can be detected through checking $_SERVER["HTTP_X_FORWARDED_PROTO"].
<?php class Utility { public function __construct() { // } public static function displayError($message) { // Clear the buffer. ob_end_clean(); // Terminate with an error message. exit("Error: {$message}."); } public static function getRootAddress() { $host = $_SERVER["HTTP_HOST"]; $protocol; if (!empty($_SERVER["HTTP_X_FORWARDED_PROTO"])) { $protocol = $_SERVER["HTTP_X_FORWARDED_PROTO"] . "://"; } else { if (!empty($_SERVER["HTTPS"])) { $protocol = "https://"; } else { $protocol = "http://"; } } $sub_directory = substr( dirname(dirname(__DIR__)), strlen($_SERVER["DOCUMENT_ROOT"]) ); // Return absolute URL of where Kaku is installed. return $protocol . $host . $sub_directory; } } ?>
<?php class Utility { public function __construct() { // } public static function displayError($message) { // Clear the buffer. ob_end_clean(); // Terminate with an error message. exit("Error: {$message}."); } public static function getRootAddress() { $host = $_SERVER["HTTP_HOST"]; $protocol = $_SERVER["SERVER_PROTOCOL"]; $protocol = strtolower(substr($protocol, 0, strpos($protocol, "/"))); $protocol .= "://"; $sub_directory = substr( dirname(dirname(__DIR__)), strlen($_SERVER["DOCUMENT_ROOT"]) ); // Return absolute URL of where Kaku is installed. return $protocol . $host . $sub_directory; } } ?>
Update Master Corps - Index
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Mscorps extends Back_end { public $model = 'model_master_corps'; public function __construct() { parent::__construct('kelola_pustaka_corps', 'Pustaka corps'); } public function index() { parent::index(); $this->set("bread_crumb", array( "#" => $this->_header_title )); } public function detail($id = FALSE) { parent::detail($id, array("kode_corps", "init_corps", "ur_corps",)); $this->set("bread_crumb", array( "back_end/" . $this->_name => $this->_header_title, "#" => 'Pendaftaran ' . $this->_header_title )); // $this->add_jsfiles(array("avant/plugins/form-jasnyupload/fileinput.min.js")); } public function get_like() { $keyword = $this->input->post("keyword"); $corps_found = $this->model_master_corps->get_like($keyword); $this->to_json($corps_found); } }
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Mscorps extends Back_end { public $model = 'model_master_corps'; public function __construct() { parent::__construct('kelola_pustaka_corps', 'Pustaka corps'); } public function index() { parent::index(); $this->set("bread_crumb", array( "#" => $this->_header_title )); } public function detail($id = FALSE) { parent::detail($id, array( "kode_corps","init_corps","ur_corps", )); $this->set("bread_crumb", array( "back_end/" . $this->_name => $this->_header_title, "#" => 'Pendaftaran ' . $this->_header_title )); // $this->add_jsfiles(array("avant/plugins/form-jasnyupload/fileinput.min.js")); } public function get_like() { $keyword = $this->input->post("keyword"); $corps_found = $this->model_ref_corps->get_like($keyword); $this->to_json($corps_found); } }
Remove --dev from composer install. --dev is the default.
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0); $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
#!/usr/bin/env php <?php chdir(__DIR__); $returnStatus = null; passthru('composer install --dev', $returnStatus); if ($returnStatus !== 0) { exit(1); } require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsArguments = array('standard' => array('PSR1'), 'files' => array('src', 'tests', 'build.php'), 'warningSeverity' => 0); $phpcsViolations = $phpcsCLI->process($phpcsArguments); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = array('coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration); $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments); if (!$result->wasSuccessful()) { exit(1); } $coverageFactory = new PHP_CodeCoverage_Report_Factory(); $coverageReport = $coverageFactory->create($result->getCodeCoverage()); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } echo "Code coverage was 100%\n";
[BUGFIX] Fix the path pointing to the main config file inside the r.js task
/** * Grunt-Contrib-RequireJS * @description Optimize RequireJS projects using r.js. * @docs https://github.com/gruntjs/grunt-contrib-requirejs */ var config = require("../Config"); module.exports = { deploy: { options: { mainConfigFile: config.JavaScripts.paths.devDir + "/" + config.JavaScripts.requireJS.config + ".js", include: [config.JavaScripts.requireJS.libSourceFile, config.JavaScripts.requireJS.config], out: config.JavaScripts.requireJS.compileDistFile, // Wrap in an IIFE wrap: true, // Generate source maps for the build. generateSourceMaps: true, // Do not preserve license comments when working with source maps, incompatible. preserveLicenseComments: false, // Uglify the build with 'uglify2'. optimize: 'uglify2', } } };
/** * Grunt-Contrib-RequireJS * @description Optimize RequireJS projects using r.js. * @docs https://github.com/gruntjs/grunt-contrib-requirejs */ var config = require("../Config"); module.exports = { deploy: { options: { mainConfigFile: config.JavaScripts.devDir + "/" + config.JavaScripts.requireJS.config + ".js", include: [config.JavaScripts.requireJS.libSourceFile, config.JavaScripts.requireJS.config], out: config.JavaScripts.requireJS.compileDistFile, // Wrap in an IIFE wrap: true, // Generate source maps for the build. generateSourceMaps: true, // Do not preserve license comments when working with source maps, incompatible. preserveLicenseComments: false, // Uglify the build with 'uglify2'. optimize: 'uglify2' } } };
Make window.hasOwnProperty work in IE8.
Object.getOwnPropertyNames = function getOwnPropertyNames(object) { var buffer = []; var key; // Non-enumerable properties cannot be discovered but can be checked for by name. // Define those used internally by JS to allow an incomplete solution var commonProps = ['length', "name", "arguments", "caller", "prototype", "observe", "unobserve"]; if (typeof object === 'undefined' || object === null) { throw new TypeError('Cannot convert undefined or null to object'); } object = Object(object); // Enumerable properties only for (key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { buffer.push(key); } } // Check for and add the common non-enumerable properties for (var i=0, s=commonProps.length; i<s; i++) { if (commonProps[i] in object) buffer.push(commonProps[i]); } return buffer; };
Object.getOwnPropertyNames = function getOwnPropertyNames(object) { var buffer = []; var key; // Non-enumerable properties cannot be discovered but can be checked for by name. // Define those used internally by JS to allow an incomplete solution var commonProps = ['length', "name", "arguments", "caller", "prototype", "observe", "unobserve"]; if (typeof object === 'undefined' || object === null) { throw new TypeError('Cannot convert undefined or null to object'); } object = Object(object); // Enumerable properties only for (key in object) { if (object.hasOwnProperty(key)) { buffer.push(key); } } // Check for and add the common non-enumerable properties for (var i=0, s=commonProps.length; i<s; i++) { if (commonProps[i] in object) buffer.push(commonProps[i]); } return buffer; };
Fix problem caused by Rob
import React from "react"; import { connect } from "react-redux"; import ChessBoardSquare from "components/chess-board-square"; class ChessBoard extends React.Component { getBoard() { const { store } = this.props; return store.getState().board; } renderFiles(rankId) { const { store } = this.props; const rank = this.getBoard()[rankId]; return Object.keys(rank).map((fileId) => { return ( <ChessBoardSquare file={fileId} key={fileId} rank={rankId} piece={rank[fileId]} store={store} /> ); }); } renderRanks() { const board = this.getBoard(); return Object.keys(board).reverse().map((rankId) => { return ( <div className="board-rank" key={rankId}> {this.renderFiles(rankId)} </div> ); }); } render() { return <div className="board">{this.renderRanks()}</div>; } } function mapStateToProps(state) { return { selectedSquare: state.selectedSquare } } export default connect(mapStateToProps)(ChessBoard);
import React from "react"; import { connect } from "react-redux"; import ChessBoardSquare from "components/chess-board-square"; class ChessBoard extends React.Component { getBoard() { const { store } = this.props; return store.getState().board; } renderFiles(rankId) { const rank = this.getBoard()[rankId]; return Object.keys(rank).map((fileId) => { return ( <ChessBoardSquare file={fileId} key={fileId} rank={rankId} square={rank[fileId]} /> ); }); } renderRanks() { const board = this.getBoard(); return Object.keys(board).reverse().map((rankId) => { return ( <div className="board-rank" key={rankId}> {this.renderFiles(rankId)} </div> ); }); } render() { return <div className="board">{this.renderRanks()}</div>; } } function mapStateToProps(state) { return { selectedSquare: state.selectedSquare } } export default connect(mapStateToProps)(ChessBoard);
Remove section from child of section
/** * ColonelKurtz Example */ import './example.scss' import ColonelKurtz from '../src/Colonel' import MediumBlock from '../addons/medium' import HtmlEmbedBlock from '../addons/html-embed' import ImageBlock from '../addons/image' import YouTubeBlock from '../addons/youtube' import SectionBlock from './blockTypes/Section' const blockTypes = [ { id: 'section', label: 'Section', component: SectionBlock, types: ['child-text', 'image', 'youtube'], maxChildren: 3 }, { id: 'medium', label: 'Medium Editor', component: MediumBlock, group: 'Rich Text' }, { id: 'embed', label: 'Embed', component: HtmlEmbedBlock }, { id: 'child-text', label: 'Child Text', component: MediumBlock, root: false }, { id: 'image', label: 'Image', group: 'Media', component: ImageBlock }, { id: 'youtube', label: 'YouTube', group: 'Media', component: YouTubeBlock } ] let editor = new ColonelKurtz({ el: document.getElementById('app'), blockTypes: blockTypes, maxChildren: 5, maxDepth: 3 }) editor.start()
/** * ColonelKurtz Example */ import './example.scss' import ColonelKurtz from '../src/Colonel' import MediumBlock from '../addons/medium' import HtmlEmbedBlock from '../addons/html-embed' import ImageBlock from '../addons/image' import YouTubeBlock from '../addons/youtube' import SectionBlock from './blockTypes/Section' const blockTypes = [ { id: 'section', label: 'Section', component: SectionBlock, types: ['child-text', 'image', 'youtube', 'section'], maxChildren: 3 }, { id: 'medium', label: 'Medium Editor', component: MediumBlock, group: 'Rich Text' }, { id: 'embed', label: 'Embed', component: HtmlEmbedBlock }, { id: 'child-text', label: 'Child Text', component: MediumBlock, root: false }, { id: 'image', label: 'Image', group: 'Media', component: ImageBlock }, { id: 'youtube', label: 'YouTube', group: 'Media', component: YouTubeBlock } ] let editor = new ColonelKurtz({ el: document.getElementById('app'), blockTypes: blockTypes, maxChildren: 5, maxDepth: 3 }) editor.start()
Add inline annotation to config
(function() { 'use strict'; angular .module('weatherApp', ['ngRoute']) .config(['$routeProvider'], config); function config($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/home/home.view.html', controller: 'HomeCtrl', controllerAs: 'vm' }) .when('/forecast', { templateUrl: 'components/forecast/forecast.view.html', controller: 'ForecastCtrl', controllerAs: 'vm' }) .when('/forecast/:days', { templateUrl: 'components/forecast/forecast.view.html', controller: 'ForecastCtrl', controllerAs: 'vm' }) .otherwise({redirectTo: '/'}); } })();
(function() { 'use strict'; angular .module('weatherApp', ['ngRoute']) .config(config); function config($routeProvider) { $routeProvider .when('/', { templateUrl: 'components/home/home.view.html', controller: 'HomeCtrl', controllerAs: 'vm' }) .when('/forecast', { templateUrl: 'components/forecast/forecast.view.html', controller: 'ForecastCtrl', controllerAs: 'vm' }) .when('/forecast/:days', { templateUrl: 'components/forecast/forecast.view.html', controller: 'ForecastCtrl', controllerAs: 'vm' }) .otherwise({redirectTo: '/'}); } })();
Make America cross-platform again (multiplatform install scripts)
const fs = require('fs'); const join = require('path').join; const sep = require('path').sep; const files = []; function crawl(location: string) { const dir = fs.readdirSync(location); dir.map(function(name, index) { const stat = fs.statSync(join(location, name)); if (stat.isDirectory()) { crawl(join(location, name)); } else { files.push(join(location, name)); } }); } crawl('docs'); const names = files.map(function (file) { const nameWithExt = file.split('docs'+sep)[1]; const name = nameWithExt.split('.md')[0]; return name; }); const mdData = {}; names.map(function (name) { mdData[name] = fs.readFileSync('docs' + sep + name + '.md', { encoding: 'utf8' }); }); fs.writeFileSync('website' + sep + 'docs-dist.json', JSON.stringify(mdData));
const fs = require('fs'); const join = require('path').join; const sep = require('path').sep; const files = []; function crawl(location: string) { const dir = fs.readdirSync(location); dir.map(function(name, index) { const stat = fs.statSync(join(location, name)); if (stat.isDirectory()) { crawl(join(location, name)); } else { files.push(join(location, name)); } }); } crawl('docs'); const names = files.map(function (file) { const nameWithExt = file.split('docs'+sep)[1]; const name = nameWithExt.split('.md')[0]; return name; }); const mdData = {}; names.map(function (name) { mdData[name] = fs.readFileSync('docs' + sep + name + '.md', { encoding: 'utf8' }); }); fs.writeFileSync('website' + sep + 'docs-dist.json', JSON.stringify(mdData)); //testsdfsdfsssssaaaaaaaaaaaa sfdaf asd sfda
Allow cross-origin for frontend server proxy
package org.luxons.sevenwonders.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // prefixes for all subscriptions config.enableSimpleBroker("/queue", "/topic"); config.setUserDestinationPrefix("/user"); // prefix for all calls from clients config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/seven-wonders-websocket") .setHandshakeHandler(handshakeHandler()) .setAllowedOrigins("http://localhost:3000") // to allow frontend server proxy requests in dev mode .withSockJS(); } @Bean public DefaultHandshakeHandler handshakeHandler() { return new AnonymousUsersHandshakeHandler(); } }
package org.luxons.sevenwonders.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.server.support.DefaultHandshakeHandler; @Configuration @EnableWebSocketMessageBroker public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void configureMessageBroker(MessageBrokerRegistry config) { // prefixes for all subscriptions config.enableSimpleBroker("/queue", "/topic"); config.setUserDestinationPrefix("/user"); // prefix for all calls from clients config.setApplicationDestinationPrefixes("/app"); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/seven-wonders-websocket").setHandshakeHandler(handshakeHandler()).withSockJS(); } @Bean public DefaultHandshakeHandler handshakeHandler() { return new AnonymousUsersHandshakeHandler(); } }
Fix date picker template syntax to match the latest style. git-svn-id: a346edc3f722475ad04b72d65977aa35d4befd55@542 3a26569e-5468-0410-bb2f-b495330926e5
/* * Copyright 2010 55 Minutes (http://www.55minutes.com) * * 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. */ //= require <jquery-ui> //= require <strftime> jQuery("#${component.marukpId}").datepicker( { showOn: "both" , buttonImage: "${behavior.buttonImageUrl}" , buttonImageOnly: true , changeMonth: true , changeYear: true } );
/* * Copyright 2010 55 Minutes (http://www.55minutes.com) * * 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. */ //= require <jquery-ui> //= require <strftime> jQuery("#${wicketMarkupId}").datepicker( { showOn: "both" , buttonImage: "${imageUrl}" , buttonImageOnly: true , changeMonth: true , changeYear: true } );
Make udiff print reasonable errors while not on a branch. R=agable@chromium.org BUG= Review URL: https://codereview.chromium.org/212493002 git-svn-id: bd64dd6fa6f3f0ed0c0666d1018379882b742947@259647 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
#!/usr/bin/env python # Copyright 2014 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. import argparse import sys import subprocess2 import git_common as git def main(args): default_args = git.config_list('depot-tools.upstream-diff.default-args') args = default_args + args parser = argparse.ArgumentParser() parser.add_argument('--wordwise', action='store_true', default=False, help=( 'Print a colorized wordwise diff ' 'instead of line-wise diff')) opts, extra_args = parser.parse_known_args(args) cur = git.current_branch() if not cur or cur == 'HEAD': print 'fatal: Cannot perform git-upstream-diff while not on a branch' return 1 par = git.upstream(cur) if not par: print 'fatal: No upstream configured for branch \'%s\'' % cur return 1 cmd = [git.GIT_EXE, 'diff', '--patience', '-C', '-C'] if opts.wordwise: cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])'] cmd += [git.get_or_create_merge_base(cur, par)] cmd += extra_args subprocess2.check_call(cmd) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
#!/usr/bin/env python # Copyright 2014 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. import argparse import sys import subprocess2 from git_common import current_branch, get_or_create_merge_base, config_list from git_common import GIT_EXE def main(args): default_args = config_list('depot-tools.upstream-diff.default-args') args = default_args + args parser = argparse.ArgumentParser() parser.add_argument('--wordwise', action='store_true', default=False, help=( 'Print a colorized wordwise diff ' 'instead of line-wise diff')) opts, extra_args = parser.parse_known_args(args) cmd = [GIT_EXE, 'diff', '--patience', '-C', '-C'] if opts.wordwise: cmd += ['--word-diff=color', r'--word-diff-regex=(\w+|[^[:space:]])'] cmd += [get_or_create_merge_base(current_branch())] cmd += extra_args subprocess2.check_call(cmd) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
Set HEAD to new ref when checking out
var fs = require('fs'); var nodePath = require('path'); var index = require('./index'); var files = require('./files'); var objects = require('./objects'); var refs = require('./refs'); var diff = require('./diff'); var util = require('./util'); var checkout = module.exports = { readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) { var localChanges = diff.readDiff("HEAD"); var headToBranchChanges = diff.readDiff("HEAD", checkoutHash); return Object.keys(localChanges) .filter(function(path) { return path in headToBranchChanges; }); }, writeCheckout: function(ref) { addModifyDelete("HEAD", refs.readHash(ref)); refs.write("HEAD", objects.read(ref) ? ref : refs.nameToBranchRef(ref)); } }; function addModifyDelete(diffFromRef, diffToRef) { var changes = diff.readDiff(diffFromRef, diffToRef); var checkoutIndex = index.readCommitIndex(diffToRef); Object.keys(changes).forEach(function(path) { if (changes[path] === diff.FILE_STATUS.ADD || changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now var content = objects.read(checkoutIndex[path]); files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)), files.repoDir()); } else if (changes[path] === diff.FILE_STATUS.DELETE) { fs.unlinkSync(path); } }); };
var fs = require('fs'); var nodePath = require('path'); var index = require('./index'); var files = require('./files'); var objects = require('./objects'); var refs = require('./refs'); var diff = require('./diff'); var util = require('./util'); var checkout = module.exports = { readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) { var localChanges = diff.readDiff("HEAD"); var headToBranchChanges = diff.readDiff("HEAD", checkoutHash); return Object.keys(localChanges) .filter(function(path) { return path in headToBranchChanges; }); }, writeCheckout: function(ref) { addModifyDelete("HEAD", refs.readHash(ref)); } }; function addModifyDelete(diffFromRef, diffToRef) { var changes = diff.readDiff(diffFromRef, diffToRef); var checkoutIndex = index.readCommitIndex(diffToRef); Object.keys(changes).forEach(function(path) { if (changes[path] === diff.FILE_STATUS.ADD || changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now var content = objects.read(checkoutIndex[path]); files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)), files.repoDir()); } else if (changes[path] === diff.FILE_STATUS.DELETE) { fs.unlinkSync(path); } }); };
Implement auto redirect authenticated user to week page.
package bj.pranie.controller; import bj.pranie.entity.User; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; /** * Created by Sebastian Sokolowski on 12.10.16. */ @Controller public class IndexController { @RequestMapping(value = "/", method = RequestMethod.GET) public String index() { if (isAuthenticatedUser()) { return "redirect:/week"; } return "index"; } private boolean isAuthenticatedUser() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); if (authentication.getPrincipal() instanceof User) { return true; } return false; } }
package bj.pranie.controller; import bj.pranie.util.TimeUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import java.util.Calendar; /** * Created by Sebastian Sokolowski on 12.10.16. */ @Controller public class IndexController { private final Logger log = LoggerFactory.getLogger(this.getClass()); @RequestMapping(value = "/", method = RequestMethod.GET) public ModelAndView index(Model model) { ModelAndView modelAndView = new ModelAndView("index"); modelAndView.addObject("time", TimeUtil.getTime()); log.debug("time" + Calendar.getInstance().getTime().toString()); return modelAndView; } }
Use IEEE computer society layout to improve looks.
#!/usr/bin/env python import docutils.core as dc from writer import writer import os.path import sys import glob preamble = r''' % These preamble commands are from build_paper.py % PDF Standard Fonts \usepackage{mathptmx} \usepackage[scaled=.90]{helvet} \usepackage{courier} % Make verbatim environment smaller \makeatletter \g@addto@macro\@verbatim\footnotesize \makeatother \renewcommand{\quote}{} ''' settings = {'documentclass': 'IEEEtran', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble, 'documentoptions': 'letterpaper,compsoc,twoside'} if len(sys.argv) != 2: print "Usage: build_paper.py paper_directory" sys.exit(-1) path = sys.argv[1] if not os.path.isdir(path): print("Cannot open directory: %s" % path) sys.exit(-1) rst = glob.glob(os.path.join(path, '*.rst'))[0] content = open(rst, 'r').read() content = ''' .. role:: math(raw) :format: latex ''' + content tex = dc.publish_string(source=content, writer=writer, settings_overrides=settings) out = open('/tmp/paper.tex', 'w') out.write(tex) out.close()
#!/usr/bin/env python import docutils.core as dc from writer import writer import os.path import sys import glob preamble = r''' % These preamble commands are from build_paper.py % PDF Standard Fonts \usepackage{mathptmx} \usepackage[scaled=.90]{helvet} \usepackage{courier} % Make verbatim environment smaller \makeatletter \g@addto@macro\@verbatim\footnotesize \makeatother \renewcommand{\quote}{} ''' settings = {'documentclass': 'IEEEtran', 'use_verbatim_when_possible': True, 'use_latex_citations': True, 'latex_preamble': preamble} if len(sys.argv) != 2: print "Usage: build_paper.py paper_directory" sys.exit(-1) path = sys.argv[1] if not os.path.isdir(path): print("Cannot open directory: %s" % path) sys.exit(-1) rst = glob.glob(os.path.join(path, '*.rst'))[0] content = open(rst, 'r').read() content = ''' .. role:: math(raw) :format: latex ''' + content tex = dc.publish_string(source=content, writer=writer, settings_overrides=settings) out = open('/tmp/paper.tex', 'w') out.write(tex) out.close()
Fix import that was breaking py3k --HG-- branch : distribute extra : rebase_source : 76bf8f9213536189bce76a41e798c44c5f468cbd
from distutils.core import Extension as _Extension from setuptools.dist import _get_unpatched _Extension = _get_unpatched(_Extension) try: from Pyrex.Distutils.build_ext import build_ext except ImportError: have_pyrex = False else: have_pyrex = True class Extension(_Extension): """Extension that uses '.c' files in place of '.pyx' files""" if not have_pyrex: # convert .pyx extensions to .c def __init__(self,*args,**kw): _Extension.__init__(self,*args,**kw) sources = [] for s in self.sources: if s.endswith('.pyx'): sources.append(s[:-3]+'c') else: sources.append(s) self.sources = sources class Library(Extension): """Just like a regular Extension, but built as a library instead""" import sys, distutils.core, distutils.extension distutils.core.Extension = Extension distutils.extension.Extension = Extension if 'distutils.command.build_ext' in sys.modules: sys.modules['distutils.command.build_ext'].Extension = Extension
from distutils.core import Extension as _Extension from dist import _get_unpatched _Extension = _get_unpatched(_Extension) try: from Pyrex.Distutils.build_ext import build_ext except ImportError: have_pyrex = False else: have_pyrex = True class Extension(_Extension): """Extension that uses '.c' files in place of '.pyx' files""" if not have_pyrex: # convert .pyx extensions to .c def __init__(self,*args,**kw): _Extension.__init__(self,*args,**kw) sources = [] for s in self.sources: if s.endswith('.pyx'): sources.append(s[:-3]+'c') else: sources.append(s) self.sources = sources class Library(Extension): """Just like a regular Extension, but built as a library instead""" import sys, distutils.core, distutils.extension distutils.core.Extension = Extension distutils.extension.Extension = Extension if 'distutils.command.build_ext' in sys.modules: sys.modules['distutils.command.build_ext'].Extension = Extension
Move pagic.environment registration out to system's service provider
<?php namespace Igniter\Flame\Pagic; use Igniter\Flame\Pagic\Source\SourceResolver; use Illuminate\Support\ServiceProvider; /** * Class PagicServiceProvider */ class PagicServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { Model::setSourceResolver($this->app['pagic']); Model::setEventDispatcher($this->app['events']); Model::setCacheManager($this->app['cache']); } /** * Register the service provider. * @return void */ public function register() { $this->app->singleton('pagic', function () { return new SourceResolver; }); } }
<?php namespace Igniter\Flame\Pagic; use Igniter\Flame\Pagic\Cache\FileSystem as FileCache; use Igniter\Flame\Pagic\Parsers\FileParser; use Igniter\Flame\Pagic\Source\SourceResolver; use Illuminate\Support\ServiceProvider; /** * Class PagicServiceProvider */ class PagicServiceProvider extends ServiceProvider { /** * Bootstrap the application events. * * @return void */ public function boot() { Model::setSourceResolver($this->app['pagic']); Model::setEventDispatcher($this->app['events']); Model::setCacheManager($this->app['cache']); } /** * Register the service provider. * @return void */ public function register() { $this->app->singleton('pagic', function () { return new SourceResolver; }); $this->app->singleton('pagic.environment', function ($app) { return new Environment(new Loader, [ 'cache' => new FileCache(storage_path().'/system/templates'), ]); }); FileParser::setCache(new FileCache(config('system.parsedTemplateCachePath'))); } }
Allow render_fields to override the default template.
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) if template is None: template = self.template fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
# -*- coding: utf-8 -*- from __future__ import print_function, division, absolute_import, unicode_literals import itertools from .util import trim def render(item, **fields): """ Render the given item """ if item is None: return '' elif isinstance(item, Renderer): return item.render(**fields) elif isinstance(item, list): return ''.join(render(e) for e in item) else: return str(item) class Renderer(object): template = '' _counter = itertools.count() def __init__(self, template=None): if template is not None: self.template = template def counter(self): return next(self._counter) def render_fields(self, fields): pass def render(self, template=None, **fields): if template is None: template = self.template fields.update({k:v for k, v in vars(self).items() if not k.startswith('_')}) self.render_fields(fields) fields = {k:render(v) for k, v in fields.items()} try: return trim(template).format(**fields) except KeyError as e: raise KeyError(str(e), type(self))
Move parsing loop into the class itself.
from pprint import pprint class Hand: def __init__(self, string): segments = "seats preflop flop turn river".split() self.seats = None self.preflop = None self.flop = None self.turn = None self.river = None self.summary = None ## step 2: split each hand into segments s = string.split('\n*** ') while len(s) > 1: # We don't always have flop, turn, riv, but last element is # always Summary. k = segments.pop(0) v = s.pop(0).splitlines() self.__dict__[k] = v ## step 3: split each segment into lines self.summary = s.pop(0).splitlines() assert len(s) == 0 def __repr__(self): return str(self.__dict__) ## main input = open('example_ignition.txt').read() ## step 1: split flat file into hands hands = input.split('\n\n\n') for i, h in enumerate(hands): hands[i] = Hand(h) ## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ] print(hands[0])
from pprint import pprint input = open('example_ignition.txt').read() hands = input.split('\n\n\n') class Hand: def __init__(self, se=None, p=None, f=None, t=None, r=None, su=None): self.seats = se self.preflop = p self.flop = f self.turn = t self.river = r self.summary = su def __repr__(self): return str(self.__dict__) for i, h in enumerate(hands): segments = "seats preflop flop turn river".split() s = h.split('\n*** ') hands[i] = Hand() while len(s) > 1: # We don't always have flop, turn, riv, but last element is # always Summary. k = segments.pop(0) v = s.pop(0).splitlines() hands[i].__dict__[k] = v hands[i].summary = s.pop(0).splitlines() assert len(s) == 0 ## [ { s:[] p:[] f:[] s:[] } { s:[] p:[] f:[] t:[] r:[] s:[] } {} {} ] print(hands[0])
Make setRunning toggle when no argument is passed
JSBP = {}; // Constants JSBP.MEMSIZE = 0x1000008; JSBP.running = false; JSBP.tickId = 0; // This will be our main memory once JSBP.core loads JSBP.mem = null; JSBP.init = function() { JSBP.core.init(); JSBP.canvas.init(); JSBP.audio.init(); JSBP.input.init(); JSBP.loader.init(); //JSBP.setRunning(true); } JSBP.tick = function() { JSBP.core.tick(); JSBP.canvas.tick(); JSBP.audio.tick(); } JSBP.setRunning = function(state) { if (state == undefined) state = !JSBP.running; JSBP.running = state; if (state) { JSBP.tickId = setInterval(JSBP.tick, 1000 / 60); JSBP.audio.node.connect(JSBP.audio.context.destination); } else { clearInterval(JSBP.tickId); JSBP.audio.node.disconnect(); } } $(JSBP.init);
JSBP = {}; // Constants JSBP.MEMSIZE = 0x1000008; JSBP.running = false; JSBP.tickId = 0; // This will be our main memory once JSBP.core loads JSBP.mem = null; JSBP.init = function() { JSBP.core.init(); JSBP.canvas.init(); JSBP.audio.init(); JSBP.input.init(); JSBP.loader.init(); //JSBP.setRunning(true); } JSBP.tick = function() { JSBP.core.tick(); JSBP.canvas.tick(); JSBP.audio.tick(); } JSBP.setRunning = function(state) { JSBP.running = state; if (state) { JSBP.tickId = setInterval(JSBP.tick, 1000 / 60); JSBP.audio.node.connect(JSBP.audio.context.destination); } else { clearInterval(JSBP.tickId); JSBP.audio.node.disconnect(); } } $(JSBP.init);
Remove unused import in lmod
import os from subprocess import Popen, PIPE LMOD_CMD = os.environ['LMOD_CMD'] LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '') def module(command, arguments=()): cmd = [LMOD_CMD, 'python', '--terse', command] cmd.extend(arguments) result = Popen(cmd, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def module_avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def module_list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def module_savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names
import os import re from collections import OrderedDict from subprocess import Popen, PIPE LMOD_CMD = os.environ['LMOD_CMD'] LMOD_SYSTEM_NAME = os.environ.get('LMOD_SYSTEM_NAME', '') def module(command, arguments=()): cmd = [LMOD_CMD, 'python', '--terse', command] cmd.extend(arguments) result = Popen(cmd, stdout=PIPE, stderr=PIPE) if command in ('load', 'unload', 'restore', 'save'): exec(result.stdout.read()) return result.stderr.read().decode() def module_avail(): string = module('avail') modules = [] for entry in string.split(): if not (entry.startswith('/') or entry.endswith('/')): modules.append(entry) return modules def module_list(): string = module('list').strip() if string != "No modules loaded": return string.split() return [] def module_savelist(system=LMOD_SYSTEM_NAME): names = module('savelist').split() if system: suffix = '.{}'.format(system) n = len(suffix) names = [name[:-n] for name in names if name.endswith(suffix)] return names
Change persistence to processing for clarity Signed-off-by: Jacob Filik <3a868c14e39a7f9b8bacb473ae15a5c5ce613b42@diamond.ac.uk>
/*- * Copyright 2016 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.processing; import java.util.List; /** * Interface to set up an operation processing run */ public interface IOperationBean { public void setDataKey(String dataKey); public void setFilePath(String fileName); public void setOutputFilePath(String outputFilePath); public void setDatasetPath(String datasetPath); public void setSlicing(String slicing); public void setProcessingPath(String persistencePath); public void setAxesNames(List<String>[] axesNames); public void setDeleteProcessingFile(boolean deletePersistenceFile); public void setXmx(String xmx); public void setDataDimensions(int[] dataDimensions); public void setReadable(boolean readable); public void setName(String name); public void setRunDirectory(String visitDir); public void setParallelizable(boolean parallelizable); }
/*- * Copyright 2016 Diamond Light Source Ltd. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.dawnsci.analysis.api.processing; import java.util.List; /** * Interface to set up an operation processing run */ public interface IOperationBean { public void setDataKey(String dataKey); public void setFilePath(String fileName); public void setOutputFilePath(String outputFilePath); public void setDatasetPath(String datasetPath); public void setSlicing(String slicing); public void setPersistencePath(String persistencePath); public void setAxesNames(List<String>[] axesNames); public void setDeletePersistenceFile(boolean deletePersistenceFile); public void setXmx(String xmx); public void setDataDimensions(int[] dataDimensions); public void setReadable(boolean readable); public void setName(String name); public void setRunDirectory(String visitDir); public void setParallelizable(boolean parallelizable); }
Change key attribute to private after Jongo version changes
/* * Copyright 2013 - Elian ORIOU * * 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. * * 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.vino.backend.model; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.jongo.marshall.jackson.oid.Id; import org.jongo.marshall.jackson.oid.ObjectId; /** * User: walien * Date: 1/7/14 * Time: 9:41 PM */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public abstract class Entity { @ObjectId @Id private String key; public Entity setKey(String key) { this.key = key; return this; } public String getKey() { return this.key; } }
/* * Copyright 2013 - Elian ORIOU * * 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. * * 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.vino.backend.model; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.jongo.marshall.jackson.oid.Id; import org.jongo.marshall.jackson.oid.ObjectId; /** * User: walien * Date: 1/7/14 * Time: 9:41 PM */ @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class") public abstract class Entity { // It seems to be an issue on Jongo... This field will be temporarly public... @ObjectId @Id public String key; public Entity() { } public Entity setKey(String key) { this.key = key; return this; } public String getKey() { return this.key; } }
Fix explicit check for presence of ibapi package
import sys import importlib if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') from . import util # noqa if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
import sys import importlib from .version import __version__, __version_info__ # noqa from . import util if sys.version_info < (3, 6, 0): raise RuntimeError('ib_insync requires Python 3.6 or higher') try: import ibapi except ImportError: raise RuntimeError( 'IB API from http://interactivebrokers.github.io is required') if util.ibapiVersionInfo() < (9, 73, 6): raise RuntimeError( f'Old version ({ibapi.__version__}) of ibapi package detected. ' 'The newest version from http://interactivebrokers.github.io ' 'is required') from .version import __version__, __version_info__ # noqa from .objects import * # noqa from .event import * # noqa from .contract import * # noqa from .order import * # noqa from .ticker import * # noqa from .ib import * # noqa from .client import * # noqa from .wrapper import * # noqa from .flexreport import * # noqa from .ibcontroller import * # noqa from . import util # noqa __all__ = ['util'] for _m in ( objects, event, contract, order, ticker, ib, # noqa client, wrapper, flexreport, ibcontroller): # noqa __all__ += _m.__all__ del sys del importlib del ibapi
Fix window test border _again_ (more fixed). --HG-- extra : convert_revision : svn%3A14d46d22-621c-0410-bb3d-6f67920f7d95/trunk%401383
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width, window.height) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
#!/usr/bin/python # $Id:$ from pyglet.gl import * def draw_client_border(window): glClearColor(0, 0, 0, 1) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() glOrtho(0, window.width, 0, window.height, -1, 1) glMatrixMode(GL_MODELVIEW) glLoadIdentity() def rect(x1, y1, x2, y2): glBegin(GL_LINE_LOOP) glVertex2f(x1, y1) glVertex2f(x2, y1) glVertex2f(x2, y2) glVertex2f(x1, y2) glEnd() glColor3f(1, 0, 0) rect(-1, -1, window.width + 1, window.height - 1) glColor3f(0, 1, 0) rect(0, 0, window.width - 1, window.height - 1)
Test generating a 503 status
package au.org.ands.vocabs.toolkit.restlet; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; /** Testing restlet. */ @Path("testing2") public class TestRestlet2 { /** getMessage. * @return the message. */ @Produces(MediaType.TEXT_PLAIN) @GET public final String getMessage() { return "Hello World! Again!"; } /** getMessage. * @return the message. */ @Produces(MediaType.APPLICATION_JSON) @GET public final String getMessageJson() { return "{\"hello\":\"Hello JSON!\"}"; } /** getException. * This shows how to return a status code 503 "service unavailable" * and also some content. * @return the message. */ @Path("except") @Produces(MediaType.TEXT_PLAIN) @GET public final Response getExcept() { return Response.status(Status.SERVICE_UNAVAILABLE). entity("Hi there").build(); } }
package au.org.ands.vocabs.toolkit.restlet; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; /** Testing restlet. */ @Path("testing2") public class TestRestlet2 { /** getMessage. * @return the message. */ @Produces(MediaType.TEXT_PLAIN) @GET public final String getMessage() { return "Hello World! Again!"; } /** getMessage. * @return the message. */ @Produces(MediaType.APPLICATION_JSON) @GET public final String getMessageJson() { return "{\"hello\":\"Hello JSON!\"}"; } }
Fix indentation in js tests
"use strict"; var assert = require('assert'); describe('Note', function () { var Note = require('../models/note') describe('model', function () { var Project = require('../models/project') , dummyProject = new Project({ slug: 'emma' }) it('should throw an error without being passed a project', function () { assert.throws(function () { new Note() }, /project/); }); it('should work fine when passed no attrs with a project', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.project, dummyProject); }); it('should have an absolute url', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.url(), '/api/projects/emma/notes/'); }); it('should have an absolute url with ID', function () { var note = new Note({id: 12}, { project: dummyProject }); assert.equal(note.url(), '/api/projects/emma/notes/12/'); }); it('should have a default status of open', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.get('status'), 'open'); }); }); });
"use strict"; var assert = require('assert'); describe('Note', function () { var Note = require('../models/note') describe('model', function () { var Project = require('../models/project') , dummyProject = new Project({ slug: 'emma' }) it('should throw an error without being passed a project', function () { assert.throws(function () { new Note() }, /project/); }); it('should work fine when passed no attrs with a project', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.project, dummyProject); }); it('should have an absolute url', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.url(), '/api/projects/emma/notes/'); }); it('should have an absolute url with ID', function () { var note = new Note({id: 12}, { project: dummyProject }); assert.equal(note.url(), '/api/projects/emma/notes/12/'); }); it('should have a default status of open', function () { var note = new Note({}, { project: dummyProject }); assert.equal(note.get('status'), 'open'); }); }); });
Add long description content type.
#!/usr/bin/env python import os import sys import skosprovider try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'skosprovider', ] requires = [ 'language-tags', 'rfc3987', 'pyld', 'html5lib' ] setup( name='skosprovider', version='0.8.0', description='Abstraction layer for SKOS vocabularies.', long_description=open('README.rst').read(), long_description_content_type='text/x-rst', author='Koen Van Daele', author_email='koen_van_daele@telenet.be', url='http://github.com/koenedaele/skosprovider', packages=packages, package_data={'': ['LICENSE']}, package_dir={'skosprovider': 'skosprovider'}, include_package_data=True, install_requires=requires, license='MIT', zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], test_suite='nose.collector' )
#!/usr/bin/env python import os import sys import skosprovider try: from setuptools import setup except ImportError: from distutils.core import setup packages = [ 'skosprovider', ] requires = [ 'language-tags', 'rfc3987', 'pyld', 'html5lib' ] setup( name='skosprovider', version='0.8.0', description='Abstraction layer for SKOS vocabularies.', long_description=open('README.rst').read(), author='Koen Van Daele', author_email='koen_van_daele@telenet.be', url='http://github.com/koenedaele/skosprovider', packages=packages, package_data={'': ['LICENSE']}, package_dir={'skosprovider': 'skosprovider'}, include_package_data=True, install_requires=requires, license='MIT', zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], test_suite='nose.collector' )
Add sdb support, and also properly return the default
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils import salt.utils.sdb def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' ret = salt.utils.traverse_dict_and_list(__opts__, key, default='_|-', delimiter=delimiter) if ret == '_|-': return default else: return salt.utils.sdb.sdb_get(ret, __opts__)
# -*- coding: utf-8 -*- ''' This runner is designed to mirror the execution module config.py, but for master settings ''' from __future__ import absolute_import from __future__ import print_function import salt.utils def get(key, default='', delimiter=':'): ''' Retrieve master config options, with optional nesting via the delimiter argument. **Arguments** default If the key is not found, the default will be returned instead delimiter Override the delimiter used to separate nested levels of a data structure. CLI Example: .. code-block:: bash salt-run config.get gitfs_remotes salt-run config.get file_roots:base salt-run config.get file_roots,base delimiter=',' ''' return salt.utils.traverse_dict_and_list(__opts__, key, delimiter=delimiter)
Exit syncing script when it's done
'use strict' let winston = require('winston') let Rat = require('../api/models/rat') let Rescue = require('../api/models/rescue') let User = require('../api/models/user') let mongoose = require('mongoose') let count = 0 let streamsClosed = 0 mongoose.connect('mongodb://localhost/fuelrats') winston.info('Beginning Index Model Sync') winston.info('Syncing Rats') let ratStream = Rat.synchronize() ratStream.on('data', function (error, doc) { count++ }) ratStream.on('error', function (error) { console.error(error) }) ratStream.on('close', function () { console.log('Finished syncing Rats') streamsClosed++ if (streamsClosed === 2) { mongoose.disconnect() } }) winston.info('Syncing Rescue') Rescue.synchronize() let rescueStream = Rescue.synchronize() rescueStream.on('data', function (error, doc) { count++ }) rescueStream.on('error', function (error) { console.error(error) }) rescueStream.on('close', function () { console.log('Finished syncing Rescues') streamsClosed++ if (streamsClosed === 2) { mongoose.disconnect() } })
'use strict' let winston = require('winston') let Rat = require('../api/models/rat') let Rescue = require('../api/models/rescue') let User = require('../api/models/user') let mongoose = require('mongoose') let count = 0 mongoose.connect('mongodb://localhost/fuelrats') winston.info('Beginning Index Model Sync') winston.info('Syncing Rats') let ratStream = Rat.synchronize() ratStream.on('data', function (error, doc) { count++ }) ratStream.on('error', function (error) { console.error(error) }) ratStream.on('close', function () { console.log('Finished syncing Rats') }) winston.info('Syncing Rescue') Rescue.synchronize() let rescueStream = Rescue.synchronize() rescueStream.on('data', function (error, doc) { count++ }) rescueStream.on('error', function (error) { console.error(error) }) rescueStream.on('close', function () { console.log('Finished syncing Rescues') })
Upgrade status to Production/Stable and add specific python version to classifiers
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="valideer", version="0.4.1", description="Lightweight data validation and adaptation library for Python", long_description=open("README.rst").read(), url="https://github.com/podio/valideer", author="George Sakkis", author_email="george.sakkis@gmail.com", packages=find_packages(), install_requires=["decorator"], test_suite="valideer.tests", platforms=["any"], keywords="validation adaptation typechecking jsonschema", classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.7", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.3", "Programming Language :: Python :: 3.4", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: MIT License", ], )
#!/usr/bin/env python from setuptools import setup, find_packages setup( name="valideer", version="0.4.1", description="Lightweight data validation and adaptation library for Python", long_description=open("README.rst").read(), url="https://github.com/podio/valideer", author="George Sakkis", author_email="george.sakkis@gmail.com", packages=find_packages(), install_requires=["decorator"], test_suite="valideer.tests", platforms=["any"], keywords="validation adaptation typechecking jsonschema", classifiers=[ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Topic :: Software Development :: Libraries :: Python Modules", "License :: OSI Approved :: MIT License", ], )
Allow nav to be overridden, use navbar by default.
<?php /* * Theme Name: Bootstrap * Template: Master * Author: Paladin Digital */ $theme = 'themes::paladindigital.laravel-bootstrap'; // Allow nav type to be overridden from controllers. if (!isset($nav)) { $nav = 'navbar'; } ?><!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> @yield('head') @include($theme . '._meta') @yield('styles') </head> <body> @include($theme . '._' . $nav) <div class="container-fluid"> @yield('content') <aside> @yield('sidebar') @yield('widgets') </aside> </div> @include($theme . '._footer') <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> @yield('scripts') </body> </html>
<?php /* * Theme Name: Bootstrap * Template: Master * Author: Paladin Digital */ $theme = 'themes::paladindigital.laravel-bootstrap'; ?><!DOCTYPE html> <html> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> @yield('head') @include($theme . '._meta') @yield('styles') </head> <body> @include($theme . '._nav') <div class="container-fluid"> @yield('content') <aside> @yield('sidebar') @yield('widgets') </aside> </div> @include($theme . '._footer') <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> @yield('scripts') </body> </html>
Use relative path for deployer.rb
from __future__ import print_function import ConfigParser __author__ = 'alforbes' config = ConfigParser.ConfigParser() config.add_section('main') config.set('main', 'debug_mode', 'false') config.set('main', 'propagate_exceptions', 'true') config.set('main', 'time_format', '%Y-%m-%dT%H:%M:%SZ') config.set('main', 'time_zone', 'UTC') config.set('main', 'strict_slashes', 'false') config.set('main', 'base_url', 'http://localhost:5000') config.add_section('db') config.set('db', 'uri', 'postgres://orlo:password@localhost:5432/orlo') config.set('db', 'echo_queries', 'false') config.add_section('logging') config.set('logging', 'debug', 'false') config.set('logging', 'file', 'disabled') config.read('/etc/orlo/orlo.ini') config.add_section('deploy_shell') config.set('deploy_shell', 'command_path', '../deployer.rb')
from __future__ import print_function import ConfigParser __author__ = 'alforbes' config = ConfigParser.ConfigParser() config.add_section('main') config.set('main', 'debug_mode', 'false') config.set('main', 'propagate_exceptions', 'true') config.set('main', 'time_format', '%Y-%m-%dT%H:%M:%SZ') config.set('main', 'time_zone', 'UTC') config.set('main', 'strict_slashes', 'false') config.set('main', 'base_url', 'http://localhost:5000') config.add_section('db') config.set('db', 'uri', 'postgres://orlo:password@localhost:5432/orlo') config.set('db', 'echo_queries', 'false') config.add_section('logging') config.set('logging', 'debug', 'false') config.set('logging', 'file', 'disabled') config.read('/etc/orlo/orlo.ini') config.add_section('deploy_shell') config.set('deploy_shell', 'command_path', '/vagrant/deployer.rb')
Remove useless stuff from Piwik
import React from 'react' import PropTypes from 'prop-types' import Head from 'next/head' import { PIWIK_URL, PIWIK_SITE_ID } from '@env' class Piwik extends React.Component { static propTypes = { title: PropTypes.string.isRequired } componentDidMount() { const { title } = this.props if (window.Piwik) { const tracker = window.Piwik.getTracker(`${PIWIK_URL}/piwik.php`, PIWIK_SITE_ID) tracker.trackPageView(title) } } render() { if (!PIWIK_URL || !PIWIK_SITE_ID) { return null } return ( <Head> <script src={`${PIWIK_URL}/piwik.js`} defer async /> </Head> ) } } export default Piwik
import React from 'react' import PropTypes from 'prop-types' import Head from 'next/head' import { withRouter } from 'next/router' import { PIWIK_URL, PIWIK_SITE_ID } from '@env' class Piwik extends React.Component { static propTypes = { title: PropTypes.string.isRequired } componentDidMount() { const { title } = this.props if (window.Piwik) { const tracker = window.Piwik.getAsyncTracker() tracker.setTrackerUrl(`${PIWIK_URL}/piwik.php`) tracker.setSiteId(PIWIK_SITE_ID) tracker.trackPageView(title) } } render() { if (!PIWIK_URL || !PIWIK_SITE_ID) { return null } return ( <Head> <script src={`${PIWIK_URL}/piwik.js`} defer async /> </Head> ) } } export default withRouter(Piwik)
Remove margin constrains from PDF printing
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, # 'margin-top': '10mm', # 'margin-right': '1mm', # 'margin-bottom': '10mm', # 'margin-left': '1mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import pdfkit, os, frappe from frappe.utils import scrub_urls def get_pdf(html, options=None): if not options: options = {} options.update({ "print-media-type": None, "background": None, "images": None, 'margin-top': '15mm', 'margin-right': '15mm', 'margin-bottom': '15mm', 'margin-left': '15mm', 'encoding': "UTF-8", 'no-outline': None }) if not options.get("page-size"): options['page-size'] = frappe.db.get_single_value("Print Settings", "pdf_page_size") or "A4" html = scrub_urls(html) fname = os.path.join("/tmp", frappe.generate_hash() + ".pdf") pdfkit.from_string(html, fname, options=options or {}) with open(fname, "rb") as fileobj: filedata = fileobj.read() os.remove(fname) return filedata
Include a missing asObject(Float obj) method.
/* * Copyright (c) 2011 Jeppetto and Jonathan Thompson * * 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 org.jeppetto.enhance; /** * Utility for converting primitive types to objects. */ public class ReferenceUtil { //------------------------------------------------------------- // Constructor //------------------------------------------------------------- private ReferenceUtil() { /* do not instantiate */ } //------------------------------------------------------------- // Methods - Public - Static //------------------------------------------------------------- public static Object asObject(Object obj) { return obj; } public static Object asObject(boolean obj) { return obj; } public static Object asObject(byte obj) { return obj; } public static Object asObject(short obj) { return obj; } public static Object asObject(int obj) { return obj; } public static Object asObject(long obj) { return obj; } public static Object asObject(float obj) { return obj; } public static Object asObject(double obj) { return obj; } }
/* * Copyright (c) 2011 Jeppetto and Jonathan Thompson * * 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 org.jeppetto.enhance; /** * Utility for converting primitive types to objects. */ public class ReferenceUtil { //------------------------------------------------------------- // Constructor //------------------------------------------------------------- private ReferenceUtil() { /* do not instantiate */ } //------------------------------------------------------------- // Methods - Public - Static //------------------------------------------------------------- public static Object asObject(Object obj) { return obj; } public static Object asObject(boolean obj) { return obj; } public static Object asObject(byte obj) { return obj; } public static Object asObject(short obj) { return obj; } public static Object asObject(int obj) { return obj; } public static Object asObject(long obj) { return obj; } public static Object asObject(double obj) { return obj; } }
Define localizable attrs for XUL elements Define which attributes are localizable for the following XUL elements: key, menu, menuitem, toolbarbutton
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], key: ['key'], menu: ['label', 'accesskey'], menuitem: ['label', 'accesskey'], tab: ['label'], textbox: ['placeholder'], toolbarbutton: ['label', 'tooltiptext'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
import { Localization } from './base'; import { overlayElement } from './overlay'; export { contexts } from './base'; const ns = 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul'; const allowed = { attributes: { global: ['aria-label', 'aria-valuetext', 'aria-moz-hint'], button: ['accesskey'], tab: ['label'], textbox: ['placeholder'], } }; export class XULLocalization extends Localization { overlayElement(element, translation) { return overlayElement(this, element, translation); } isElementAllowed() { return false; } isAttrAllowed(attr, element) { if (element.namespaceURI !== ns) { return false; } const tagName = element.localName; const attrName = attr.name; // is it a globally safe attribute? if (allowed.attributes.global.indexOf(attrName) !== -1) { return true; } // are there no allowed attributes for this element? if (!allowed.attributes[tagName]) { return false; } // is it allowed on this element? // XXX the allowed list should be amendable; https://bugzil.la/922573 if (allowed.attributes[tagName].indexOf(attrName) !== -1) { return true; } return false; } }
Allow caller to set flags
import {compile} from 'google-closure-compiler-js'; import logger from './logger'; export default function closure(flags = {}) { return { name: 'closure-compiler-js', transformBundle(code) { flags = Object.assign({ createSourceMap: true, processCommonJsModules: true }, flags); flags.jsCode = [{ src: code }]; const output = compile(flags); if (logger(flags, output)) { throw new Error(`compilation error, ${output.errors.length} error${output.errors.length===0 || output.errors.length>1?'s':''}`); } return {code: output.compiledCode, map: output.sourceMap}; } }; }
import {compile} from 'google-closure-compiler-js'; import logger from './logger'; export default function closure(flags = {}) { return { name: 'closure-compiler-js', transformBundle(code) { flags.createSourceMap = true; flags.processCommonJsModules = true; flags.jsCode = [{ src: code }]; const output = compile(flags); if (logger(flags, output)) { throw new Error(`compilation error, ${output.errors.length} error${output.errors.length===0 || output.errors.length>1?'s':''}`); } return {code: output.compiledCode, map: output.sourceMap}; } }; }
Remove -, !, + and ~ from the slug too
'use strict'; var diacritics = require('./diacritics'); function nbSlug(name) { var diacriticsMap = {}; for (var i = 0; i < diacritics.length; i++) { var letters = diacritics[i].letters; for (var j = 0; j < letters.length ; j++) { diacriticsMap[letters[j]] = diacritics[i].base; } } function removeDiacritics (str) { return str.replace(/[^\u0000-\u007E]/g, function(a){ return diacriticsMap[a] || a; }); } var slug = removeDiacritics(String(name || '').trim()) .replace(/^\s\s*/, '') // Trim start .replace(/\s\s*$/, '') // Trim end .toLowerCase() // Camel case is bad .replace(/[^a-z0-9\-\s]+/g, '') // Exchange invalid chars .replace(/[\s]+/g, '-') // Swap whitespace for single hyphen .replace(/-{2,}/g, '-') // Replace consecutive single hypens .trim(); while (slug[slug.length - 1] === '-') { slug = slug.slice(0, -1); } return slug; } module.exports = nbSlug;
'use strict'; var diacritics = require('./diacritics'); function nbSlug(name) { var diacriticsMap = {}; for (var i = 0; i < diacritics.length; i++) { var letters = diacritics[i].letters; for (var j = 0; j < letters.length ; j++) { diacriticsMap[letters[j]] = diacritics[i].base; } } function removeDiacritics (str) { return str.replace(/[^\u0000-\u007E]/g, function(a){ return diacriticsMap[a] || a; }); } var slug = removeDiacritics(String(name || '').trim()) .replace(/^\s\s*/, '') // Trim start .replace(/\s\s*$/, '') // Trim end .toLowerCase() // Camel case is bad .replace(/[^a-z0-9_\-~!\+\s]+/g, '') // Exchange invalid chars .replace(/[\s]+/g, '-') // Swap whitespace for single hyphen .replace(/--/g, '-') .replace(/--/g, '-') .replace(/--/g, '-') .replace(/--/g, '-') .trim(); while (slug[slug.length - 1] === '-') { slug = slug.slice(0, -1); } return slug; } module.exports = nbSlug;
Remove field name from error returned during feature gate validation Prior to this commit the feature gate validation returned a validation error with its field path set to "workspaces". This isn't correct - the validation can guard any field. This commit removes the "workspaces" field path from the validation error returned by the feature gate validation.
/* Copyright 2021 The Tekton Authors 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 v1beta1 import ( "context" "fmt" "github.com/tektoncd/pipeline/pkg/apis/config" "knative.dev/pkg/apis" ) // ValidateEnabledAPIFields checks that the enable-api-fields feature gate is set // to the wantVersion value and, if not, returns an error stating which feature // is dependent on the version and what the current version actually is. func ValidateEnabledAPIFields(ctx context.Context, featureName, wantVersion string) *apis.FieldError { currentVersion := config.FromContextOrDefaults(ctx).FeatureFlags.EnableAPIFields if currentVersion != wantVersion { var errs *apis.FieldError message := fmt.Sprintf(`%s requires "enable-api-fields" feature gate to be %q but it is %q`, featureName, wantVersion, currentVersion) return errs.Also(apis.ErrGeneric(message)) } var errs *apis.FieldError = nil return errs }
/* Copyright 2021 The Tekton Authors 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 v1beta1 import ( "context" "fmt" "github.com/tektoncd/pipeline/pkg/apis/config" "knative.dev/pkg/apis" ) // ValidateEnabledAPIFields checks that the enable-api-fields feature gate is set // to the wantVersion value and, if not, returns an error stating which feature // is dependent on the version and what the current version actually is. func ValidateEnabledAPIFields(ctx context.Context, featureName, wantVersion string) *apis.FieldError { currentVersion := config.FromContextOrDefaults(ctx).FeatureFlags.EnableAPIFields if currentVersion != wantVersion { var errs *apis.FieldError message := fmt.Sprintf(`%s requires "enable-api-fields" feature gate to be %q but it is %q`, featureName, wantVersion, currentVersion) return errs.Also(apis.ErrGeneric(message, "workspaces")) } var errs *apis.FieldError = nil return errs }
Make it easier to use corporate keys
from django.db import models from django.contrib.auth.models import AbstractUser from django_pgjson.fields import JsonField class Capsuler(AbstractUser): settings = JsonField(blank=True, default={}) def __unicode__(self): return self.username def get_active_keys(self): return APIKey.objects.filter(owner=self, expired=False) class APIKey(models.Model): KEY_TYPES = ( ('Account', 'Account'), ('Character', 'Character'), ('Corporation', 'Corporation') ) name = models.CharField(max_length=100) keyID = models.CharField(max_length=20) vCode = models.CharField(max_length=128) accessMask = models.IntegerField(null=True, editable=False) type = models.CharField(max_length=11, choices=KEY_TYPES, editable=False, null=True) expired = models.BooleanField(default=False, editable=False) expires = models.DateTimeField(editable=False, null=True) characterID = models.IntegerField(null=True) corporationID = models.IntegerField(null=True) owner = models.ForeignKey(Capsuler) def __unicode__(self): return self.name class APIUpdate(models.Model): service = models.CharField(max_length=100) last_update = models.DateTimeField(auto_now=True) apikey = models.ForeignKey(APIKey) class Meta: unique_together = ('service', 'apikey')
from django.db import models from django.contrib.auth.models import AbstractUser from django_pgjson.fields import JsonField class Capsuler(AbstractUser): settings = JsonField(blank=True, default={}) def __unicode__(self): return self.username def get_active_keys(self): return APIKey.objects.filter(owner=self, expired=False) class APIKey(models.Model): KEY_TYPES = ( ('Account', 'Account'), ('Character', 'Character'), ('Corporation', 'Corporation') ) name = models.CharField(max_length=100) keyID = models.CharField(max_length=20) vCode = models.CharField(max_length=128) accessMask = models.IntegerField(null=True, editable=False) type = models.CharField(max_length=11, choices=KEY_TYPES, editable=False, null=True) expired = models.BooleanField(default=False, editable=False) expires = models.DateTimeField(editable=False, null=True) owner = models.ForeignKey(Capsuler) def __unicode__(self): return self.name class APIUpdate(models.Model): service = models.CharField(max_length=100) last_update = models.DateTimeField(auto_now=True) apikey = models.ForeignKey(APIKey) class Meta: unique_together = ('service', 'apikey')
Improve color string regex pattern for multiline matches
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:([\s\S]*?)\}/gmi; let m; // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
'use strict'; // Load requirements const clk = require('chalk'), chalk = new clk.constructor({level: 1, enabled: true}); // Formats a string with ANSI styling module.exports = function(str) { // Variables const regex = /\{([a-z,]+)\:(.+?)\}/gi; let m; // Check for a non-string if ( typeof str !== 'string' ) { return ''; } // Loop through matches while ( ( m = regex.exec(str) ) !== null ) { // Allow for multiple formatting options let split = m[1].split(','), partial = m[2]; // Wrap the replacement area for ( let i in split ) { if ( chalk[split[i]] !== undefined ) { partial = chalk[split[i]](partial); } } // Make the replacement in the original string str = str.replace(m[0], partial); } // Still matches to be made return ( str.match(regex) !== null ? this.colorString(str) : str.replace(/\{([a-z,]+)\:/gi, '') ); };
Increase default DRILL_TIMEOUT to 60 minutes
### Redis Options REDIS_HOST="localhost" REDIS_PORT=6379 REDIS_DB=1 ### Celery Options BROKER_URL="amqp://guest@localhost//" CELERY_ROUTES = {'fuzzer.tasks.fuzz': {'queue': 'fuzzer'}, 'driller.tasks.drill': {'queue': 'driller'}} ### Environment Options # directory contain driller-qemu versions, relative to the directoy node.py is invoked in QEMU_DIR="driller-qemu" # directory containing the binaries, used by the driller node to find binaries BINARY_DIR="/cgc/binaries/" ### Driller options # how long to drill before giving up in seconds DRILL_TIMEOUT=60 * 60 # 60 minutes MEM_LIMIT=8 * 1024 * 1024 * 1024 ### Fuzzer options # how often to check for crashes in seconds CRASH_CHECK_INTERVAL=60 # how long to fuzz before giving up in seconds FUZZ_TIMEOUT=60 * 60 * 24 # how many fuzzers should be spun up when a fuzzing job is received FUZZER_INSTANCES=4 # where the fuzzer should place it's results on the filesystem FUZZER_WORK_DIR="work"
### Redis Options REDIS_HOST="localhost" REDIS_PORT=6379 REDIS_DB=1 ### Celery Options BROKER_URL="amqp://guest@localhost//" CELERY_ROUTES = {'fuzzer.tasks.fuzz': {'queue': 'fuzzer'}, 'driller.tasks.drill': {'queue': 'driller'}} ### Environment Options # directory contain driller-qemu versions, relative to the directoy node.py is invoked in QEMU_DIR="driller-qemu" # directory containing the binaries, used by the driller node to find binaries BINARY_DIR="/cgc/binaries/" ### Driller options # how long to drill before giving up in seconds DRILL_TIMEOUT=60 * 15 # 15 minutes MEM_LIMIT=8 * 1024 * 1024 * 1024 ### Fuzzer options # how often to check for crashes in seconds CRASH_CHECK_INTERVAL=60 # how long to fuzz before giving up in seconds FUZZ_TIMEOUT=60 * 60 * 24 # how many fuzzers should be spun up when a fuzzing job is received FUZZER_INSTANCES=4 # where the fuzzer should place it's results on the filesystem FUZZER_WORK_DIR="work"
Reduce chattiness of dev debug logging
/* jshint node: true */ module.exports = function(environment) { var ENV = { baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { dziBaseUrl: '//s3-us-west-2.amazonaws.com/media.incrossada.org', title: 'la incrossada' } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = false; ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_MODULE_RESOLVER = false; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'production') { } return ENV; };
/* jshint node: true */ module.exports = function(environment) { var ENV = { baseURL: '/', locationType: 'auto', EmberENV: { FEATURES: { // Here you can enable experimental features on an ember canary build // e.g. 'with-controller': true } }, APP: { dziBaseUrl: '//s3-us-west-2.amazonaws.com/media.incrossada.org', title: 'la incrossada' } }; if (environment === 'development') { // LOG_MODULE_RESOLVER is needed for pre-1.6.0 ENV.LOG_MODULE_RESOLVER = true; ENV.APP.LOG_RESOLVER = true; ENV.APP.LOG_ACTIVE_GENERATION = true; ENV.APP.LOG_MODULE_RESOLVER = true; // ENV.APP.LOG_TRANSITIONS = true; // ENV.APP.LOG_TRANSITIONS_INTERNAL = true; ENV.APP.LOG_VIEW_LOOKUPS = true; } if (environment === 'production') { } return ENV; };
Fix running average action history
import theano from sft import Size from sft.Actions import Actions from sft.agent.ah.ActionHistory import ActionHistory import numpy as np class RunningAvg(ActionHistory): def __init__(self, logger, n, factor): self.logger = logger self.n = n self.factor = factor self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX) def get_size(self): return Size(self.n, self.ACTION_WIDTH) def get_history(self, all_actions): return self.actions def new_action(self, a): for i in range(1, self.n)[::-1]: self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1] self.actions[0, :] = Actions.get_one_hot(a) self.logger.log_parameter("actions", str(self.actions)) def new_episode(self): self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
import theano from sft import Size from sft.Actions import Actions from sft.agent.ah.ActionHistory import ActionHistory import numpy as np class RunningAvg(ActionHistory): def __init__(self, logger, n, factor): self.logger = logger self.n = n self.factor = factor self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX) def get_size(self): return Size(self.n, self.ACTION_WIDTH) def get_history(self, all_actions): return self.actions def new_action(self, a): for i in range(1, self.n): self.actions[i] = (1 - self.factor) * self.actions[i] + self.factor * self.actions[i - 1] self.actions[0, :] = Actions.get_one_hot(a) self.logger.log_parameter("actions", str(self.actions)) def new_episode(self): self.actions = np.zeros([self.n, self.ACTION_WIDTH], dtype=theano.config.floatX)
Add fix for confusing security warnings when phantomjs exits
"use strict"; /** * Opens the given page and resolves when phantomjs called back. * Will be executed inside of phantomjs. * * @private * @param {string} url * @param {Function} resolve * @param {Function} reject */ function openPage(url, resolve, reject) { /* jshint validthis: true */ this.open(url, function onPageLoaded(status) { if (status !== "success") { return reject(new Error("Cannot load " + url + ": Phantomjs returned status " + status)); } resolve(); }); } /** * Calls phantom.exit() with errorcode 0 * * @private */ function exitPhantom() { /* global phantom */ Object.keys(pages).forEach(function (pageId) { // Closing all pages just to cleanup properly pages[pageId].close(); }); pages = null; // Using setTimeout(0) to ensure that all JS code still waiting in the queue is executed before exiting // Otherwise PhantomJS prints a confusing security warning // @see https://github.com/ariya/phantomjs/commit/1eec21ed5c887bf21a1a6833da3c98c68401d90e setTimeout(function () { phantom.exit(0); }, 0); } /** * Cleans all references to a specific page. * * @private * @param {number} pageId */ function disposePage(pageId) { /* global pages */ pages[pageId].close(); delete pages[pageId]; } exports.openPage = openPage; exports.exitPhantom = exitPhantom; exports.disposePage = disposePage;
"use strict"; /** * Opens the given page and resolves when phantomjs called back. * Will be executed inside of phantomjs. * * @private * @param {string} url * @param {Function} resolve * @param {Function} reject */ function openPage(url, resolve, reject) { /* jshint validthis: true */ this.open(url, function onPageLoaded(status) { if (status !== "success") { return reject(new Error("Cannot load " + url + ": Phantomjs returned status " + status)); } resolve(); }); } /** * Calls phantom.exit() with errorcode 0 * * @private */ function exitPhantom() { /* global phantom */ phantom.exit(0); } /** * Cleans all references to a specific page. * * @private * @param {number} pageId */ function disposePage(pageId) { /* global pages */ pages[pageId].close(); delete pages[pageId]; } exports.openPage = openPage; exports.exitPhantom = exitPhantom; exports.disposePage = disposePage;
Fix attach failing when no workspace is open
package me.coley.recaf.ui.controls; import javafx.scene.control.*; import javafx.scene.control.cell.ComboBoxListCell; import javafx.scene.layout.HBox; import me.coley.recaf.control.gui.GuiController; import me.coley.recaf.util.UiUtil; import me.coley.recaf.workspace.*; /** * Cell/renderer for displaying {@link JavaResource}s. */ public class ResourceSelectionCell extends ComboBoxListCell<JavaResource> { private final GuiController controller; /** * @param controller * Controller to use. */ public ResourceSelectionCell(GuiController controller) { this.controller = controller; } @Override public void updateItem(JavaResource item, boolean empty) { super.updateItem(item, empty); if(!empty) { HBox g = new HBox(); if(item != null) { String t = item.toString(); // Add icon for resource types g.getChildren().add(new IconView(UiUtil.getResourceIcon(item))); // Indicate which resource is the primary resource if(controller.getWorkspace() != null && item == controller.getWorkspace().getPrimary()) { Label lbl = new Label(" [Primary]"); lbl.getStyleClass().add("bold"); g.getChildren().add(lbl); } setText(t); } setGraphic(g); } else { setGraphic(null); setText(null); } } }
package me.coley.recaf.ui.controls; import javafx.scene.control.*; import javafx.scene.control.cell.ComboBoxListCell; import javafx.scene.layout.HBox; import me.coley.recaf.control.gui.GuiController; import me.coley.recaf.util.UiUtil; import me.coley.recaf.workspace.*; /** * Cell/renderer for displaying {@link JavaResource}s. */ public class ResourceSelectionCell extends ComboBoxListCell<JavaResource> { private final GuiController controller; /** * @param controller * Controller to use. */ public ResourceSelectionCell(GuiController controller) { this.controller = controller; } @Override public void updateItem(JavaResource item, boolean empty) { super.updateItem(item, empty); if(!empty) { HBox g = new HBox(); if(item != null) { String t = item.toString(); // Add icon for resource types g.getChildren().add(new IconView(UiUtil.getResourceIcon(item))); // Indicate which resource is the primary resource if(item == controller.getWorkspace().getPrimary()) { Label lbl = new Label(" [Primary]"); lbl.getStyleClass().add("bold"); g.getChildren().add(lbl); } setText(t); } setGraphic(g); } else { setGraphic(null); setText(null); } } }
Change logging api to incldue handle
package org.skife.jdbi.v2.logging; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.Handle; /** * Default SQLLog implementation, does nothing */ public final class NoOpLog implements SQLLog { final static BatchLogger batch = new BatchLogger() { public final void add(String sql) { } public final void log() { } }; public void logBeginTransaction(Handle h) { } public void logCommitTransaction(Handle h) { } public void logRollbackTransaction(Handle h) { } public void logObtainHandle(Handle h) { } public void logReleaseHandle(Handle h) { } public void logSQL(String sql) { } public void logPreparedBatch(String sql, int count) { } public BatchLogger logBatch() { return batch; } public void logCheckpointTransaction(Handle h, String name) { } public void logReleaseCheckpointTransaction(Handle h, String name) { } public void logRollbackToCheckpoint(Handle h, String checkpointName) { } }
package org.skife.jdbi.v2.logging; import org.skife.jdbi.v2.tweak.SQLLog; import org.skife.jdbi.v2.Handle; /** * Default SQLLog implementation, does nothing */ public final class NoOpLog implements SQLLog { final static BatchLogger batch = new BatchLogger() { public final void add(String sql) { } public final void log() { } }; public void logBeginTransaction(Handle h) { } public void logCommitTransaction(Handle h) { } public void logRollbackTransaction(Handle h) { } public void logObtainHandle(Handle h) { } public void logReleaseHandle(Handle h) { } public void logSQL(String sql) { } public void logPreparedBatch(String sql, int count) { } public BatchLogger logBatch() { return null; } public void logCheckpointTransaction(Handle h, String name) { } public void logReleaseCheckpointTransaction(Handle h, String name) { } public void logRollbackToCheckpoint(Handle h, String checkpointName) { } }
Increase gunicorn max_requests to avoid process churn at high request rates.
# This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Use our own Gevent worker worker_class = "ichnaea.gunicorn_worker.LocationGeventWorker" # Maximum number of simultaneous greenlets, # limited by number of DB and Redis connections worker_connections = 50 # Set timeout to the same value as the default one from Amazon ELB (60 secs). timeout = 60 # Disable keep-alive keepalive = 0 # Recycle worker processes after 10m requests to prevent memory leaks # from effecting us, at 1000 req/s this means recycle every 2.8 hours max_requests = 10000000 # Log errors to stderr errorlog = "-" # Avoid too much output on the console loglevel = "warning" def post_worker_init(worker): from random import randint # Use 10% jitter, to prevent all workers from restarting at once, # as they get an almost equal number of requests jitter = randint(0, max_requests // 10) worker.max_requests += jitter # Actually initialize the application worker.wsgi(None, None)
# This file contains gunicorn configuration setttings, as described at # http://docs.gunicorn.org/en/latest/settings.html # The file is loaded via the -c ichnaea.gunicorn_config command line option # Use our own Gevent worker worker_class = "ichnaea.gunicorn_worker.LocationGeventWorker" # Maximum number of simultaneous greenlets, # limited by number of DB and Redis connections worker_connections = 50 # Set timeout to the same value as the default one from Amazon ELB (60 secs). timeout = 60 # Disable keep-alive keepalive = 0 # Recycle worker processes after 100k requests to prevent memory leaks # from effecting us max_requests = 100000 # Log errors to stderr errorlog = "-" # Avoid too much output on the console loglevel = "warning" def post_worker_init(worker): from random import randint # Use 10% jitter, to prevent all workers from restarting at once, # as they get an almost equal number of requests jitter = randint(0, max_requests // 10) worker.max_requests += jitter # Actually initialize the application worker.wsgi(None, None)
Change license classifier to BSD License to remove PyPI error
#!/usr/bin/env python from setuptools import setup from setuptools import find_packages import derpibooru setup( name = "DerPyBooru", description = "Python bindings for Derpibooru's API", url = "https://github.com/joshua-stone/DerPyBooru", version = "0.5.2", author = "Joshua Stone", author_email = "joshua.gage.stone@gmail.com", license = "Simplified BSD License", platforms = ["any"], packages = find_packages(), install_requires = ["requests"], include_package_data = True, download_url = "https://github.com/joshua-stone/DerPyBooru/tarball/0.5.2", classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: BSD License", "Topic :: Software Development :: Libraries :: Python Modules" ] )
#!/usr/bin/env python from setuptools import setup from setuptools import find_packages import derpibooru setup( name = "DerPyBooru", description = "Python bindings for Derpibooru's API", url = "https://github.com/joshua-stone/DerPyBooru", version = "0.5.2", author = "Joshua Stone", author_email = "joshua.gage.stone@gmail.com", license = "Simplified BSD License", platforms = ["any"], packages = find_packages(), install_requires = ["requests"], include_package_data = True, download_url = "https://github.com/joshua-stone/DerPyBooru/tarball/0.5.2", classifiers = [ "Development Status :: 4 - Beta", "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: Simplified BSD License", "Topic :: Software Development :: Libraries :: Python Modules" ] )
Remove unnecessary 'done' calls from tests.
"use strict"; var Browser = require("zombie"); var expect = require("chai").expect; var Lurker = require("../lib/lurker"); describe("The lurker plugin", function () { it("has a name", function () { expect(Lurker.register.attributes, "name") .to.have.property("name", "lurker"); }); }); describe("The lurker status page", function () { describe("when not authenticated", function () { var browser; before(function (done) { browser = new Browser(); browser.visit("/").fin(done); }); it("challenges the request", function () { expect(browser.statusCode, "status").to.equal(401); }); }); describe("when authenticated", function () { var browser; before(function (done) { browser = new Browser(); browser.credentials.set({ username : "octocat" }); // Grafana likes to throw errors... browser.visit("/").fin(done); }); it("shows the Grafana dashboard", function () { expect(browser.text("title"), "title").to.match(/grafana/i); }); }); });
"use strict"; var Browser = require("zombie"); var expect = require("chai").expect; var Lurker = require("../lib/lurker"); describe("The lurker plugin", function () { it("has a name", function (done) { expect(Lurker.register.attributes, "name") .to.have.property("name", "lurker"); done(); }); }); describe("The lurker status page", function () { describe("when not authenticated", function () { var browser; before(function (done) { browser = new Browser(); browser.visit("/").fin(done); }); it("challenges the request", function () { expect(browser.statusCode, "status").to.equal(401); }); }); describe("when authenticated", function () { var browser; before(function (done) { browser = new Browser(); browser.credentials.set({ username : "octocat" }); // Grafana likes to throw errors... browser.visit("/").fin(done); }); it("shows the Grafana dashboard", function () { expect(browser.text("title"), "title").to.match(/grafana/i); }); }); });
Fix messageMatcher in situations where message is null
package io.cozmic.usher.pipeline; import de.odysseus.el.util.SimpleContext; import io.cozmic.usher.core.MessageMatcher; import io.cozmic.usher.message.PipelinePack; import javax.el.ExpressionFactory; import javax.el.ValueExpression; /** * Created by chuck on 7/3/15. */ public class JuelMatcher implements MessageMatcher { private static ExpressionFactory factory = ExpressionFactory.newInstance(); private SimpleContext context = new SimpleContext(); private ValueExpression expression; public JuelMatcher(String expressionVal) { expression = factory.createValueExpression(context, expressionVal, boolean.class); } @Override public boolean matches(PipelinePack pipelinePack) { SimpleContext runtimeContext = new SimpleContext(); final Object msg = pipelinePack.getMessage(); if (msg != null) { factory.createValueExpression(runtimeContext, "${msgClassSimpleName}", String.class).setValue(runtimeContext, msg.getClass().getSimpleName()); factory.createValueExpression(runtimeContext, "${msg}", msg.getClass()).setValue(runtimeContext, msg); } return (boolean) expression.getValue(runtimeContext); } }
package io.cozmic.usher.pipeline; import de.odysseus.el.util.SimpleContext; import io.cozmic.usher.core.MessageMatcher; import io.cozmic.usher.message.PipelinePack; import javax.el.ExpressionFactory; import javax.el.ValueExpression; /** * Created by chuck on 7/3/15. */ public class JuelMatcher implements MessageMatcher { private static ExpressionFactory factory = ExpressionFactory.newInstance(); private SimpleContext context = new SimpleContext(); private ValueExpression expression; public JuelMatcher(String expressionVal) { expression = factory.createValueExpression(context, expressionVal, boolean.class); } @Override public boolean matches(PipelinePack pipelinePack) { SimpleContext runtimeContext = new SimpleContext(); final Object msg = pipelinePack.getMessage(); factory.createValueExpression(runtimeContext, "${msgClassSimpleName}", String.class).setValue(runtimeContext, msg.getClass().getSimpleName()); factory.createValueExpression(runtimeContext, "${msg}", msg.getClass()).setValue(runtimeContext, msg); return (boolean) expression.getValue(runtimeContext); } }
Support profile.X_specific instead of profile['X-specific'].
if (process.env.NODE_ENV === 'development') { ['test1', 'test2'].forEach(createServiceWithName); } else { throw Error('Test login handlers can only be registered on development servers for security reasons.'); } function createServiceWithName(serviceName) { Accounts.registerLoginHandler(serviceName, function (options) { if (! options || ! options[serviceName]) { return undefined; } var selector = {}; selector['services.' + serviceName + '.name'] = options[serviceName]; var user = Meteor.users.findOne(selector); if (user) { return { userId: user._id }; } var servicesObj = {}; servicesObj[serviceName] = { name: options[serviceName] }; var profileObj = { doNotOverride: options[serviceName] // Field shared among services }; profileObj[serviceName + "_specific"] = options[serviceName]; var newUserId = Accounts.insertUserDoc(options, { profile: profileObj, services: servicesObj }); return { userId: newUserId }; }); }
if (process.env.NODE_ENV === 'development') { ['test1', 'test2'].forEach(createServiceWithName); } else { throw Error('Test login handlers can only be registered on development servers for security reasons.'); } function createServiceWithName(serviceName) { Accounts.registerLoginHandler(serviceName, function (options) { if (! options || ! options[serviceName]) { return undefined; } var selector = {}; selector['services.' + serviceName + '.name'] = options[serviceName]; var user = Meteor.users.findOne(selector); if (user) { return { userId: user._id }; } var servicesObj = {}; servicesObj[serviceName] = { name: options[serviceName] }; var profileObj = { doNotOverride: options[serviceName] // Field shared among services }; profileObj[serviceName + "-specific"] = options[serviceName]; var newUserId = Accounts.insertUserDoc(options, { profile: profileObj, services: servicesObj }); return { userId: newUserId }; }); }
Add valid cases for later
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`(abc)`)}, {"abcdef", regexp.MustCompile(`(abcdef)`)}, {"a,b", regexp.MustCompile(`(a|b)`)}, {"a,bc,def", regexp.MustCompile(`(a|bc|def)`)}, {"a\\,b", regexp.MustCompile(`(a,b)`)}, {"a\\,bc\\,def", regexp.MustCompile(`(a,bc,def)`)}, {"a\\,b,c", regexp.MustCompile(`(a,b|c)`)}, {"a,bc\\,def", regexp.MustCompile(`(a|bc,def)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
package main import ( "reflect" "regexp" "testing" ) var genMatcherTests = []struct { src string dst *regexp.Regexp }{ {"abc", regexp.MustCompile(`(abc)`)}, {"a,b", regexp.MustCompile(`(a|b)`)}, {"a\\,b", regexp.MustCompile(`(a,b)`)}, } func TestGenMatcher(t *testing.T) { for _, test := range genMatcherTests { expect := test.dst actual, err := newMatcher(test.src) if err != nil { t.Errorf("NewSubvert(%q) returns %q, want nil", test.src, err) } if !reflect.DeepEqual(actual, expect) { t.Errorf("%q: got %q, want %q", test.src, actual, expect) } } }
Increase description max length to 2500 characters
# -*- coding: utf-8 -*- from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey) from sqlalchemy.orm import relationship, backref from .base import Base class Record(Base): __tablename__ = 'records' id = Column(Integer, primary_key=True, autoincrement=False) genre_id = Column(Integer, ForeignKey('genres.id'), nullable=False) import_date = Column(DateTime, nullable=False) artist = Column(String(250), nullable=False) title = Column(String(250), nullable=False) label = Column(String(250), nullable=False) notes = Column(String(2500)) grade = Column(String(16), nullable=False) format = Column(String(2), nullable=False) price = Column(Integer) genre = relationship("Genre", backref=backref('records', order_by=id)) class RecordStatus(Base): __tablename__ = 'record_status' record_id = Column(Integer, ForeignKey('records.id'), primary_key=True, autoincrement=False) status = Column(String(50), nullable=False)
# -*- coding: utf-8 -*- from sqlalchemy import (Column, Integer, String, DateTime, ForeignKey) from sqlalchemy.orm import relationship, backref from .base import Base class Record(Base): __tablename__ = 'records' id = Column(Integer, primary_key=True, autoincrement=False) genre_id = Column(Integer, ForeignKey('genres.id'), nullable=False) import_date = Column(DateTime, nullable=False) artist = Column(String(250), nullable=False) title = Column(String(250), nullable=False) label = Column(String(250), nullable=False) notes = Column(String(500)) grade = Column(String(16), nullable=False) format = Column(String(2), nullable=False) price = Column(Integer) genre = relationship("Genre", backref=backref('records', order_by=id)) class RecordStatus(Base): __tablename__ = 'record_status' record_id = Column(Integer, ForeignKey('records.id'), primary_key=True, autoincrement=False) status = Column(String(50), nullable=False)
Include version 2.5.0 in PhantomJs test for versions
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.PhantomJsDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting PhatomJS versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class PhantomJsVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = PhantomJsDriverManager.getInstance(); specificVersions = new String[] { "1.9.7", "1.9.8", "2.1.1", "2.5.0" }; } }
/* * (C) Copyright 2016 Boni Garcia (http://bonigarcia.github.io/) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser General Public License * (LGPL) version 2.1 which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-2.1.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * */ package io.github.bonigarcia.wdm.test; import org.junit.Before; import io.github.bonigarcia.wdm.PhantomJsDriverManager; import io.github.bonigarcia.wdm.base.BaseVersionTst; /** * Test asserting PhatomJS versions. * * @author Boni Garcia (boni.gg@gmail.com) * @since 1.4.0 */ public class PhantomJsVersionTest extends BaseVersionTst { @Before public void setup() { browserManager = PhantomJsDriverManager.getInstance(); specificVersions = new String[] { "1.9.7", "1.9.8", "2.1.1" }; } }
Set the view content based on the response content.
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Application * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Page Controller Class * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku_Server * @subpackage Application */ class ComApplicationControllerPage extends KControllerResource { protected function _initialize(KConfig $config) { $config->append(array( 'view' => 'page' )); parent::_initialize($config); } protected function _actionGet(KCommandContext $context) { $this->getView()->content = $context->response->getContent(); return parent::_actionGet($context); } }
<?php /** * @version $Id$ * @package Nooku_Server * @subpackage Application * @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net) * @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> * @link http://www.nooku.org */ /** * Page Controller Class * * @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens> * @package Nooku_Server * @subpackage Application */ class ComApplicationControllerPage extends KControllerResource { protected function _initialize(KConfig $config) { $config->append(array( 'view' => 'page' )); parent::_initialize($config); } }
Maintain the previous behavior where if there was no result set we'd attempt to pass it to res.json and have express handle the exception and bubble it up.
'use strict'; const KMSProvider = require('../../providers/kms'); /** * AWS-SDK gives out weirdly formatted keys, so make them * consistent with formatting across the rest of Tokend * * @param {Object} obj * @returns {Object} */ const normalizeKeys = (obj) => Object.keys(obj).reduce((acc, key) => { acc[key.toLowerCase()] = obj[key]; return acc; }, {}); /** * Route handler for KMS secrets * @returns {function} */ function KMS() { return (req, res, next) => { (new KMSProvider(req.body)).initialize().then((result) => { // I don't know how we'd get a falsy `result` but we need a method for handling it if (!result) { return res.json(result); } let data = {}; // Handle a case where there's no if (result.hasOwnProperty('data')) { data = normalizeKeys(result.data); } // Check for both undefined and null. `!= null` handles both cases. if (data.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq data.plaintext = Buffer.from(data.plaintext, 'base64').toString(); } res.json(data); }).catch(next); }; } module.exports = KMS;
'use strict'; const KMSProvider = require('../../providers/kms'); /** * AWS-SDK gives out weirdly formatted keys, so make them * consistent with formatting across the rest of Tokend * * @param {Object} obj * @returns {Object} */ const normalizeKeys = (obj) => Object.keys(obj).reduce((acc, key) => { acc[key.toLowerCase()] = obj[key]; return acc; }, {}); /** * Route handler for KMS secrets * @returns {function} */ function KMS() { return (req, res, next) => { (new KMSProvider(req.body)).initialize().then((result) => { // I don't know how we'd get a falsy `result` but we need a method for handling it if (!result) { return; } let data = {}; // Handle a case where there's no if (result.hasOwnProperty('data')) { data = normalizeKeys(result.data); } // Check for both undefined and null. `!= null` handles both cases. if (data.hasOwnProperty('plaintext')) { // eslint-disable-line eqeqeq data.plaintext = Buffer.from(data.plaintext, 'base64').toString(); } res.json(data); }).catch(next); }; } module.exports = KMS;
Add note that staff knows the password
<div class="pure-g centered-row"> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <?php echo _('If you do not want to check in, you can still use the access code!') ; ?> <p> <p> <?php echo _('Just ask our staff about the Wi-Fi.') ; ?> <p> </div> </div> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <a href="<?php echo $retry_url; ?>" class="pure-button pure-button-primary"> <i class="fa fa-play fa-lg"></i> <?php echo _('Enter access code'); ?> </a> </p> </div> </div> </div>
<div class="pure-g centered-row"> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <?php echo _('If you do not want to check in, you can still use the access code!') ; ?> <p> </div> </div> <div class="pure-u-1 pure-u-md-1-2"> <div class="l-box"> <p> <a href="<?php echo $retry_url; ?>" class="pure-button pure-button-primary"> <i class="fa fa-play fa-lg"></i> <?php echo _('Enter access code'); ?> </a> </p> </div> </div> </div>
Index.js: Move blogController to run only if blog section is loaded
window.onload = function() { sectionShow(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; if (event.target.id == 'blog_btn') { blogController() }; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
window.onload = function() { sectionShow(); blogController(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
Fix bug in word count example
"use strict"; //# aims to be similiar to this "official" word count example //# https://github.com/apache/kafka/blob/0.10.0/streams/examples/src/main/java/org/apache/kafka/streams/examples/wordcount/WordCountDemo.java /* the input topic could look like this: "fruit banana" "fruit cherry" "vegetable broccoli" "fruit strawberry" "vegetable lettuce" the output topic would then look like this: "fruit 3" */ const {KafkaStreams} = require("./../index.js"); const config = require("./../test/test-config.js"); const kafkaStreams = new KafkaStreams(config); const stream = kafkaStreams.getKStream("my-input-topic"); stream .map(keyValueMapperEtl) .countByKey("key", "count") .filter(kv => kv.count >= 3) .map(kv => kv.key + " " + kv.count) .tap(kv => console.log(kv)) .to("my-output-topic"); stream.start(); //consume & produce for 5 seconds setTimeout(kafkaStreams.closeAll.bind(kafkaStreams), 5000); function keyValueMapperEtl(message){ const elements = message.toLowerCase().split(" "); return { key: elements[0], value: elements[1] }; } //# alternatively checkout ../test/unit/WordCount.test.js for a working example without kafka broker
"use strict"; //# aims to be similiar to this "official" word count example //# https://github.com/apache/kafka/blob/0.10.0/streams/examples/src/main/java/org/apache/kafka/streams/examples/wordcount/WordCountDemo.java /* the input topic could look like this: "fruit banana" "fruit cherry" "vegetable broccoli" "fruit strawberry" "vegetable lettuce" the output topic would then look like this: "fruit 3" */ const {KafkaStreams} = require("./../index.js"); const config = require("./../test/test-config.js"); const kafkaStreams = new KafkaStreams(config); const stream = kafkaStreams.getKStream("my-input-topic"); stream .map(keyValueMapperEtl) .countByKey("key", "count") .filter(kv => kv.count >= 3) .map(kv => kv.key + " " + kv.count) .tap(kv => console.log(kv)) .to("my-output-topic"); stream.start(); //consume & produce for 5 seconds setTimeout(kafkaStreams.closeAll().bind(kafkaStreams), 5000); function keyValueMapperEtl(message){ const elements = message.toLowerCase().split(" "); return { key: elements[0], value: elements[1] }; } //# alternatively checkout ../test/unit/WordCount.test.js for a working example without kafka broker
Set fixture scope to module, so that pipes from one file dont influence tests from another
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="module") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="module") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="module") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
#!/usr/bin/env python # -*- coding: utf-8 -*- # type: ignore """Shared fixture functions.""" import pathlib import pytest # pylint: disable=E0401 import spacy # pylint: disable=E0401 from spacy.language import Language # pylint: disable=E0401 from spacy.tokens import Doc # pylint: disable=E0401 @pytest.fixture(scope="session") def nlp () -> Language: """ Language shared fixture. """ nlp = spacy.load("en_core_web_sm") # pylint: disable=W0621 return nlp @pytest.fixture(scope="session") def doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a piece of football news. """ text = pathlib.Path("dat/cfc.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc @pytest.fixture(scope="session") def long_doc (nlp: Language) -> Doc: # pylint: disable=W0621 """ Doc shared fixture. returns: spaCy EN doc containing a long text. """ text = pathlib.Path("dat/lee.txt").read_text() doc = nlp(text) # pylint: disable=W0621 return doc
Handle situations with no discussions
<div class="data-list"> @forelse ($discussions as $discussion) <div class="block"> <div class="item"> <div class="item-avatar"> {!! avatar($discussion->author)->link() !!} </div> <div class="item-content"> {!! $discussion->present()->titleAsLink !!} <div class="meta"> <div class="meta-item topic"> {!! $discussion->present()->topic !!} </div> @if ($discussion->replies_count > 0) <div class="meta-item replies"> @icon('chat') <span>{{ $discussion->replies_count }} {{ str_plural('reply', $discussion->replies_count) }}</span> </div> @endif <div class="meta-item timestamp"> @icon('clock') <span> {!! $discussion->present()->updatedAtRelative !!} by&nbsp;{!! $discussion->present()->updatedBy !!} </span> </div> @if ($discussion->answer_count > 0) <div class="meta-item answered"> @icon('check') <span>answered</span> </div> @endif </div> </div> </div> </div> @empty {!! alert('warning', 'No discussions found.') !!} @endforelse </div>
<div class="data-list"> @foreach ($discussions as $discussion) <div class="block"> <div class="item"> <div class="item-avatar"> {!! avatar($discussion->author)->link() !!} </div> <div class="item-content"> {!! $discussion->present()->titleAsLink !!} <div class="meta"> <div class="meta-item topic"> {!! $discussion->present()->topic !!} </div> @if ($discussion->replies_count > 0) <div class="meta-item replies"> @icon('chat') <span>{{ $discussion->replies_count }} {{ str_plural('reply', $discussion->replies_count) }}</span> </div> @endif <div class="meta-item timestamp"> @icon('clock') <span> {!! $discussion->present()->updatedAtRelative !!} by&nbsp;{!! $discussion->present()->updatedBy !!} </span> </div> @if ($discussion->answer_count > 0) <div class="meta-item answered"> @icon('check') <span>answered</span> </div> @endif </div> </div> </div> </div> @endforeach </div>
Use handlebars.js instead of runtime Due to a whacky bug with handlebars minified version, use full stuff. This is 100kb greater. Have to fix this when they fix this issue
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var htmlmin = require('broccoli-htmlmin'); var app = new EmberApp({ storeConfigInMeta: false }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/animate.css/animate.css'); app.import('vendor/scripts/jquery.drawPieChart.js'); var index = app.legacyFilesToAppend.indexOf('bower_components/handlebars/handlebars.runtime.js'); if(index) { app.legacyFilesToAppend[index] = 'bower_components/handlebars/handlebars.js'; } var tree = app.toTree(); options = { quotes: true }; tree = htmlmin(tree, options); module.exports = tree;
/* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); var htmlmin = require('broccoli-htmlmin'); var app = new EmberApp({ storeConfigInMeta: false }); // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. app.import('bower_components/animate.css/animate.css'); app.import('vendor/scripts/jquery.drawPieChart.js'); var tree = app.toTree(); options = { quotes: true }; tree = htmlmin(tree, options); module.exports = tree;
Fix typo in Licorice Mode name assignment
/* eslint-disable no-magic-numbers */ import LabeledMode from './LabeledMode'; class LicoriceMode extends LabeledMode { static id = 'LC'; constructor(opts) { super(opts); } calcAtomRadius(_atom) { return this.opts.bond; } calcStickRadius() { return this.opts.bond; } calcSpaceFraction() { return this.opts.space; } getAromRadius() { return this.opts.aromrad; } showAromaticLoops() { return this.opts.showarom; } drawMultiorderBonds() { return this.opts.multibond; } /** @deprecated Old-fashioned atom labels, to be removed in the next major version. */ getLabelOpts() { return { fg: 'none', bg: '0x202020', showBg: false, labels: this.settings.now.labels, colors: true, adjustColor: true, transparent: true, }; } } LicoriceMode.prototype.id = 'LC'; LicoriceMode.prototype.name = 'Licorice'; LicoriceMode.prototype.shortName = 'Licorice'; LicoriceMode.prototype.depGroups = [ 'AtomsSpheres', 'BondsCylinders', 'ALoopsTorus', ]; export default LicoriceMode;
/* eslint-disable no-magic-numbers */ import LabeledMode from './LabeledMode'; class LicoriceMode extends LabeledMode { static id = 'LC'; constructor(opts) { super(opts); } calcAtomRadius(_atom) { return this.opts.bond; } calcStickRadius() { return this.opts.bond; } calcSpaceFraction() { return this.opts.space; } getAromRadius() { return this.opts.aromrad; } showAromaticLoops() { return this.opts.showarom; } drawMultiorderBonds() { return this.opts.multibond; } /** @deprecated Old-fashioned atom labels, to be removed in the next major version. */ getLabelOpts() { return { fg: 'none', bg: '0x202020', showBg: false, labels: this.settings.now.labels, colors: true, adjustColor: true, transparent: true, }; } } LicoriceMode.prototype.id = 'LC'; LicoriceMode.prototype.hortName = 'Licorice'; LicoriceMode.prototype.shortName = 'Licorice'; LicoriceMode.prototype.depGroups = [ 'AtomsSpheres', 'BondsCylinders', 'ALoopsTorus', ]; export default LicoriceMode;
Add index on file tags field
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['storedfilenode'].create_index([ ('tags', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('external_accounts', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
# Indices that need to be added manually: # # invoke shell --no-transaction from pymongo import ASCENDING, DESCENDING db['user'].create_index([ ('emails', ASCENDING), ]) db['user'].create_index([ ('external_accounts', ASCENDING), ]) db['user'].create_index([ ('emails', ASCENDING), ('username', ASCENDING), ]) db['node'].create_index([ ('is_deleted', ASCENDING), ('is_collection', ASCENDING), ('is_public', ASCENDING), ('institution_id', ASCENDING), ('is_registration', ASCENDING), ('contributors', ASCENDING), ]) db['node'].create_index([ ('tags', ASCENDING), ('is_public', ASCENDING), ('is_deleted', ASCENDING), ('institution_id', ASCENDING), ])
Add mode switch to res.company
# -*- coding: utf-8 -*- ############################################################################## # # Set minimum order on suppliers # Copyright (C) 2016 OpusVL (<http://opusvl.com/>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import ( res_company, res_partner, purchase, ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
# -*- coding: utf-8 -*- ############################################################################## # # Set minimum order on suppliers # Copyright (C) 2016 OpusVL (<http://opusvl.com/>) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## from . import ( res_partner, purchase, ) # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
Add missed file to the test
/** * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ elementName: 'ibm-element', elementDescription: 'IBM element description', githubOrganization: 'IBMResearch' }) .toPromise(); }); it('creates files', function() { assert.file([ 'demo/index.html', 'test/ibm-element.html', 'test/index.html', '.gitignore', '.eslintrc.json', 'bower.json', 'ibm-element.html', 'index.html', 'LICENSE', 'README.md' ]); }); });
/** * @license * Copyright (c) 2016 The IBM Research Emergent Solutions authors. All rights reserved. * This code may only be used under the MIT style license found at https://ibmresearch.github.io/LICENSE.txt * The complete set of authors may be found at https://ibmresearch.github.io/AUTHORS.txt * The complete set of contributors may be found at https://ibmresearch.github.io/CONTRIBUTORS.txt */ 'use strict'; var path = require('path'); var assert = require('yeoman-assert'); var helpers = require('yeoman-test'); describe('generator-polymer-init-ibm-element:app', function() { before(function() { return helpers.run(path.join(__dirname, '../generators/app')) .withPrompts({ elementName: 'ibm-element', elementDescription: 'IBM element description', githubOrganization: 'IBMResearch' }) .toPromise(); }); it('creates files', function() { assert.file([ 'demo/index.html', 'test/ibm-element.html', 'test/index.html', '.gitignore', 'ibm-element.html', 'bower.json', 'index.html', 'LICENSE', 'README.md' ]); }); });
Add is-casting-shadow to Layout Header.
import m from 'mithril'; import attributes from '../attributes'; export let Header = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {scroll, waterfall, transparent, castShadow} = args; attr.class.push('mdl-layout__header'); if(scroll) attr.class.push('mdl-layout__header--scroll'); if(waterfall) attr.class.push('mdl-layout__header--waterfall'); if(transparent) attr.class.push('mdl-layout__header--transparent'); if(castShadow) attr.class.push('is-casting-shadow'); return <header {...attr}>{children}</header>; } }; export let HeaderRow = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); attr.class.push('mdl-layout__header-row'); return <div {...attr}>{children}</div>; } };
import m from 'mithril'; import attributes from '../attributes'; export let Header = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); let {scroll, waterfall, transparent} = args; attr.class.push('mdl-layout__header'); if(scroll) attr.class.push('mdl-layout__header--scroll'); if(waterfall) attr.class.push('mdl-layout__header--waterfall'); if(transparent) attr.class.push('mdl-layout__header--transparent'); return <header {...attr}>{children}</header>; } }; export let HeaderRow = { view(ctrl, args, ...children) { args = args || {}; let attr = attributes(args); attr.class.push('mdl-layout__header-row'); return <div {...attr}>{children}</div>; } };
Increment GopherJS version to 1.16.2+go1.16.4
// +build go1.16 package compiler import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) // Version is the GopherJS compiler version string. const Version = "1.16.2+go1.16.4" // GoVersion is the current Go 1.x version that GopherJS is compatible with. const GoVersion = 16 // CheckGoVersion checks the version of the Go distribution // at goroot, and reports an error if it's not compatible // with this version of the GopherJS compiler. func CheckGoVersion(goroot string) error { if nvc, err := strconv.ParseBool(os.Getenv("GOPHERJS_SKIP_VERSION_CHECK")); err == nil && nvc { return nil } v, err := ioutil.ReadFile(filepath.Join(goroot, "VERSION")) if err != nil { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but failed to read its VERSION file: %v", Version, err) } if !bytes.HasPrefix(v, []byte("go1.16")) { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but found version %s", Version, v) } return nil }
// +build go1.16 package compiler import ( "bytes" "fmt" "io/ioutil" "os" "path/filepath" "strconv" ) // Version is the GopherJS compiler version string. const Version = "1.16.1+go1.16.3" // GoVersion is the current Go 1.x version that GopherJS is compatible with. const GoVersion = 16 // CheckGoVersion checks the version of the Go distribution // at goroot, and reports an error if it's not compatible // with this version of the GopherJS compiler. func CheckGoVersion(goroot string) error { if nvc, err := strconv.ParseBool(os.Getenv("GOPHERJS_SKIP_VERSION_CHECK")); err == nil && nvc { return nil } v, err := ioutil.ReadFile(filepath.Join(goroot, "VERSION")) if err != nil { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but failed to read its VERSION file: %v", Version, err) } if !bytes.HasPrefix(v, []byte("go1.16")) { return fmt.Errorf("GopherJS %s requires a Go 1.16.x distribution, but found version %s", Version, v) } return nil }
Add coreNLP models jar relative path as well
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') coreNLPModelsPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLPModels.jar') self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath, coreNLPModelsPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results
#!/usr/bin/env python import os """ Performs some core NLP operations as a proof of concept for the library. """ from stanford_corenlp_pywrapper import CoreNLP class StanfordCoreNLP: def __init__(self): # I don't see anywhere to put properties like this path... # For now it's hardcoded and would need to be changed when deployed... print "Some stuff" print os.path.abspath(__file__) coreNLPPath = os.path.join(os.path.dirname(__file__), '../../lib/stanfordCoreNLP.jar') print coreNLPPath self.proc = CoreNLP('pos', corenlp_jars=[coreNLPPath]) def run(self, data): results = [] for corpus in data: results.append(self.proc.parse_doc(corpus.contents)) return results
Revert last change (breaks XSPT)
class RepeatTracker(object): def __init__(self): self.repeater_map = {} def __setitem__(self, key, value): try: self.repeater_map[key].index = value except KeyError, e: self.repeater_map[key] = Repeater(value) def __getitem__(self, key): return self.repeater_map[key] class Repeater(object): def __init__(self, index=0, item=None, length=None): self.index = index self.item = item self.length = length @property def number(self): return self.index + 1 @property def even(self): return not (self.index % 2) @property def odd(self): return (self.index % 2) @property def first(self): return (self.index == 0) @property def last(self): return (self.index == (self.length - 1)) class RepeatIterator(object): def __init__(self, iterable): self.src_iterable = iterable self.src_iterator = enumerate(iterable) try: self.length = len(iterable) except TypeError: # if the iterable is a generator, then we have no length self.length = None def __iter__(self): return self def next(self): index, item = self.src_iterator.next() return Repeater(index, item, self.length)
class RepeatTracker(object): def __init__(self): self.repeater_map = {} def __setitem__(self, key, value): try: self.repeater_map[key].index = value except KeyError, e: self.repeater_map[key] = Repeater(value) def __getitem__(self, key): return self.repeater_map[key] class Repeater(object): def __init__(self, index=0, length=None): self.index = index self.length = length @property def number(self): return self.index + 1 @property def even(self): return not (self.index % 2) @property def odd(self): return (self.index % 2) @property def first(self): return (self.index == 0) @property def last(self): return (self.index == (self.length - 1)) def reiterate(iterable): try: length = len(iterable) except TypeError: # if the iterable is a generator, then we have no length length = None for index, item in enumerate(iterable): yield (Repeater(index, length), item)
Remove django requirement to prevent installing two versions of django
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-socialregistration', version='0.4.2', author='Alen Mujezinovic', author_email='alen@caffeinehit.com', description='Django application enabling registration through a variety of APIs', long_description=open('README.rst').read(), url='http://github.com/flashingpumpkin/django-socialregistration', keywords='django facebook twitter oauth openid registration', #install_requires=['django', 'oauth2', 'python-openid'], install_requires=['oauth2', 'python-openid'], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(), package_data={'socialregistration': ['templates/socialregistration/*.html'], } ) if __name__ == '__main__': setup(**METADATA)
#!/usr/bin/env python from setuptools import setup,find_packages METADATA = dict( name='django-socialregistration', version='0.4.2', author='Alen Mujezinovic', author_email='alen@caffeinehit.com', description='Django application enabling registration through a variety of APIs', long_description=open('README.rst').read(), url='http://github.com/flashingpumpkin/django-socialregistration', keywords='django facebook twitter oauth openid registration', install_requires=['django', 'oauth2', 'python-openid'], include_package_data=True, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'Topic :: Software Development :: Libraries :: Python Modules', 'Environment :: Web Environment', 'Topic :: Internet', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], packages=find_packages(), package_data={'socialregistration': ['templates/socialregistration/*.html'], } ) if __name__ == '__main__': setup(**METADATA)
Make queues durable by default in the MetaData so tasks & backgroundable get it for free.
/* * Copyright 2008-2011 Red Hat, Inc, and individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.torquebox.messaging.metadata; public class QueueMetaData extends AbstractDestinationMetaData { private boolean durable = true; public QueueMetaData() { } public QueueMetaData(String name) { super( name ); } public String toString() { return "[QueueMetaData: name=" + getName() + "]"; } public void setDurable(boolean durable) { this.durable = durable; } public boolean isDurable() { return this.durable; } }
/* * Copyright 2008-2011 Red Hat, Inc, and individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.torquebox.messaging.metadata; public class QueueMetaData extends AbstractDestinationMetaData { private boolean durable; public QueueMetaData() { } public QueueMetaData(String name) { super( name ); } public String toString() { return "[QueueMetaData: name=" + getName() + "]"; } public void setDurable(boolean durable) { this.durable = durable; } public boolean isDurable() { return this.durable; } }
Include data in release package Closes #3
from setuptools import setup, find_packages version = '0.3.2' setup( name='django-tagging-ext', version=version, description="Adds in new features to supplement django-tagging", long_description=open("README.rst").read(), classifiers=[ "Development Status :: 4 - Beta", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Utilities", ], keywords='django,pinax', author='Daniel Greenfeld', author_email='pydanny@gmail.com', url='http://github.com/pydanny/django-tagging-ext', license='MIT', packages=find_packages(), include_package_data=True, )
from setuptools import setup, find_packages version = '0.3.2' setup( name='django-tagging-ext', version=version, description="Adds in new features to supplement django-tagging", long_description=open("README.rst").read(), classifiers=[ "Development Status :: 4 - Beta", "Programming Language :: Python", "Topic :: Software Development :: Libraries :: Python Modules", "Framework :: Django", "Environment :: Web Environment", "Intended Audience :: Developers", "License :: OSI Approved :: BSD License", "Operating System :: OS Independent", "Topic :: Utilities", ], keywords='django,pinax', author='Daniel Greenfeld', author_email='pydanny@gmail.com', url='http://github.com/pydanny/django-tagging-ext', license='MIT', packages=find_packages(), )
Add basic users module test
const mockCreate = jest.fn() jest.mock('@/services/api/users', () => ({ create: mockCreate })) import { createStore } from '>/helpers' describe('users', () => { beforeEach(() => jest.resetModules()) let storeMocks let store beforeEach(() => { storeMocks = { auth: { actions: { login: jest.fn(), }, }, } store = createStore({ users: require('./users'), ...storeMocks, }) }) it('can signup', async () => { let signupData = { email: 'foo@foo.com', password: 'foo' } mockCreate.mockImplementation(user => user) await store.dispatch('users/signup', signupData) expect(mockCreate).toBeCalledWith(signupData) expect(storeMocks.auth.actions.login.mock.calls[0][1]).toEqual(signupData) }) it('can get all entries', () => { expect(store.getters['users/all']).toEqual([]) }) })
const mockCreate = jest.fn() jest.mock('@/services/api/users', () => ({ create: mockCreate })) import { createStore } from '>/helpers' describe('users', () => { beforeEach(() => jest.resetModules()) let storeMocks let store beforeEach(() => { storeMocks = { auth: { actions: { login: jest.fn(), }, }, } store = createStore({ users: require('./users'), ...storeMocks, }) }) it('can signup', async () => { let signupData = { email: 'foo@foo.com', password: 'foo' } mockCreate.mockImplementation(user => user) await store.dispatch('users/signup', signupData) expect(mockCreate).toBeCalledWith(signupData) expect(storeMocks.auth.actions.login.mock.calls[0][1]).toEqual(signupData) }) })
Migrate profiles manager tests to pytest
from unittest.mock import MagicMock, patch from buffpy.managers.profiles import Profiles from buffpy.models.profile import Profile, PATHS MOCKED_RESPONSE = { "name": "me", "service": "twiter", "id": 1 } def test_profiles_manager_all_method(): """ Should retrieve profile info. """ mocked_api = MagicMock() mocked_api.get.return_value = [{"a": "b"}] with patch("buffpy.managers.profiles.Profile", return_value=1) as mocked_profile: profiles = Profiles(api=mocked_api).all() assert profiles == [1] mocked_api.get.assert_called_once_with(url=PATHS["GET_PROFILES"]) mocked_profile.assert_called_once_with(mocked_api, {"a": "b"}) def test_profiles_manager_filter_method(): """ Should filter based on criteria. """ mocked_api = MagicMock() profiles = Profiles(mocked_api, [{"a": "b"}, {"a": "c"}]) assert profiles.filter(a="b") == [{"a": "b"}] def test_profiles_manager_filter_method_empty(): """ Should filter if profile manager is None. """ mocked_api = MagicMock() mocked_api.get.return_value = [{"a": "b"}, {"a": "c"}] profiles = Profiles(api=mocked_api) assert profiles.filter(a="b") == [Profile(mocked_api, {"a": "b"})]
from nose.tools import eq_ from mock import MagicMock, patch from buffpy.managers.profiles import Profiles from buffpy.models.profile import Profile, PATHS mocked_response = { 'name': 'me', 'service': 'twiter', 'id': 1 } def test_profiles_manager_all_method(): ''' Test basic profiles retrieving ''' mocked_api = MagicMock() mocked_api.get.return_value = [{'a':'b'}] with patch('buffpy.managers.profiles.Profile') as mocked_profile: mocked_profile.return_value = 1 profiles = Profiles(api=mocked_api).all() eq_(profiles, [1]) mocked_api.get.assert_called_once_with(url=PATHS['GET_PROFILES']) mocked_profile.assert_called_once_with(mocked_api, {'a': 'b'}) def test_profiles_manager_filter_method(): ''' Test basic profiles filtering based on some minimal criteria ''' mocked_api = MagicMock() profiles = Profiles(mocked_api, [{'a':'b'}, {'a': 'c'}]) eq_(profiles.filter(a='b'), [{'a': 'b'}]) def test_profiles_manager_filter_method_empty(): ''' Test basic profiles filtering when the manager is empty ''' mocked_api = MagicMock() mocked_api.get.return_value = [{'a':'b'}, {'a': 'c'}] profiles = Profiles(api=mocked_api) eq_(profiles.filter(a='b'), [Profile(mocked_api, {'a': 'b'})])
Update path to save to mnt dir
from __future__ import division from __future__ import print_function from __future__ import absolute_import import subprocess if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('layer', type=str, help='fc6|conv42|pool1') parser.add_argument('--cuda-device', type=int, default=0, help='0|1|2|3 [default: 0]') args = parser.parse_args() for i in xrange(5): out_dir = '/mnt/visual_communication_dataset/trained_models_5_30_18/%s/%d' % (args.layer, i + 1) train_test_split_dir = './train_test_split/%d' % (i + 1) command = 'CUDA_VISIBLE_DEVICES={device} python train_average.py {layer} --train-test-split-dir {split_dir} --out-dir {out_dir} --cuda'.format( device=args.cuda_device, layer=args.layer, split_dir=train_test_split_dir, out_dir=out_dir) subprocess.call(command, shell=True)
from __future__ import division from __future__ import print_function from __future__ import absolute_import import subprocess if __name__ == "__main__": import argparse parser = argparse.ArgumentParser() parser.add_argument('layer', type=str, help='fc6|conv42|pool1') parser.add_argument('--cuda-device', type=int, default=0, help='0|1|2|3 [default: 0]') args = parser.parse_args() for i in xrange(5): out_dir = './trained_models/%s/%d' % (args.layer, i + 1) train_test_split_dir = './train_test_split/%d' % (i + 1) command = 'CUDA_VISIBLE_DEVICES={device} python train_average.py {layer} --train-test-split-dir {split_dir} --out-dir {out_dir} --cuda'.format( device=args.cuda_device, layer=args.layer, split_dir=train_test_split_dir, out_dir=out_dir) subprocess.call(command, shell=True)
Add beta version tagging for 0.5 beta 1
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from eforge.menu import ItemOrder EFORGE_PLUGIN = { 'name': 'EForge Core', 'credit': 'Copyright &copy; 2010 Element43 and contributors', 'provides': { 'mnu': [('project-page', ItemOrder(000, 'Summary'))], }, } VERSION = (0, 5, 0, 'beta 1') def get_version(): return '%d.%d.%d %s' % VERSION
# -*- coding: utf-8 -*- # EForge project management system, Copyright © 2010, Element43 # # Permission to use, copy, modify, and/or distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR # ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF # OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # from eforge.menu import ItemOrder EFORGE_PLUGIN = { 'name': 'EForge Core', 'credit': 'Copyright &copy; 2010 Element43 and contributors', 'provides': { 'mnu': [('project-page', ItemOrder(000, 'Summary'))], }, } VERSION = (0, 5, 0) def get_version(): return '%d.%d.%d' % VERSION
Fix URL schema for subscribers
const express = require('express') const guildFeedSubscriberAPI = express.Router({ mergeParams: true }) const controllers = require('../../../../../controllers/index.js') const feedHasSubscriber = require('../../../../../middleware/feedHasSubscriber.js') const Joi = require('@hapi/joi') const validator = require('express-joi-validation').createValidator({ passError: true }); const filterSchema = require('../../../../../util/validation/filterSchema.js') const subscriberSchema = require('../../../../../util/validation/subscriberSchema.js') const subscriberIDSchema = Joi.object({ guildID: Joi.string(), feedID: Joi.string(), subscriberID: Joi.string() }) // Create a subscriber guildFeedSubscriberAPI.post( '/', validator.body(subscriberSchema), controllers.api.guilds.feeds.subscribers.createSubscriber ) // Validate the subscriber exists for the feed in params guildFeedSubscriberAPI.use( '/:subscriberID', validator.params(subscriberIDSchema), feedHasSubscriber ) // Delete a subscriber guildFeedSubscriberAPI.delete( '/:subscriberID', controllers.api.guilds.feeds.subscribers.deleteSubscriber ) // Edit a subscriber guildFeedSubscriberAPI.patch( '/:subscriberID', validator.body(filterSchema), controllers.api.guilds.feeds.subscribers.editSubscriber ) module.exports = guildFeedSubscriberAPI
const express = require('express') const guildFeedSubscriberAPI = express.Router({ mergeParams: true }) const controllers = require('../../../../../controllers/index.js') const feedHasSubscriber = require('../../../../../middleware/feedHasSubscriber.js') const Joi = require('@hapi/joi') const validator = require('express-joi-validation').createValidator({ passError: true }); const filterSchema = require('../../../../../util/validation/filterSchema.js') const subscriberSchema = require('../../../../../util/validation/subscriberSchema.js') const subscriberIDSchema = Joi.object({ subscriberID: Joi.string() }) // Create a subscriber guildFeedSubscriberAPI.post( '/', validator.body(subscriberSchema), controllers.api.guilds.feeds.subscribers.createSubscriber ) // Validate the subscriber exists for the feed in params guildFeedSubscriberAPI.use( '/:subscriberID', validator.params(subscriberIDSchema), feedHasSubscriber ) // Delete a subscriber guildFeedSubscriberAPI.delete( '/:subscriberID', controllers.api.guilds.feeds.subscribers.deleteSubscriber ) // Edit a subscriber guildFeedSubscriberAPI.patch( '/:subscriberID', validator.body(filterSchema), controllers.api.guilds.feeds.subscribers.editSubscriber ) module.exports = guildFeedSubscriberAPI
Make second signal installation test enforce Gtk.Window.type as the return type rather than GObject.TYPE_OBJECT. svn path=/trunk/; revision=408
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen\n\[object GtkWindow\] // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window.type, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING], return_type: Gtk.Window.type}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string); return new Gtk.Window()}); Seed.print(w.signal.hello.emit(2, "Weathermen"));
#!/usr/bin/env seed // Returns: 0 // STDIN: // STDOUT:2 Weathermen\n\[object GtkWindow\] // STDERR: Seed.import_namespace("GObject"); Seed.import_namespace("Gtk"); Gtk.init(null, null); HelloWindowType = { parent: Gtk.Window.type, name: "HelloWindow", class_init: function(klass, prototype) { var HelloSignalDefinition = {name: "hello", parameters: [GObject.TYPE_INT, GObject.TYPE_STRING], return_type: GObject.TYPE_OBJECT}; hello_signal_id = klass.install_signal(HelloSignalDefinition); }, } HelloWindow = new GType(HelloWindowType); w = new HelloWindow(); w.signal.hello.connect(function(object, number, string) {Seed.print(number+ " " + string); return new Gtk.Window()}); Seed.print(w.signal.hello.emit(2, "Weathermen"));