text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Delete debug injection of state in mFA
"use strict"; angular.module('arethusa.morph').directive('morphFormAttributes', [ 'morph', '$document', function(morph, $document) { return { restrict: 'A', scope: { form: '=morphFormAttributes', tokenId: '=' }, link: function(scope, element, attrs) { var id = scope.tokenId; scope.m = morph; scope.attrs = morph.sortAttributes(scope.form.attributes); scope.inv = scope.form.lexInv; scope.askForRemoval = function() { scope.confirmationRequested = true; }; scope.skipRemoval = function() { scope.confirmationRequested = false; }; scope.removeForm = function() { if (scope.form.selected) { morph.unsetState(id); } morph.removeForm(id, scope.form); }; }, templateUrl: 'templates/arethusa.morph/morph_form_attributes.html' }; } ]);
"use strict"; angular.module('arethusa.morph').directive('morphFormAttributes', [ 'morph', '$document', 'state', function(morph, $document, state) { return { restrict: 'A', scope: { form: '=morphFormAttributes', tokenId: '=' }, link: function(scope, element, attrs) { var id = scope.tokenId; scope.m = morph; scope.attrs = morph.sortAttributes(scope.form.attributes); scope.inv = scope.form.lexInv; scope.askForRemoval = function() { scope.confirmationRequested = true; }; scope.skipRemoval = function() { scope.confirmationRequested = false; }; scope.removeForm = function() { if (scope.form.selected) { morph.unsetState(id); } morph.removeForm(id, scope.form); }; }, templateUrl: 'templates/arethusa.morph/morph_form_attributes.html' }; } ]);
Include subdirectories when building the package.
from setuptools import setup, find_packages version = '0.1' setup(name='ramp', version=version, description="Rapid machine learning prototyping", long_description=open("README.md").read(), classifiers=[ 'License :: OSI Approved :: BSD License' ], keywords='machine learning data analysis statistics mining', author='Ken Van Haren', author_email='kvh@science.io', url='http://github.com/kvh/ramp', license='BSD', packages=find_packages(exclude=["*.tests"]), zip_safe=False, install_requires=[ 'numpy', 'pandas', ] )
from setuptools import setup version = '0.1' setup(name='ramp', version=version, description="Rapid machine learning prototyping", long_description=open("README.md").read(), classifiers=[ 'License :: OSI Approved :: BSD License' ], keywords='machine learning data analysis statistics mining', author='Ken Van Haren', author_email='kvh@science.io', url='http://github.com/kvh/ramp', license='BSD', packages=['ramp'], zip_safe=False, install_requires=[ 'numpy', 'pandas', ] )
Revert "pass dependencies to BacklogCore instance" This reverts commit 997a8cac8f0f3531b1931cfee9b9c64148bc16b0.
<?php use Monolog\Logger; require_once '../vendor/autoload.php'; /* set PHP config defaults */ ini_set('date.timezone', 'UTC'); /* required to set a default timezone, blame Derick Rethans */ ini_set('error_log', __DIR__ . '/../logs/php_errors.log'); ini_set('error_reporting', E_ALL); ini_set('html_errors', 0); ini_set('log_errors', 1); ini_set('user_agent', 'CVBacklogUI/2.0.0 (https://github.com/Room-11/CVBacklogUI)'); /* get application environment */ $appEnv = (isset($_SERVER['APP_ENV']) && in_array($_SERVER['APP_ENV'], ['dev', 'prod'])) ? $_SERVER['APP_ENV'] : (('127.0.0.1' === $_SERVER['REMOTE_ADDR']) ? 'dev' : 'prod'); /* default production options */ ini_set('display_errors', 0); $debug = false; $logLevel = Logger::INFO; /* development options */ if ('dev' === $appEnv) { ini_set('display_errors', 1); $debug = true; $logLevel = Logger::DEBUG; } require_once '../src/app.php';
<?php use Monolog\Logger; require_once '../vendor/autoload.php'; /* set PHP config defaults */ ini_set('date.timezone', 'UTC'); /* required to set a default timezone, blame Derick Rethans */ ini_set('error_log', __DIR__ . '/../logs/php_errors.log'); ini_set('error_reporting', E_ALL); ini_set('html_errors', 0); ini_set('log_errors', 1); /* get application environment */ $appEnv = (isset($_SERVER['APP_ENV']) && in_array($_SERVER['APP_ENV'], ['dev', 'prod'])) ? $_SERVER['APP_ENV'] : (('127.0.0.1' === $_SERVER['REMOTE_ADDR']) ? 'dev' : 'prod'); /* default production options */ ini_set('display_errors', 0); $debug = false; $logLevel = Logger::INFO; /* development options */ if ('dev' === $appEnv) { ini_set('display_errors', 1); $debug = true; $logLevel = Logger::DEBUG; } require_once '../src/app.php';
Set `mptt_indent_field` explicitly for proper MPTT list columns
from django.contrib import admin from mptt.admin import MPTTModelAdmin from mptt.forms import MPTTAdminForm from parler.admin import TranslatableAdmin from .models import Category from parler.forms import TranslatableModelForm class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm): """ Form for categories, both MPTT + translatable. """ pass class CategoryAdmin(MPTTModelAdmin, TranslatableAdmin): """ Admin page for categories. """ list_display = ('title', 'slug') mptt_indent_field = 'title' # be explicit for MPTT search_fields = ('translations__title', 'translations__slug') form = CategoryAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug', 'parent'), }), ) def get_prepopulated_fields(self, request, obj=None): # Needed for django-parler return {'slug': ('title',)} admin.site.register(Category, CategoryAdmin)
from django.contrib import admin from mptt.admin import MPTTModelAdmin from mptt.forms import MPTTAdminForm from parler.admin import TranslatableAdmin from .models import Category from parler.forms import TranslatableModelForm class CategoryAdminForm(MPTTAdminForm, TranslatableModelForm): """ Form for categories, both MPTT + translatable. """ pass class CategoryAdmin(MPTTModelAdmin, TranslatableAdmin): """ Admin page for categories. """ list_display = ('title', 'slug') search_fields = ('translations__title', 'translations__slug') form = CategoryAdminForm fieldsets = ( (None, { 'fields': ('title', 'slug', 'parent'), }), ) def get_prepopulated_fields(self, request, obj=None): # Needed for django-parler return {'slug': ('title',)} admin.site.register(Category, CategoryAdmin)
Update URL of new project
# -*- coding: utf-8 -*- #!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup __version__ = '0.4' setup( name='webstack-django-sorting', version=__version__, description="Easy sorting of tables with Django", long_description=open('README.rst').read(), author='Stéphane Raimbault', author_email='stephane.raimbault@webstack.fr', url='http://github.com/webstack/webstack-django-sorting/', packages=[ 'webstack_django_sorting', 'webstack_django_sorting.templatetags', ], package_dir={'webstack_django_sorting': 'webstack_django_sorting'}, include_package_data=True, zip_safe=False, keywords='sorting,pagination,django', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Framework :: Django', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
# -*- coding: utf-8 -*- #!/usr/bin/env python try: from setuptools import setup except ImportError: from distutils.core import setup __version__ = '0.4' setup( name='webstack-django-sorting', version=__version__, description="Easy sorting of tables with Django", long_description=open('README.rst').read(), author='Stéphane Raimbault', author_email='stephane.raimbault@webstack.fr', url='http://github.com/stephane/django-sorting/', packages=[ 'webstack_django_sorting', 'webstack_django_sorting.templatetags', ], package_dir={'webstack_django_sorting': 'webstack_django_sorting'}, include_package_data=True, zip_safe=False, keywords='sorting,pagination,django', license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Intended Audience :: Developers', 'Natural Language :: English', 'Framework :: Django', 'Environment :: Web Environment', 'Programming Language :: Python', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', ], )
Add NODE_ENV to webpack using define plugin
// start webapck const path = require('path'); const express = require('express'); const webpack = require('webpack'); const webpackMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const config = require('./webpack.config'); // create express const app = express(); // setup hot reload config.plugins = [ // define plugin for node env new webpack.DefinePlugin({ 'process.env': {NODE_ENV: JSON.stringify(process.envNODE_ENV)}, }), new webpack.HotModuleReplacementPlugin(), // setup no errors plugin new webpack.NoErrorsPlugin(), ]; // override entry for hotload config.entry = [ 'webpack-hot-middleware/client', config.entry, ]; // returns a Compiler instance const compiler = webpack(config); // stats outpu config const statsConf = { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false, }; app.use(webpackMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: 'src', stats: statsConf, })); app.use(webpackHotMiddleware(compiler)); // serve statics app.use(express.static(__dirname)); // serve index app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'index.html'))); // start server app.listen(3000, (err) => { if (err) { console.log(err); } console.info('==> Listing on port 3000'); });
// start webapck const path = require('path'); const express = require('express'); const webpack = require('webpack'); const webpackMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const config = require('./webpack.config'); // create express const app = express(); // setup hot reload config.plugins = [ new webpack.HotModuleReplacementPlugin(), // setup no errors plugin new webpack.NoErrorsPlugin(), ]; // override entry for hotload config.entry = [ 'webpack-hot-middleware/client', config.entry, ]; // returns a Compiler instance const compiler = webpack(config); // stats outpu config const statsConf = { colors: true, hash: false, timings: true, chunks: false, chunkModules: false, modules: false, }; app.use(webpackMiddleware(compiler, { publicPath: config.output.publicPath, contentBase: 'src', stats: statsConf, })); app.use(webpackHotMiddleware(compiler)); // serve statics app.use(express.static(__dirname)); // serve index app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'index.html'))); // start server app.listen(3000, (err) => { if (err) { console.log(err); } console.info('==> Listing on port 3000'); });
Fix failing unit tests for nativesequence
package nativesequence import ( "testing" "github.com/johnny-morrice/godelbrot/base" "github.com/johnny-morrice/godelbrot/nativebase" ) func TestSequence(t *testing.T) { if testing.Short() { panic("nativesequence testing impossible in short mode") } const iterateLimit = 10 app := &nativebase.MockRenderApplication{ MockRenderApplication: base.MockRenderApplication{ PictureWidth: 10, PictureHeight: 10, Base: base.BaseConfig{DivergeLimit: 4.0, IterateLimit: iterateLimit}, }, } app.PlaneMin = complex(0.0, 0.0) app.PlaneMax = complex(10.0, 10.0) numerics := Make(app) out := numerics.Sequence() const expectedCount = 100 actualCount := len(out) if expectedCount != actualCount { t.Error("Expected", expectedCount, "members but there were", actualCount) } }
package nativesequence import ( "testing" "github.com/johnny-morrice/godelbrot/base" "github.com/johnny-morrice/godelbrot/nativebase" ) func TestSequence(t *testing.T) { if testing.Short() { panic("nativesequence testing impossible in short mode") } const iterateLimit = 10 app := &nativebase.MockRenderApplication{ MockRenderApplication: base.MockRenderApplication{ PictureWidth: 10, PictureHeight: 10, Base: base.BaseConfig{DivergeLimit: 4.0, IterateLimit: iterateLimit}, }, } app.PlaneMin = complex(0.0, 0.0) app.PlaneMax = complex(10.0, 10.0) numerics := Make(app) out := numerics.Sequence() const expectedCount = 100 actualArea := numerics.Area() if expectedCount != actualArea { t.Error("Expected area of", expectedCount, "but received", actualArea) } members := make([]base.PixelMember, actualArea) i := 0 for point := range out { members[i] = point i++ } actualCount := len(members) if expectedCount != actualCount { t.Error("Expected", expectedCount, "members but there were", actualCount) } }
Store number of required array elements into constant
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; use PH7\Framework\Math\Measure\Year as YearMeasure; class UserBirthDateCore { const DEFAULT_AGE = 30; const BIRTHDATE_DELIMITER = '-'; const NUMBER_ARRAY_ELEMENTS = 3; /** * @param string $sBirthDate YYYY-MM-DD format. * * @return int */ public static function getAgeFromBirthDate($sBirthDate) { $aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate); if (self::isInvalidBirthDate($aAge)) { return self::DEFAULT_AGE; } return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get(); } private static function isInvalidBirthDate(array $aAge) { return count($aAge) < self::NUMBER_ARRAY_ELEMENTS; } }
<?php /** * @author Pierre-Henry Soria <hello@ph7cms.com> * @copyright (c) 2018, Pierre-Henry Soria. All Rights Reserved. * @license GNU General Public License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory. * @package PH7 / App / System / Core / Class */ namespace PH7; use PH7\Framework\Math\Measure\Year as YearMeasure; class UserBirthDateCore { const DEFAULT_AGE = 30; const BIRTHDATE_DELIMITER = '-'; /** * @param string $sBirthDate YYYY-MM-DD format. * * @return int */ public static function getAgeFromBirthDate($sBirthDate) { $aAge = explode(self::BIRTHDATE_DELIMITER, $sBirthDate); if (self::isInvalidBirthDate($aAge)) { return self::DEFAULT_AGE; } return (new YearMeasure($aAge[0], $aAge[1], $aAge[2]))->get(); } private static function isInvalidBirthDate(array $aAge) { return count($aAge) < 3; } }
Add login method to PostIt class
import { connection, UserModel, GroupModel } from './models'; /** * The User class * @author Babatunde Adeyemi <tundewrites@gmail.com> * @class */ class PostIt { /** * Initializes the database connection * Initializes the database models * @constructor */ constructor() { this.UserModel = UserModel; this.GroupModel = GroupModel; } /** * Registers new user's info to database * @param {string} firstName - User's first name * @param {string} lastName - User's last name * @param {string} email - User's email * @param {string} phone - User's phone * @param {string} password - User's password * @returns {Promise} - returns a Bluebird JS Promise */ registerUser(firstName, lastName, email, phone, password) { return connection.sync().then(() => this.UserModel.create({ firstName, lastName, email, phone, password }) ); } /** * Fetches user's details * @param {string} email - Signin email address * @param {*} password - Signin password * @returns {promise} - returns a Bluebird JS Promise */ logUserIn(email) { return this.UserModel.findOne({ where: { email } }); } } export default PostIt;
import { connection, UserModel, GroupModel } from './models'; /** * The User class * @author Babatunde Adeyemi <tundewrites@gmail.com> * @class */ class PostIt { /** * Initializes the database connection * Initializes the database models * @constructor */ constructor() { this.UserModel = UserModel; this.GroupModel = GroupModel; } /** * Registers new user's info to database * @param {string} firstName - User's first name * @param {string} lastName - User's last name * @param {string} email - User's email * @param {string} phone - User's phone * @param {string} password - User's password * @returns {Promise} - returns a Bluebird JS Promise */ registerUser(firstName, lastName, email, phone, password) { return connection.sync().then(() => this.UserModel.create({ firstName, lastName, email, phone, password }) ); } } export default PostIt;
Fix `unsafeReadProtoTagged` so it works in IE
"use strict"; exports._unsafeReadProtoTagged = (function () { var tagOf = function (value) { return Object.prototype.toString.call(value).slice(8, -1); }; return function (name) { return function (failure) { return function (success) { return function (value) { var obj = value; while (obj != null) { var proto = Object.getPrototypeOf(obj); var ctor = tagOf(proto); if (ctor === name) { return success(value); } else if (ctor === "Object") { return failure(tagOf(value)); } obj = proto; } return failure(tagOf(value)); }; }; }; }; }());
"use strict"; exports._unsafeReadProtoTagged = function (name) { return function (failure) { return function (success) { return function (value) { var obj = value; while (obj != null) { var proto = Object.getPrototypeOf(obj); var ctor = proto.constructor.name; if (ctor === name) { return success(value); } else if (ctor === "Object") { return failure(Object.getPrototypeOf(value).constructor.name); } obj = proto; } return failure(Object.getPrototypeOf(value).constructor.name); }; }; }; };
Add JavaDoc and remove warnings.
package org.oblodiff.token; import org.oblodiff.token.api.Token; /** * The basic implementation of a {@link Token}, contains code that all {@link Token}s share. * * @param <T> the type of the content this token represents * @author Christian Rösch &lt;christianroesch@gmx.net&gt; */ public abstract class BasicToken<T> implements Token { /** * the representation of the value/content of this token. */ private final T content; /** * @param ct the content this token represents. * @see #getContent() for further details */ public BasicToken(final T ct) { super(); content = ct; } @Override public final int hashCode() { return content.hashCode(); } @Override public final boolean equals(Object obj) { return obj instanceof BasicToken && content.equals(((BasicToken) obj).content); } /** * @return the content of this token. The content is used for generating the hash of this token. */ protected T getContent() { return content; } @Override public String toString() { return super.toString() + " >" + content + "<"; } }
package org.oblodiff.token; import org.oblodiff.token.api.Token; /** * The basic implementation of a {@link Token}, contains code that all {@link Token}s share. * * @param <T> the type of the content this token represents * @author Christian Rösch &lt;christianroesch@gmx.net&gt; */ public abstract class BasicToken<T extends Object> implements Token { /** * the representation of the value/content of this token. */ private final T content; public BasicToken(final T ct) { super(); content = ct; } @Override public final int hashCode() { return content.hashCode(); } @Override public final boolean equals(Object obj) { if (!(obj instanceof BasicToken)) { return false; } return content.equals(((BasicToken) obj).content); } protected T getContent() { return content; } @Override public String toString() { return super.toString() + " >" + content + "<"; } }
Make sure not to commit non-compiling code
import pandas as pd import os.path TEMPERATURES_FILE = 'data/USCityTemperaturesAfter1850.csv' CITY_STATE_FILE = 'data/city_state.csv' def load_data(path='data/GlobalLandTemperaturesbyCity.csv', ignore_before=1850): out = pd.read_csv(path, header=0) us = out.loc[out['Country'] == 'United States'] us = us.loc[us['dt'] > 1850] us.to_csv(TEMPERATURES_FILE) return us def city_country(raw_file='data/RawUSData.csv'): out = pd.read_csv(raw_file) keep = ['Name', 'Canonical Name'] us = out[keep] us = us.assign(State = us['Canonical Name'].apply(get_state)) us = us.rename(columns={'Name':'City'}) us = us[['City', 'State']] us.to_csv(CITY_STATE_FILE) def get_state(raw_string): return raw_string.split(',')[-2] def main(): if not os.path.isfile(TEMPERATURES_FILE): # TODO: add force make file load_data() data = pd.read_csv(TEMPERATURES_FILE) if not os.path.isfile(CITY_STATE_FILE): city_country() cities = pd.read_csv(CITY_STATE_FILE) if __name__ == "__main__": main()
import pandas as pd import os.path TEMPERATURES_FILE = 'data/USCityTemperaturesAfter1850.csv' CITY_STATE_FILE = 'data/city_state.csv' def load_data(path='data/GlobalLandTemperaturesbyCity.csv', ignore_before=1850): out = pd.read_csv(path, header=0) us = out.loc[out['Country'] == 'United States'] us = us.loc[us['dt'] > 1850] us.to_csv(TEMPERATURES_FILE) return us def city_country(raw_file='data/RawUSData.csv'): out = pd.read_csv(raw_file) keep = ['Name', 'Canonical Name'] us = out[keep] us = us.assign(State = us['Canonical Name'].apply(get_state)) us = us.rename(columns={'Name':'City'}) us = us[['City', 'State']] us.to_csv(CITY_STATE_FILE) def get_state(raw_string): return raw_string.split(',')[-2] def main(): if not os.path.isfile(TEMPERATURES_FILE): # TODO: add force make file load_data() data = pd.read_csv(TEMPERATURES_FILE) city_country() if __name__ == "__main__": main()
Add a convenience method to get the player ship
from . import packet as p class Tracker: def __init__(self): self.objects = {} @property def player_ship(self): for _obj in self.objects.values(): if _obj['type'] == p.ObjectType.player_vessel: return _obj return {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
from . import packet as p class Tracker: def __init__(self): self.objects = {} def update_object(self, record): try: oid = record['object'] except KeyError: return else: self.objects.setdefault(oid, {}).update(record) def remove_object(self, oid): try: del self.objects[oid] except KeyError: pass def rx(self, packet): if isinstance(packet, p.ObjectUpdatePacket): for record in packet.records: self.update_object(record) elif isinstance(packet, p.DestroyObjectPacket): self.remove_object(packet.object)
Change module version from 2.0.0.1 to 2.2 Change the module version for release. The module version strategy has been changed to conform with the new Omise plugin version strategy. The previous version is 2.0.0.1 that implied to be version 2.1. So, the new version will be 2.2.
<?php require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php'; // Define version of Omise-OpenCart if (!defined('OMISE_OPENCART_VERSION')) define('OMISE_OPENCART_VERSION', '2.2'); // Just mockup $datetime = new DateTime('now'); $datetime->format('Y-m-d\TH:i:s\Z'); if (!defined('OMISE_OPENCART_RELEASED_DATE')) define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z')); $opencart_version = defined('VERSION') ? " OpenCart/".VERSION : ""; // Define 'OMISE_USER_AGENT_SUFFIX' if (!defined('OMISE_USER_AGENT_SUFFIX')) define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version); // Define 'OMISE_API_VERSION' if(!defined('OMISE_API_VERSION')) define('OMISE_API_VERSION', '2014-07-27'); ?>
<?php require_once dirname(__FILE__).'/omise-plugin/helpers/charge.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/currency.php'; require_once dirname(__FILE__).'/omise-plugin/helpers/transfer.php'; // Define version of Omise-OpenCart if (!defined('OMISE_OPENCART_VERSION')) define('OMISE_OPENCART_VERSION', '2.0.0.1'); // Just mockup $datetime = new DateTime('now'); $datetime->format('Y-m-d\TH:i:s\Z'); if (!defined('OMISE_OPENCART_RELEASED_DATE')) define('OMISE_OPENCART_RELEASED_DATE', $datetime->format('Y-m-d\TH:i:s\Z')); $opencart_version = defined('VERSION') ? " OpenCart/".VERSION : ""; // Define 'OMISE_USER_AGENT_SUFFIX' if (!defined('OMISE_USER_AGENT_SUFFIX')) define('OMISE_USER_AGENT_SUFFIX', "OmiseOpenCart/".OMISE_OPENCART_VERSION.$opencart_version); // Define 'OMISE_API_VERSION' if(!defined('OMISE_API_VERSION')) define('OMISE_API_VERSION', '2014-07-27'); ?>
Change reset FA icon for fa-chain-broken
<?php /** * Main layout. * * @package PTTRC * @subpackage views */ ?> <!DOCTYPE html> <html> <head> <title><?php echo htmlspecialchars( $title ); ?></title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i" rel="stylesheet"> <link rel="stylesheet" href="css/style.css" /> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://use.fontawesome.com/a4c255239f.js"></script> <script src="js/scripts.js"></script> </head> <body class="<?php echo $class; ?>"> <div class="container"> <!--<h1>Timers</h1>--> <?php if ( $error ) : ?> <div class="warn"><?php echo $error; ?></div> <?php endif; ?> <?php echo $content; ?> <?php global $step; if ( $step !== 'reset' ) : ?> <a class="reset-link" href="?step=reset" title="Reset"> <span class="fa fa-chain-broken"></span> </a> <?php endif; ?> </div> </body> </html>
<?php /** * Main layout. * * @package PTTRC * @subpackage views */ ?> <!DOCTYPE html> <html> <head> <title><?php echo htmlspecialchars( $title ); ?></title> <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i" rel="stylesheet"> <link rel="stylesheet" href="css/style.css" /> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://use.fontawesome.com/a4c255239f.js"></script> <script src="js/scripts.js"></script> </head> <body class="<?php echo $class; ?>"> <div class="container"> <!--<h1>Timers</h1>--> <?php if ( $error ) : ?> <div class="warn"><?php echo $error; ?></div> <?php endif; ?> <?php echo $content; ?> <?php global $step; if ( $step !== 'reset' ) : ?> <a class="reset-link" href="?step=reset" title="Reset"> <span class="fa fa-refresh"></span> </a> <?php endif; ?> </div> </body> </html>
chore(examples): Check for request data prior to setting user If outside of request scope (or the process domain is otherwise null, then skip setting request data)
const bugsnag = require("./bugsnag"); function attemptLogin(username, password) { return new Promise((resolve, reject) => { if (username === "crash") { // Obviously you wouldn't expect to see this in your production app, but here is an example of what // you might have underlying your database abstraction. reject(new Error(`Unable to connect to database`)); } else { if (username === password) { resolve({ id: 1, name: username, }); } else { resolve(null); } } }); } function loadSession(req, res, next) { // We may not always be reporting errors manually. What happens if there's an error we didn't anticipate? // In that case we can attach some user data to the request, so we know which user was affected by the error. if (bugsnag.requestData) { bugsnag.requestData.user = { id: 1, name: "james", plan: "beast-mode", }; } next(null); } module.exports = { attemptLogin, loadSession, };
const bugsnag = require("./bugsnag"); function attemptLogin(username, password) { return new Promise((resolve, reject) => { if (username === "crash") { // Obviously you wouldn't expect to see this in your production app, but here is an example of what // you might have underlying your database abstraction. reject(new Error(`Unable to connect to database`)); } else { if (username === password) { resolve({ id: 1, name: username, }); } else { resolve(null); } } }); } function loadSession(req, res, next) { // We may not always be reporting errors manually. What happens if there's an error we didn't anticipate? // In that case we can attach some user data to the request, so we know which user was affected by the error. bugsnag.requestData.user = { id: 1, name: "james", plan: "beast-mode", }; next(null); } module.exports = { attemptLogin, loadSession, };
Add Satoumi as a classification.
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (7, 'supergroup', 'Supergroup'), ('Special Units', [ (3, 'shuffle', 'Shuffle Unit'), (6, 'revival', 'Revival Unit'), (8, 'satoyama', 'Satoyama Unit'), (9, 'satoumi', 'Satoumi Unit'), ]), (OTHER, 'other', 'Other') ) PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
from model_utils import Choices from ohashi.constants import OTHER BLOOD_TYPE = Choices('A', 'B', 'O', 'AB') CLASSIFICATIONS = Choices( (1, 'major', 'Major Unit'), (2, 'minor', 'Minor Unit'), (4, 'temporary', 'Temporary Unit'), (5, 'subunit', 'Sub-Unit'), (7, 'supergroup', 'Supergroup'), ('Special Units', [ (3, 'shuffle', 'Shuffle Unit'), (6, 'revival', 'Revival Unit'), (8, 'satoyama', 'Satoyama Unit'), ]), (OTHER, 'other', 'Other') ) PHOTO_SOURCES = Choices( (1, 'promotional', 'Promotional Photo'), (2, 'blog', 'Blog Photo'), (OTHER, 'other', 'Other') ) SCOPE = Choices( (1, 'hp', 'Hello! Project'), (2, 'ufa', 'Up Front Agency'), (OTHER, 'other', 'Other') ) STATUS = Choices( (1, 'active', 'Active'), (2, 'former', 'Former'), (OTHER, 'other', 'Other') )
Set a KEY_PREFIX for the Redis cache, so that we don't get collisions when running multiple sites on one server
from .base import * DEBUG = False WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch.ElasticSearch', 'INDEX': 'wagtaildemo' } } INSTALLED_APPS+= ( 'djcelery', 'kombu.transport.django', 'gunicorn', ) CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': '127.0.0.1:6379', 'KEY_PREFIX': 'wagtaildemo', 'OPTIONS': { 'CLIENT_CLASS': 'redis_cache.client.DefaultClient', } } } # CELERY SETTINGS import djcelery djcelery.setup_loader() BROKER_URL = 'redis://' CELERY_SEND_TASK_ERROR_EMAILS = True CELERYD_LOG_COLOR = False try: from .local import * except ImportError: pass
from .base import * DEBUG = False WAGTAILSEARCH_BACKENDS = { 'default': { 'BACKEND': 'wagtail.wagtailsearch.backends.elasticsearch.ElasticSearch', 'INDEX': 'wagtaildemo' } } INSTALLED_APPS+= ( 'djcelery', 'kombu.transport.django', 'gunicorn', ) CACHES = { 'default': { 'BACKEND': 'redis_cache.cache.RedisCache', 'LOCATION': '127.0.0.1:6379', 'OPTIONS': { 'CLIENT_CLASS': 'redis_cache.client.DefaultClient', } } } # CELERY SETTINGS import djcelery djcelery.setup_loader() BROKER_URL = 'redis://' CELERY_SEND_TASK_ERROR_EMAILS = True CELERYD_LOG_COLOR = False try: from .local import * except ImportError: pass
Add debug logging to stats transform.
import Transform from './Transform'; import Stats from '../server/Stats'; export default class StatsTransform extends Transform { constructor(opts, config, logger) { super(opts, config, logger); this._stats = new Stats(config, logger); this._type = this.getOption('type', 'increment'); this._name = this.getOption('name'); this._value = this.getOption('value', '1'); } close() { this._stats.close(); } process(event) { try { const value = parseInt(this._value.render(event), 10); const type = this._type.render(event); const name = this._name.render(event); switch (type) { case 'increment': this._logger.debug('Sending stats increment.', {name, value}); this._stats.increment(name, value); break; case 'gauge': this._logger.debug('Sending stats guage.', {name, value}); this._stats.gauge(name, value); break; } return this.emit(null); } catch (e) { return this.fail(e); } } }
import Transform from './Transform'; import Stats from '../server/Stats'; export default class StatsTransform extends Transform { constructor(opts, config, logger) { super(opts, config, logger); this._stats = new Stats(config, logger); this._type = this.getOption('type', 'increment'); this._name = this.getOption('name'); this._value = this.getOption('value', '1'); } close() { this._stats.close(); } process(event) { try { const value = parseInt(this._value.render(event), 10); const type = this._type.render(event); const name = this._name.render(event); switch (type) { case 'increment': this._stats.increment(name, value); break; case 'gauge': this._stats.gauge(name, value); break; } return this.emit(null); } catch (e) { return this.fail(e); } } }
Fix weird error messages about play() and pause()
const helper = require('./helper') let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = [...Array(5)].map((_, i) => new Audio(`./data/capture${i}.mp3`)) let pachiSounds = [...Array(5)].map((_, i) => new Audio(`./data/${i}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play().catch(helper.noop), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play().catch(helper.noop), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play().catch(helper.noop), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play().catch(helper.noop), delay) }
let lastPachiIndex = -1 let lastCaptureIndex = -1 let captureSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/capture${x}.mp3`)) let pachiSounds = Object.keys(new Int8Array(5)).map(x => new Audio(`./data/${x}.mp3`)) let newGameSound = new Audio('./data/newgame.mp3') let passSound = new Audio('./data/pass.mp3') exports.playPachi = function(delay = 0) { let index = lastPachiIndex while (index === lastPachiIndex) { index = Math.floor(Math.random() * pachiSounds.length) } lastPachiIndex = index setTimeout(() => pachiSounds[index].play(), delay) } exports.playCapture = function(delay = 0) { let index = lastCaptureIndex while (index === lastCaptureIndex) { index = Math.floor(Math.random() * captureSounds.length) } lastCaptureIndex = index setTimeout(() => captureSounds[index].play(), delay) } exports.playPass = function(delay = 0) { setTimeout(() => passSound.play(), delay) } exports.playNewGame = function(delay = 0) { setTimeout(() => newGameSound.play(), delay) }
Refactor to use the _read method
var util = require('util') , stream = require('stream') var isstream = require('isstream') util.inherits(BulkStream, stream.Readable) module.exports = BulkStream function BulkStream () { stream.Readable.call(this) var self = this self._items = [] self._streams = [] self._index = 0 } BulkStream.prototype.append = function (item) { var self = this if (isstream(item)) { item.pause() self._streams.push(item) } self._items.push(item) } BulkStream.prototype._read = function (n) { var self = this if (self._index === self._items.length) { // process.nextTick(function () { // self.push(null) // }) return } var item = self._items[self._index] if (item._reading) { return } if (isstream(item)) { item._reading = true item.on('readable', function () { var chunk = item.read() if (chunk === null) { self._index++ self._read() } else { self.push(chunk) } }) } else { self._index++ self.push(item) } }
var util = require('util') , stream = require('stream') var isstream = require('isstream') util.inherits(BulkStream, stream.Readable) module.exports = BulkStream function BulkStream () { stream.Readable.call(this) var self = this self._items = [] process.nextTick(function () { self.start() }) } BulkStream.prototype.append = function (item) { if (isstream(item)) { item.pause() } this._items.push(item) } BulkStream.prototype.start = function () { var self = this var read = function (index) { if (index === self._items.length) { process.nextTick(function () { self.push(null) }) return } var item = self._items[index] if (isstream(item)) { item.on('data', function (chunk) { self.push(chunk) }) item.on('end', function () { read(++index) }) item.resume() } else { self.push(item) read(++index) } } read(0) } BulkStream.prototype._read = function (n) {}
Use ruby style instance variables in UnboundMethod
<?php namespace Phuby; class UnboundMethod extends Object { static function initialized($self) { $self->attr_reader('name'); } function initialize($owner, $name, $block) { $this->{'@owner'} = $owner; $this->{'@name'} = $name; $this->{'@block'} = $block; } function bind($receiver) { return new Method($this, $receiver); } function inspect() { return '<'.get_called_class().': '.$this->{'@owner'}.'#'.$this->{'@name'}.'>'; } function name() { return $this->{'@name'}; } function owner() { return Module::const_get($this->{'@owner'}); } function to_proc() { return $this->{'@block'}; } }
<?php namespace Phuby; class UnboundMethod extends Object { protected $owner; protected $name; protected $block; function initialize($owner, $name, $block) { $this->owner = $owner; $this->name = $name; $this->block = $block; } function bind($receiver) { return new Method($this, $receiver); } function inspect() { return '<'.get_called_class().": $this->owner#$this->name>"; } function name() { return $this->name; } function owner() { return Module::const_get($this->owner); } function to_proc() { return $this->block; } }
Set maxAge of two hours on session cookie
const express = require('express'); const cors = require('cors'); const session = require('express-session'); const bodyParser = require('body-parser'); const authMiddleware = require('./authMiddleware'); const auth = require('./controllers/auth'); const documents = require('./controllers/documents'); const deadlines = require('./controllers/deadlines'); const app = express(); const PORT_NUMBER = 8081; const SESSION = { secret: 'goodbirbs', cookie: { secure: false, maxAge: (1000 * 60 * 60 * 2) // two hours }, saveUninitialized: true, resave: true }; const CORS_CONFIG = { credentials: true, origin: 'http://localhost:3000' }; // Middleware app.use(session(SESSION)); app.use(bodyParser.json()); app.use(authMiddleware); // Routes app.use('/auth', cors(CORS_CONFIG), auth); app.use('/documents', cors(CORS_CONFIG), documents); app.use('/deadlines', cors(CORS_CONFIG), deadlines); const server = app.listen(PORT_NUMBER, () => { const { port } = server.address(); console.log(`Marketplace Managed API listening to port ${port}`); }); module.exports = server;
const express = require('express'); const cors = require('cors'); const session = require('express-session'); const bodyParser = require('body-parser'); const authMiddleware = require('./authMiddleware'); const auth = require('./controllers/auth'); const documents = require('./controllers/documents'); const deadlines = require('./controllers/deadlines'); const app = express(); const PORT_NUMBER = 8081; const SESSION = { secret: 'goodbirbs', cookie: { secure: false }, saveUninitialized: true, resave: true }; const CORS_CONFIG = { credentials: true, origin: 'http://localhost:3000' }; // Middleware app.use(session(SESSION)); app.use(bodyParser.json()); app.use(authMiddleware); // Routes app.use('/auth', cors(CORS_CONFIG), auth); app.use('/documents', cors(CORS_CONFIG), documents); app.use('/deadlines', cors(CORS_CONFIG), deadlines); const server = app.listen(PORT_NUMBER, () => { const { port } = server.address(); console.log(`Marketplace Managed API listening to port ${port}`); }); module.exports = server;
Set separate game mode permissions default to true. I meant to do this ages ago.
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.admin.config; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class AdminConfig { @Setting(value = "broadcast-message-template", comment = "config.broadcast.template") private BroadcastConfig broadcastMessage = new BroadcastConfig(); @Setting(value = "separate-gamemode-permissions", comment = "config.gamemode.separate") private boolean separateGamemodePermission = true; public BroadcastConfig getBroadcastMessage() { return broadcastMessage; } public boolean isSeparateGamemodePermission() { return separateGamemodePermission; } }
/* * This file is part of Nucleus, licensed under the MIT License (MIT). See the LICENSE.txt file * at the root of this project for more details. */ package io.github.nucleuspowered.nucleus.modules.admin.config; import ninja.leaping.configurate.objectmapping.Setting; import ninja.leaping.configurate.objectmapping.serialize.ConfigSerializable; @ConfigSerializable public class AdminConfig { @Setting(value = "broadcast-message-template", comment = "config.broadcast.template") private BroadcastConfig broadcastMessage = new BroadcastConfig(); // TODO: Make the default true in future versions? @Setting(value = "separate-gamemode-permissions", comment = "config.gamemode.separate") private boolean separateGamemodePermission = false; public BroadcastConfig getBroadcastMessage() { return broadcastMessage; } public boolean isSeparateGamemodePermission() { return separateGamemodePermission; } }
Change download and documentation URLs.
#!/usr/bin/env python # coding: utf-8 from distribute_setup import use_setuptools use_setuptools() try: from setuptools import setup except ImportError: from distutils.core import setup import sys extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup(name='mockito', version='0.3.0', packages=['mockito', 'mockito_test', 'mockito_util'], url='http://code.google.com/p/mockito-python', download_url='http://code.google.com/p/mockito-python/downloads/list', maintainer='Mockito Maintainers', maintainer_email='mockito-python@googlegroups.com', license='MIT', description='Spying framework', long_description='Mockito is a spying framework based on Java library with the same name.', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Testing', 'Programming Language :: Python :: 3' ], test_loader = 'mockito_util.test:TestLoader', test_suite = 'mockito_test', **extra )
#!/usr/bin/env python # coding: utf-8 from distribute_setup import use_setuptools use_setuptools() try: from setuptools import setup except ImportError: from distutils.core import setup import sys extra = {} if sys.version_info >= (3,): extra['use_2to3'] = True setup(name='mockito', version='0.3.0', packages=['mockito', 'mockito_test', 'mockito_util'], url='http://code.google.com/p/mockito/wiki/MockitoForPython', download_url='http://bitbucket.org/szczepiq/mockito-python/downloads/', maintainer='mockito maintainers', maintainer_email='mockito-python@googlegroups.com', license='MIT', description='Spying framework', long_description='Mockito is a spying framework based on Java library with the same name.', classifiers=['Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Topic :: Software Development :: Testing', 'Programming Language :: Python :: 3' ], test_loader = 'mockito_util.test:TestLoader', test_suite = 'mockito_test', **extra )
Make duplicate match filter less likely to produce false positives
package won.matcher.service.nodemanager.service; import com.google.common.base.Charsets; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnels; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import won.matcher.service.common.event.HintEvent; /** * Created by hfriedrich on 06.07.2016. * * Currently the hint "database" is just implemented as an in memory bloom filter so that (best guess) duplicate * checks are possible to avoid sending duplicate hints. In a future version this might be changed to a persistent * hint database. */ @Component @Scope("singleton") public class HintDBService { private BloomFilter savedHints; public HintDBService() { savedHints = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 100000000, 0.001); } public void saveHint(HintEvent hint) { savedHints.put(getHintIdentificationString(hint)); } public boolean mightHintSaved(HintEvent hint) { return savedHints.mightContain(getHintIdentificationString(hint)); } private String getHintIdentificationString(HintEvent hint) { return hint.getFromNeedUri() + hint.getFromWonNodeUri() + hint.getToNeedUri() + hint.getToWonNodeUri(); } }
package won.matcher.service.nodemanager.service; import com.google.common.base.Charsets; import com.google.common.hash.BloomFilter; import com.google.common.hash.Funnels; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import won.matcher.service.common.event.HintEvent; /** * Created by hfriedrich on 06.07.2016. * * Currently the hint "database" is just implemented as an in memory bloom filter so that (best guess) duplicate * checks are possible to avoid sending duplicate hints. In a future version this might be changed to a persistent * hint database. */ @Component @Scope("singleton") public class HintDBService { private BloomFilter savedHints; public HintDBService() { savedHints = BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 100000, 0.001); } public void saveHint(HintEvent hint) { savedHints.put(getHintIdentificationString(hint)); } public boolean mightHintSaved(HintEvent hint) { return savedHints.mightContain(getHintIdentificationString(hint)); } private String getHintIdentificationString(HintEvent hint) { return hint.getFromNeedUri() + hint.getFromWonNodeUri() + hint.getToNeedUri() + hint.getToWonNodeUri(); } }
Check if a key exists in an array, so it doesn't raise an error
<?php include_once('phpviddler.php'); class Php5viddler extends Phpviddler { function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) { $result = parent::sendRequest($method, $args, $postmethod); if($tryagain && is_null($result)) { $result = parent::sendRequest($method, $args, $postmethod, false); } elseif(is_null($result)) { throw new ViddlerException("No response", $method, 8888, 'n/a'); } if(is_array($result) && isset($result['error'])) { throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']); } return $result; } } class ViddlerException extends Exception { var $details; var $method; public function __construct($message, $method, $code=0, $details='') { $this->details = $details; $this->method = $method; parent::__construct($message, $code); } public function getDetails() { return $this->details; } public function __toString() { return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n"; } } ?>
<?php include_once('phpviddler.php'); class Php5viddler extends Phpviddler { function sendRequest($method=null,$args=null,$postmethod='get',$tryagain=true) { $result = parent::sendRequest($method, $args, $postmethod); if($tryagain && is_null($result)) { $result = parent::sendRequest($method, $args, $postmethod, false); } elseif(is_null($result)) { throw new ViddlerException("No response", $method, 8888, 'n/a'); } if(is_array($result) && $result['error']) { throw new ViddlerException($result['error']['description'], $method, $result['error']['code'], $result['error']['details']); } return $result; } } class ViddlerException extends Exception { var $details; var $method; public function __construct($message, $method, $code=0, $details='') { $this->details = $details; $this->method = $method; parent::__construct($message, $code); } public function getDetails() { return $this->details; } public function __toString() { return "{$this->method} exception [{$this->code}]: {$this->getMessage()} ({$this->details})\n"; } } ?>
Expand technology section for plot to nearest by default.
<?php $template->assign('PageTopic','Plot A Course'); require_once(get_file_loc('menue.inc')); create_nav_menue($template,$player); $container=array(); $container['url'] = 'course_plot_processing.php'; $container['body'] = ''; $template->assign('PlotCourseFormLink',SmrSession::get_new_href($container)); $container['url'] = 'course_plot_nearest_processing.php'; $template->assign('PlotNearestFormLink',SmrSession::get_new_href($container)); if ($ship->hasJump()) { $container=create_container('sector_jump_processing.php',''); $container['target_page'] = 'current_sector.php'; $template->assign('JumpDriveFormLink',SmrSession::get_new_href($container)); } if(isset($_REQUEST['xtype'])) SmrSession::updateVar('XType',$_REQUEST['xtype']); else if(!isset($var['XType'])) SmrSession::updateVar('XType','Technology'); $template->assign('XType',$var['XType']); $template->assign('AllXTypes',array('Technology','Ships','Weapons','Locations','Goods')); ?>
<?php $template->assign('PageTopic','Plot A Course'); require_once(get_file_loc('menue.inc')); create_nav_menue($template,$player); $container=array(); $container['url'] = 'course_plot_processing.php'; $container['body'] = ''; $template->assign('PlotCourseFormLink',SmrSession::get_new_href($container)); $container['url'] = 'course_plot_nearest_processing.php'; $template->assign('PlotNearestFormLink',SmrSession::get_new_href($container)); if ($ship->hasJump()) { $container=create_container('sector_jump_processing.php',''); $container['target_page'] = 'current_sector.php'; $template->assign('JumpDriveFormLink',SmrSession::get_new_href($container)); } if(isset($_REQUEST['xtype'])) $template->assign('XType',$_REQUEST['xtype']); $template->assign('AllXTypes',array('Technology','Ships','Weapons','Locations','Goods')); ?>
Load User model from compatibility layer
from django.test import TestCase from django.contrib.auth import authenticate from django.core import mail from oscar.core.compat import get_user_model User = get_user_model() class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase): def test_authenticates_when_passwords_are_different(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password=username) user = authenticate(username=email, password='user1') self.assertTrue(user is not None) def test_rejects_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') user = authenticate(username=email, password='password') self.assertTrue(user is None) def test_mails_admins_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') authenticate(username=email, password='password') self.assertEqual(1, len(mail.outbox))
from django.test import TestCase from django.contrib.auth import authenticate, get_user_model from django.core import mail User = get_user_model() class TestEmailAuthBackendWhenUsersShareAnEmail(TestCase): def test_authenticates_when_passwords_are_different(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password=username) user = authenticate(username=email, password='user1') self.assertTrue(user is not None) def test_rejects_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') user = authenticate(username=email, password='password') self.assertTrue(user is None) def test_mails_admins_when_passwords_match(self): # Create two users with the same email address email = 'person@example.com' for username in ['user1', 'user2']: User.objects.create_user(username, email, password='password') authenticate(username=email, password='password') self.assertEqual(1, len(mail.outbox))
Increment version now we connect to prod by default
from setuptools import setup, find_packages requires = [ 'amaasutils', 'configparser', 'python-dateutil', 'pytz', 'requests', 'warrant' ] setup( name='amaascore', version='0.4.0', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
from setuptools import setup, find_packages requires = [ 'amaasutils', 'configparser', 'python-dateutil', 'pytz', 'requests', 'warrant' ] setup( name='amaascore', version='0.3.6', description='Asset Management as a Service - Core SDK', license='Apache License 2.0', url='https://github.com/amaas-fintech/amaas-core-sdk-python', author='AMaaS', author_email='tech@amaas.com', classifiers=[ 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: Python :: 3.6', ], packages=find_packages(exclude=['tests']), # Very annoying that this doesnt work - I have to include a MANIFEST install_requires=requires, )
[local-sync] Update DeleteSentMessage task for ordering
const SyncbackTask = require('./syncback-task') class DeleteSentMessageGMAIL extends SyncbackTask { description() { return `DeleteSentMessage`; } affectsImapMessageUIDs() { return true } async run(db, imap) { const {messageId} = this.syncbackRequestObject().props const trash = await db.Folder.find({where: {role: 'trash'}}); if (!trash) { throw new Error(`Could not find folder with role 'trash'.`) } const allMail = await db.Folder.find({where: {role: 'all'}}); if (!allMail) { throw new Error(`Could not find folder with role 'all'.`) } // Move the message from all mail to trash and then delete it from there const steps = [ {folder: allMail, deleteFn: (box, uid) => box.moveFromBox(uid, trash.name)}, {folder: trash, deleteFn: (box, uid) => box.addFlags(uid, 'DELETED')}, ] for (const {folder, deleteFn} of steps) { const box = await imap.openBox(folder.name); const uids = await box.search([['HEADER', 'Message-ID', messageId]]) for (const uid of uids) { await deleteFn(box, uid); } box.closeBox(); } } } module.exports = DeleteSentMessageGMAIL;
const SyncbackTask = require('./syncback-task') class DeleteSentMessageGMAIL extends SyncbackTask { description() { return `DeleteSentMessage`; } async run(db, imap) { const {messageId} = this.syncbackRequestObject().props const trash = await db.Folder.find({where: {role: 'trash'}}); if (!trash) { throw new Error(`Could not find folder with role 'trash'.`) } const allMail = await db.Folder.find({where: {role: 'all'}}); if (!allMail) { throw new Error(`Could not find folder with role 'all'.`) } // Move the message from all mail to trash and then delete it from there const steps = [ {folder: allMail, deleteFn: (box, uid) => box.moveFromBox(uid, trash.name)}, {folder: trash, deleteFn: (box, uid) => box.addFlags(uid, 'DELETED')}, ] for (const {folder, deleteFn} of steps) { const box = await imap.openBox(folder.name); const uids = await box.search([['HEADER', 'Message-ID', messageId]]) for (const uid of uids) { await deleteFn(box, uid); } box.closeBox(); } } } module.exports = DeleteSentMessageGMAIL;
Add reference to the new functions' container to our `window.wmf` object.
var wmf = {} wmf.editButtons = require('./js/transforms/addEditButtons') wmf.compatibility = require('wikimedia-page-library').CompatibilityTransform wmf.elementLocation = require('./js/elementLocation') wmf.utilities = require('./js/utilities') wmf.findInPage = require('./js/findInPage') wmf.footerReadMore = require('wikimedia-page-library').FooterReadMore wmf.footerMenu = require('wikimedia-page-library').FooterMenu wmf.footerLegal = require('wikimedia-page-library').FooterLegal wmf.footerContainer = require('wikimedia-page-library').FooterContainer wmf.filePages = require('./js/transforms/disableFilePageEdit') wmf.imageDimming = require('wikimedia-page-library').DimImagesTransform wmf.tables = require('./js/transforms/collapseTables') wmf.themes = require('wikimedia-page-library').ThemeTransform wmf.redLinks = require('wikimedia-page-library').RedLinks wmf.paragraphs = require('./js/transforms/relocateFirstParagraph') wmf.images = require('./js/transforms/widenImages') wmf.platform = require('wikimedia-page-library').PlatformTransform wmf.viewport = require('./js/viewport') window.wmf = wmf
var wmf = {} wmf.editButtons = require('./js/transforms/addEditButtons') wmf.compatibility = require('wikimedia-page-library').CompatibilityTransform wmf.elementLocation = require('./js/elementLocation') wmf.utilities = require('./js/utilities') wmf.findInPage = require('./js/findInPage') wmf.footerReadMore = require('wikimedia-page-library').FooterReadMore wmf.footerMenu = require('wikimedia-page-library').FooterMenu wmf.footerLegal = require('wikimedia-page-library').FooterLegal wmf.footerContainer = require('wikimedia-page-library').FooterContainer wmf.filePages = require('./js/transforms/disableFilePageEdit') wmf.imageDimming = require('wikimedia-page-library').DimImagesTransform wmf.tables = require('./js/transforms/collapseTables') wmf.themes = require('wikimedia-page-library').ThemeTransform wmf.redLinks = require('wikimedia-page-library').RedLinks wmf.paragraphs = require('./js/transforms/relocateFirstParagraph') wmf.images = require('./js/transforms/widenImages') wmf.platform = require('wikimedia-page-library').PlatformTransform window.wmf = wmf
Add delay to Baykok spawn and play sound
package totemic_commons.pokefenn.ceremony; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import totemic_commons.pokefenn.api.ceremony.Ceremony; import totemic_commons.pokefenn.api.music.MusicInstrument; import totemic_commons.pokefenn.entity.boss.EntityBaykok; import totemic_commons.pokefenn.util.EntityUtil; public class CeremonyBaykok extends Ceremony { public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments) { super(name, musicNeeded, maxStartupTime, instruments); } @Override public void effect(World world, BlockPos pos, int time) { if(world.isRemote || time != getEffectTime() - 1) return; world.playBroadcastSound(1013, pos, 0); //Wither spawn sound BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4))); EntityUtil.spawnEntity(world, spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5, new EntityBaykok(world)); } @Override public int getEffectTime() { return 3 * 20; } }
package totemic_commons.pokefenn.ceremony; import net.minecraft.util.BlockPos; import net.minecraft.util.EnumFacing; import net.minecraft.world.World; import totemic_commons.pokefenn.api.ceremony.Ceremony; import totemic_commons.pokefenn.api.music.MusicInstrument; import totemic_commons.pokefenn.entity.boss.EntityBaykok; import totemic_commons.pokefenn.util.EntityUtil; public class CeremonyBaykok extends Ceremony { public CeremonyBaykok(String name, int musicNeeded, int maxStartupTime, MusicInstrument... instruments) { super(name, musicNeeded, maxStartupTime, instruments); } @Override public void effect(World world, BlockPos pos, int time) { BlockPos spos = pos.offset(EnumFacing.getHorizontal(world.rand.nextInt(4))); EntityUtil.spawnEntity(world, spos.getX() + 0.5, spos.getY(), spos.getZ() + 0.5, new EntityBaykok(world)); } }
Remove deprecated attributes comment_re and check_version
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Stoutenburgh # Copyright (c) 2016 Ben Stoutenburgh # # License: MIT # """This module exports the Bashate plugin class.""" from SublimeLinter.lint import Linter import os class Bashate(Linter): """Provides an interface to bashate.""" cmd = 'bashate' regex = ( r'^.+:(?P<line>\d+):1: (?:(?P<error>E)|(?P<warning>W))\d{3} (?P<message>.+)' ) defaults = { 'selector': 'source.shell.bash', '--ignore=,': '', '--warn=,': '', '--error=,': '' } tempfile_suffix = 'sh' def tmpfile(self, cmd, code, suffix=''): """ Run an external executable using a temp file to pass code and return its output. We override this to have the tmpfile extension match what is being linted so E005 is valid. """ filename, extension = os.path.splitext(self.filename) extension = '.missingextension' if not extension else extension return super().tmpfile(cmd, code, extension)
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by Ben Stoutenburgh # Copyright (c) 2016 Ben Stoutenburgh # # License: MIT # """This module exports the Bashate plugin class.""" from SublimeLinter.lint import Linter import os class Bashate(Linter): """Provides an interface to bashate.""" cmd = 'bashate' comment_re = r'\s*#' regex = ( r'^.+:(?P<line>\d+):1: (?:(?P<error>E)|(?P<warning>W))\d{3} (?P<message>.+)' ) defaults = { 'selector': 'source.shell.bash', '--ignore=,': '', '--warn=,': '', '--error=,': '' } tempfile_suffix = 'sh' check_version = False def tmpfile(self, cmd, code, suffix=''): """ Run an external executable using a temp file to pass code and return its output. We override this to have the tmpfile extension match what is being linted so E005 is valid. """ filename, extension = os.path.splitext(self.filename) extension = '.missingextension' if not extension else extension return super().tmpfile(cmd, code, extension)
Fix return type of Maybe usecase
package easymvp.usecase; import javax.annotation.Nullable; import easymvp.executer.PostExecutionThread; import easymvp.executer.UseCaseExecutor; import io.reactivex.Maybe; import io.reactivex.MaybeTransformer; /** * @author Saeed Masoumi (s-masoumi@live.com) */ public abstract class MaybeUseCase<R, Q> extends UseCase<Maybe, Q> { private final MaybeTransformer<? super R, ? extends R> schedulersTransformer; public MaybeUseCase(final UseCaseExecutor useCaseExecutor, final PostExecutionThread postExecutionThread) { super(useCaseExecutor, postExecutionThread); schedulersTransformer = new MaybeTransformer<R, R>() { @Override public Maybe<R> apply(Maybe<R> single) { return single.subscribeOn(useCaseExecutor.getScheduler()) .observeOn(postExecutionThread.getScheduler()); } }; } @Override public Maybe<R> execute(@Nullable Q param) { return interact(param).compose(getSchedulersTransformer()); } @Override protected abstract Maybe<R> interact(@Nullable Q param); private MaybeTransformer<? super R, ? extends R> getSchedulersTransformer() { return schedulersTransformer; } }
package easymvp.usecase; import javax.annotation.Nullable; import easymvp.executer.PostExecutionThread; import easymvp.executer.UseCaseExecutor; import io.reactivex.Maybe; import io.reactivex.MaybeTransformer; /** * @author Saeed Masoumi (s-masoumi@live.com) */ public abstract class MaybeUseCase<R, Q> extends UseCase<Maybe, Q> { private final MaybeTransformer<? super R, ? extends R> schedulersTransformer; public MaybeUseCase(final UseCaseExecutor useCaseExecutor, final PostExecutionThread postExecutionThread) { super(useCaseExecutor, postExecutionThread); schedulersTransformer = new MaybeTransformer<R, R>() { @Override public Maybe<R> apply(Maybe<R> single) { return single.subscribeOn(useCaseExecutor.getScheduler()) .observeOn(postExecutionThread.getScheduler()); } }; } @Override public Maybe execute(@Nullable Q param) { return interact(param).compose(getSchedulersTransformer()); } @Override protected abstract Maybe<R> interact(@Nullable Q param); private MaybeTransformer<? super R, ? extends R> getSchedulersTransformer() { return schedulersTransformer; } }
Add sorl-thumbnail and Django as installation requirements.
#!/usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup( name="django-flexible-images", version="1.0.0", url="https://github.com/lewiscollard/django-flexible-images", author="Lewis Collard", author_email="lewis.collard@onespacemedia.com", packages=find_packages(), include_package_data=True, zip_safe=False, description='A responsive image solution for Django.', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication', ], install_requires=[ 'django', 'sorl-thumbnail' ] )
#!/usr/bin/env python # coding: utf-8 from setuptools import find_packages, setup setup( name="django-flexible-images", version="1.0.0", url="https://github.com/lewiscollard/django-flexible-images", author="Lewis Collard", author_email="lewis.collard@onespacemedia.com", packages=find_packages(), include_package_data=True, zip_safe=False, description='A responsive image solution for Django.', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Framework :: Django', 'Framework :: Django :: 1.8', 'Natural Language :: English', 'Programming Language :: Python :: 2.7', 'License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication', ], )
Remove objects when they are not used
import pygame from pygame.locals import * from wars.block import Block class Device(object): # Static params height = 60 # Object params blocks = [] title = None pos_y = None def __init__(self, title, pos): self.title = title self.pos_y = pos self.blocks = [] def move_blocks(self, amount): for block in self.blocks: block.move(amount) if block.right_edge() <= 0: self.blocks.remove(block) del block def add_block(self, block): block.pos_y = self.pos_y * self.height self.blocks.append(block) def reset(self): del self.blocks[:] def draw(self, surface): # Do all the drawing of yourself and such. # As there is currently only one ST, this is omitted # Draw the blocks into yourself for block in self.blocks: block.draw(surface)
import pygame from pygame.locals import * from wars.block import Block class Device(object): # Static params height = 60 # Object params blocks = [] title = None pos_y = None def __init__(self, title, pos): self.title = title self.pos_y = pos self.blocks = [] def move_blocks(self, amount): for block in self.blocks: block.move(amount) if block.right_edge() <= 0: self.blocks.remove(block) def add_block(self, block): block.pos_y = self.pos_y * self.height self.blocks.append(block) def reset(self): del self.blocks[:] def draw(self, surface): # Do all the drawing of yourself ans such # TODO: Implement this.. # Draw the blocks into yourself for block in self.blocks: block.draw(surface)
Add playCard functionality and reducerHandler
import createReducer from 'redux/utils/createReducer'; import { List } from 'immutable'; import { DRAW_CARD } from './deck'; import { CardModel } from './card'; const PLAY_CARD = 'PLAY_CARD'; const initialState = new List([ new CardModel({ id: 1, name: 'Gabria Warden', mana: 1, attack: 5, defense: 1 }), new CardModel({ id: 2, name: 'Abusive Sergeant', mana: 1, attack: 2, defense: 1 }), new CardModel({ id: 3, name: 'Acolyte of Pain', mana: 3 }), new CardModel({ id: 4, name: 'Azure Drake', mana: 5, attack: 4, defense: 4 }), ]); export function playCard(index) { return { index, type: PLAY_CARD }; } function drawCardHandler(state) { const newCard = new CardModel({ id: 1, name: 'Gabria Warden', mana: 1, attack: 5, defense: 1 }); return state.push(newCard); } function playCardHandler(state, action) { return state.delete(action.index); } const handlers = { [DRAW_CARD]: drawCardHandler, [PLAY_CARD]: playCardHandler, }; export default createReducer(initialState, handlers);
import createReducer from 'redux/utils/createReducer'; import { List } from 'immutable'; import { DRAW_CARD } from './deck'; import { CardModel } from './card'; const initialState = new List([ new CardModel({ id: 1, name: 'Gabria Warden', mana: 1, attack: 5, defense: 1 }), new CardModel({ id: 2, name: 'Abusive Sergeant', mana: 1, attack: 2, defense: 1 }), new CardModel({ id: 3, name: 'Acolyte of Pain', mana: 3 }), new CardModel({ id: 4, name: 'Azure Drake', mana: 5, attack: 4, defense: 4 }), ]); function drawCardHandler(state) { const newCard = new CardModel({ id: 1, name: 'Gabria Warden', mana: 1, attack: 5, defense: 1 }); return state.push(newCard); } const handlers = { [DRAW_CARD]: drawCardHandler, }; export default createReducer(initialState, handlers);
Remove rule to warn on explicit any
module.exports = { parser: "@typescript-eslint/parser", // Specifies the ESLint parser extends: [ "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react "plugin:@typescript-eslint/recommended", // Uses the recommended rules from @typescript-eslint/eslint-plugin "prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier "plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. ], parserOptions: { ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features sourceType: "module", // Allows for the use of imports ecmaFeatures: { jsx: true // Allows for the parsing of JSX } }, rules: { // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs // e.g. "@typescript-eslint/explicit-function-return-type": "off", "camelcase": "off", "@typescript-eslint/camelcase": "off", "@typescript-eslint/no-inferrable-types": "off", "@typescript-eslint/no-explicit-any": "off" }, settings: { react: { version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use } } };
module.exports = { parser: "@typescript-eslint/parser", // Specifies the ESLint parser extends: [ "plugin:react/recommended", // Uses the recommended rules from @eslint-plugin-react "plugin:@typescript-eslint/recommended", // Uses the recommended rules from @typescript-eslint/eslint-plugin "prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier "plugin:prettier/recommended" // Enables eslint-plugin-prettier and displays prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array. ], parserOptions: { ecmaVersion: 2018, // Allows for the parsing of modern ECMAScript features sourceType: "module", // Allows for the use of imports ecmaFeatures: { jsx: true // Allows for the parsing of JSX } }, rules: { // Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs // e.g. "@typescript-eslint/explicit-function-return-type": "off", "camelcase": "off", "@typescript-eslint/camelcase": "off", "@typescript-eslint/no-inferrable-types": "off" }, settings: { react: { version: "detect" // Tells eslint-plugin-react to automatically detect the version of React to use } } };
Make numbers the default comments style
from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import StringField, IntegerField, SelectField, BooleanField csrf = CsrfProtect() class Submission(Form): submission = StringField('Submission URL') comments = BooleanField('Include comments') comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')]) email = StringField('Kindle email address') kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')]) class Subreddit(Form): subreddit = StringField('Subreddit') comments = BooleanField('Include comments') comments_style = SelectField('Comments style', choices=[('numbers', 'numbers'), ('quotes', 'quotes')]) time = SelectField('Time period', choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'), ('hour', 'hour')]) limit = IntegerField('Number of posts') email = StringField('Kindle email address') kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
from flask_wtf import Form from flask_wtf.csrf import CsrfProtect from wtforms import StringField, IntegerField, SelectField, BooleanField csrf = CsrfProtect() class Submission(Form): submission = StringField('Submission URL') comments = BooleanField('Include comments') comments_style = SelectField('Comments style', choices=[('quotes', 'quotes'), ('numbers', 'numbers')]) email = StringField('Kindle email address') kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')]) class Subreddit(Form): subreddit = StringField('Subreddit') comments = BooleanField('Include comments') comments_style = SelectField('Comments style', choices=[('quotes', 'quotes'), ('numbers', 'numbers')]) time = SelectField('Time period', choices=[('all', 'all'), ('year', 'year'), ('month', 'month'), ('week', 'week'), ('day', 'day'), ('hour', 'hour')]) limit = IntegerField('Number of posts') email = StringField('Kindle email address') kindle_address = SelectField('Kindle address', choices=[('normal', '@kindle.com'), ('free', '@free.kindle.com')])
Create a pattern to replace with the shortcodes.
<?php /** * @file * Filter that enable the use patterns to create visual content more easy. * Drupal\visual_content_layout\Plugin\Filter\FilterVisualContent. * */ namespace Drupal\visual_content_layout\Plugin\Filter; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; /** * Provides a filter to use shortdoces. *. * * @Filter( * id = "filter_visualcontentlayout", * title = @Translation("Visual Content Layout"), * description = @Translation("Provides a ShortCode filter format to easily generate content layout."), * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE, * settings = { * "allowed_shortcodes" = "[box]" * } * ) */ class FilterVisualContentLayout extends FilterBase{ /** * {@inheritdoc} */ public function process($text, $langcode) { return new FilterProcessResult(_filter_visual_layout_content($text, $this)); } /** * {@inheritdoc} */ public function tips($long = FALSE) { } }
<?php /** * @file * Filter that enable the use patterns to create visual content more easy. * Drupal\visual_content_layout\Plugin\Filter\FilterVisualContent. * */ namespace Drupal\visual_content_layout\Plugin\Filter; use Drupal\filter\FilterProcessResult; use Drupal\filter\Plugin\FilterBase; /** * Provides a filter to use shortdoces. *. * * @Filter( * id = "filter_visualcontentlayout", * title = @Translation("Visual Content Layout"), * description = @Translation("Provides a ShortCode filter format to easily generate content layout."), * type = Drupal\filter\Plugin\FilterInterface::TYPE_TRANSFORM_REVERSIBLE * ) */ class FilterVisualContentLayout extends FilterBase{ /** * {@inheritdoc} */ public function process($text, $langcode) { return new FilterProcessResult(_filter_visual_layout_content($text, $this)); } /** * {@inheritdoc} */ public function tips($long = FALSE) { } }
Correct parameter for network request
<?php namespace AdvancedBan; use AdvancedBan; class Network { private $host; private $path; public function __construct(string $url) { $url = parse_url($url); $this->host = $url["host"]; $this->path = $url["path"]; return $this; } public function getHost( ) { return $this->host; } public function getPath( ) { return $this->path; } public function send( ) { $request = curl_init("https://" . $this->host . $this->path); curl_setopt($request, CURLOPT_RETURNTRANSFER, true); curl_setopt($request, CURLOPT_POSTFIELDS, "website=" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); curl_exec($request); curl_close($request); return $this; } }
<?php namespace AdvancedBan; use AdvancedBan; class Network { private $host; private $path; public function __construct(string $url) { $url = parse_url($url); $this->host = $url["host"]; $this->path = $url["path"]; return $this; } public function getHost( ) { return $this->host; } public function getPath( ) { return $this->path; } public function send( ) { $request = curl_init("https://" . $this->host . $this->path); curl_setopt($request, CURLOPT_RETURNTRANSFER, true); curl_setopt($request, CURLOPT_POSTFIELDS, "domain=" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]); curl_exec($request); curl_close($request); return $this; } }
Revert "server: ensures we are not listening on the public interface" This reverts commit 272b9fdec7eadfa83ec57b7563788611ecdc5534.
var express = require('express'); var haml = require('hamljs'); var path = require('path'); var fs = require('fs'); var bodyParser = require('body-parser'); var engine = require('./libs/words_finder_engine'); engine.initialize(); // setup var app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.use( bodyParser.json() ); // routes app.get('/', function(req, res) { var hamlView = fs.readFileSync('views/main.haml', 'utf8'); res.send( haml.render(hamlView) ); }); app.post('/find-words', function(req, res) { res.json( engine.findWords(req.body) ); }); app.listen(process.env.PORT || 3000);
var express = require('express'); var haml = require('hamljs'); var path = require('path'); var fs = require('fs'); var bodyParser = require('body-parser'); var engine = require('./libs/words_finder_engine'); engine.initialize(); // setup var app = express(); app.use(express.static(path.join(__dirname, 'public'))); app.use( bodyParser.json() ); // routes app.get('/', function(req, res) { var hamlView = fs.readFileSync('views/main.haml', 'utf8'); res.send( haml.render(hamlView) ); }); app.post('/find-words', function(req, res) { res.json( engine.findWords(req.body) ); }); app.listen(process.env.PORT || 3000, '127.0.0.1');
Adjust image size to fetch for gallery view. to comply with predefined bucket sizes, for performance/cache reasons: https://git.wikimedia.org/blob/mediawiki%2Fextensions%2FMultimediaViewer.git/f9e7bae91a8032fa13fc68114a0d57d190ea77f9/resources%2Fmmv%2Fmmv.ThumbnailWidthCalculator.js Change-Id: I6fef16c591d149e5e1c7a5e7ae53eb057bbef1c3
package org.wikipedia.page.gallery; import org.json.JSONObject; import org.mediawiki.api.json.Api; import org.mediawiki.api.json.RequestBuilder; import org.wikipedia.PageQueryTask; import org.wikipedia.PageTitle; import org.wikipedia.Site; public class GalleryItemFetchTask extends PageQueryTask<GalleryItem> { public GalleryItemFetchTask(Api api, Site site, PageTitle title) { super(LOW_CONCURRENCY, api, site, title); } @Override public void buildQueryParams(RequestBuilder builder) { builder.param("prop", "imageinfo") .param("iiprop", "url|dimensions|mime|extmetadata") .param("iiurlwidth", "2880"); } @Override public GalleryItem processPage(int pageId, PageTitle pageTitle, JSONObject pageData) throws Throwable { return new GalleryItem(pageData); } }
package org.wikipedia.page.gallery; import org.json.JSONObject; import org.mediawiki.api.json.Api; import org.mediawiki.api.json.RequestBuilder; import org.wikipedia.PageQueryTask; import org.wikipedia.PageTitle; import org.wikipedia.Site; public class GalleryItemFetchTask extends PageQueryTask<GalleryItem> { public GalleryItemFetchTask(Api api, Site site, PageTitle title) { super(LOW_CONCURRENCY, api, site, title); } @Override public void buildQueryParams(RequestBuilder builder) { builder.param("prop", "imageinfo") .param("iiprop", "url|dimensions|mime|extmetadata") .param("iiurlwidth", "2048"); } @Override public GalleryItem processPage(int pageId, PageTitle pageTitle, JSONObject pageData) throws Throwable { return new GalleryItem(pageData); } }
Use page_unpublished signal in frontend cache invalidator
from django.db import models from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.signals import page_published, page_unpublished from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache def page_published_signal_handler(instance, **kwargs): purge_page_from_cache(instance) def page_unpublished_signal_handler(instance, **kwargs): purge_page_from_cache(instance) def register_signal_handlers(): # Get list of models that are page types indexed_models = [model for model in models.get_models() if issubclass(model, Page)] # Loop through list and register signal handlers for each one for model in indexed_models: page_published.connect(page_published_signal_handler, sender=model) page_unpublished.connect(page_unpublished_signal_handler, sender=model)
from django.db import models from django.db.models.signals import post_delete from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.signals import page_published from wagtail.contrib.wagtailfrontendcache.utils import purge_page_from_cache def page_published_signal_handler(instance, **kwargs): purge_page_from_cache(instance) def post_delete_signal_handler(instance, **kwargs): purge_page_from_cache(instance) def register_signal_handlers(): # Get list of models that are page types indexed_models = [model for model in models.get_models() if issubclass(model, Page)] # Loop through list and register signal handlers for each one for model in indexed_models: page_published.connect(page_published_signal_handler, sender=model) post_delete.connect(post_delete_signal_handler, sender=model)
Fix trailing slash 404 for flat pages and co By modifying the URL, flatpage requests without a trailing slash will always fail, triggering the redirect provided by `APPEND_SLASH`. This is important because urls that share a common endpoint path were 404ing on a flatpage not found when not constructed with a slash.
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.conf.urls import patterns, url, include from apps.home import routes as r urlpatterns = patterns( '', url(r'^$', r.home_page, name='home_page'), url(r'^progress/$', r.progress_page, name='progress_page'), url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status, name='retrieve_job_status'), url(r'^training/$', r.training_list_page, name="training_list_page"), url(r'^training/groups_to_follow/$', r.groups_to_follow), # "training" instead of "training/" because the flatpages admin interface # insists that the "URL" (really a URL segment) start with a leading slash url(r'^training(?P<url>.*/)$', include('django.contrib.flatpages.urls')), )
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.conf.urls import patterns, url, include from apps.home import routes as r urlpatterns = patterns( '', url(r'^$', r.home_page, name='home_page'), url(r'^progress/$', r.progress_page, name='progress_page'), url(r'^jobs/(?P<job_id>\d+)/$', r.retrieve_job_status, name='retrieve_job_status'), url(r'^training/$', r.training_list_page, name="training_list_page"), url(r'^training/groups_to_follow/$', r.groups_to_follow), # "training" instead of "training/" because the flatpages admin interface # insists that the "URL" (really a URL segment) start with a leading slash url(r'^training', include('django.contrib.flatpages.urls')), )
[WEB-766] Rework popover to allow width to auto size by default, and be overriden by prop.
import React from 'react'; import PropTypes from 'prop-types'; import { default as Base, PopoverProps } from '@material-ui/core/Popover'; import styled from 'styled-components'; import { Box, BoxProps } from 'rebass/styled-components'; import { borders, radii, shadows, space } from '../../themes/baseTheme'; const StyledPopover = styled(Base)` .MuiPopover-paper { margin-top: ${space[2]}px; margin-bottom: ${space[2]}px; border: ${borders.modal}; box-shadow: ${shadows.large}; border-radius: ${radii.default}px; width: ${({ width }) => width}; max-width: calc(100% - ${space[5]}px); } `; const PopoverContentWrapper = React.forwardRef((props, ref) => ( <Box {...props} ref={ref} /> )); const Popover = props => { const { themeProps, PaperProps, ...popoverProps } = props; return ( <StyledPopover PaperProps={{ component: PopoverContentWrapper }} {...popoverProps} /> ); }; Popover.propTypes = { ...PopoverProps, themeProps: PropTypes.shape(BoxProps), }; Popover.defaultProps = { width: 'auto', anchorOrigin: { vertical: 'bottom', horizontal: 'left', }, transformOrigin: { vertical: 'top', horizontal: 'left', }, }; export default Popover;
import React from 'react'; import { default as Base, PopoverProps } from '@material-ui/core/Popover'; import styled from 'styled-components'; import { Box } from 'rebass/styled-components'; import { borders, radii, shadows, space } from '../../themes/baseTheme'; const StyledPopover = styled(Base)` .MuiPopover-paper { padding: ${space[3]}px; margin-top: ${space[2]}px; margin-bottom: ${space[2]}px; border: ${borders.modal}; box-shadow: ${shadows.large}; border-radius: ${radii.default}px; } `; const PopoverContentWrapper = React.forwardRef((props, ref) => ( <Box width={['100%', '50%', '33.3%', '25%']} {...props} ref={ref} /> )); const Popover = props => <StyledPopover {...props} />; Popover.propTypes = PopoverProps; Popover.defaultProps = { PaperProps: { component: PopoverContentWrapper, }, anchorOrigin: { vertical: 'bottom', horizontal: 'left', }, transformOrigin: { vertical: 'top', horizontal: 'left', }, }; export default Popover;
Remove beautifulsoup from the feed extension's requirements.
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the feed Sphinx extension. It creates an RSS feed of recently updated sphinx pages. ''' requires = ['Sphinx>=0.6', 'python-dateutil', 'html5lib'] setup( name='feed', version='0.2', url='http://bitbucket.org/birkenfeld/sphinx-contrib', # download_url='http://pypi.python.org/pypi/feed', license='BSD', author='dan mackinlay', author_email='bitbucket@email.possumpalace.org', description='Sphinx extension feed', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
# -*- coding: utf-8 -*- from setuptools import setup, find_packages long_desc = ''' This package contains the feed Sphinx extension. It creates an RSS feed of recently updated sphinx pages. ''' requires = ['Sphinx>=0.6', 'python-dateutil', 'beautifulsoup>=3.2.0', 'html5lib'] setup( name='feed', version='0.2', url='http://bitbucket.org/birkenfeld/sphinx-contrib', # download_url='http://pypi.python.org/pypi/feed', license='BSD', author='dan mackinlay', author_email='bitbucket@email.possumpalace.org', description='Sphinx extension feed', long_description=long_desc, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Documentation', 'Topic :: Utilities', ], platforms='any', packages=find_packages(), include_package_data=True, install_requires=requires, namespace_packages=['sphinxcontrib'], )
Allow caller to return any kind of value.
package com.hyprion.beckon; import sun.misc.Signal; import sun.misc.SignalHandler; import java.util.List; import java.util.concurrent.Callable; public class SignalFolder implements SignalHandler { final private Callable[] fns; public SignalFolder(List funs) { fns = new Callable[funs.size()]; for (int i = 0; i < fns.length; i++) { fns[i] = (Callable) funs.get(i); } } public void handle(Signal sig) { for (Callable c : fns) { boolean cont = true; try { Object oRes = c.call(); if (oRes == false || oRes == null) { cont = false; } } catch (Exception e) {} finally { if (!cont) { break; } } } } }
package com.hyprion.beckon; import sun.misc.Signal; import sun.misc.SignalHandler; import java.util.List; import java.util.concurrent.Callable; public class SignalFolder implements SignalHandler { final private Callable[] fns; public SignalFolder(List funs) { fns = new Callable[funs.size()]; for (int i = 0; i < fns.length; i++) { fns[i] = (Callable) funs.get(i); } } public void handle(Signal sig) { for (Callable c : fns) { boolean res = false; try { res = (Boolean) c.call(); // No input elems? } catch (Exception e) {} finally { if (!res) { break; } } } } }
Revert "number: match input example to be Dutch as in the output" This reverts commit c2d28a6ddf6cb833e996ccb00cbb4206394958d2. Reason for revert: This change was incorrect. The examples were supposed to demonstrate that the API can provide translations. Change-Id: I247d5509136d34ce4c82a8ac2de50dad3f652a78 Reviewed-on: https://go-review.googlesource.com/c/text/+/316529 Reviewed-by: Emmanuel Odeke <bd234ba4276433f0e5fc7a8fa2d18274fa711567@orijtech.com> Reviewed-by: Alberto Donizetti <90b16103a35511ced020676f3544f17117fb4c92@gmail.com> Run-TryBot: Emmanuel Odeke <bd234ba4276433f0e5fc7a8fa2d18274fa711567@orijtech.com> Run-TryBot: Alberto Donizetti <90b16103a35511ced020676f3544f17117fb4c92@gmail.com> Trust: Cherry Mui <d62e63aa42ce272d7b6a5055d97e942b33a34679@google.com>
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package number formats numbers according to the customs of different locales. // // The number formats of this package allow for greater formatting flexibility // than passing values to message.Printf calls as is. It currently supports the // builtin Go types and anything that implements the Convert interface // (currently internal). // // p := message.NewPrinter(language.English) // // p.Printf("%v bottles of beer on the wall.", number.Decimal(1234)) // // Prints: 1,234 bottles of beer on the wall. // // p.Printf("%v of gophers lose too much fur", number.Percent(0.12)) // // Prints: 12% of gophers lose too much fur. // // p := message.NewPrinter(language.Dutch) // // p.Printf("There are %v bikes per household.", number.Decimal(1.2)) // // Prints: Er zijn 1,2 fietsen per huishouden. // // // The width and scale specified in the formatting directives override the // configuration of the formatter. package number
// Copyright 2017 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package number formats numbers according to the customs of different locales. // // The number formats of this package allow for greater formatting flexibility // than passing values to message.Printf calls as is. It currently supports the // builtin Go types and anything that implements the Convert interface // (currently internal). // // p := message.NewPrinter(language.English) // // p.Printf("%v bottles of beer on the wall.", number.Decimal(1234)) // // Prints: 1,234 bottles of beer on the wall. // // p.Printf("%v of gophers lose too much fur", number.Percent(0.12)) // // Prints: 12% of gophers lose too much fur. // // p := message.NewPrinter(language.Dutch) // // p.Printf("Er zijn %v fietsen per huishouden.", number.Decimal(1.2)) // // Prints: Er zijn 1,2 fietsen per huishouden. // // // The width and scale specified in the formatting directives override the // configuration of the formatter. package number
Return empty at the right place
package de.stephanlindauer.criticalmaps.vo.chat; import com.squareup.okhttp.internal.Util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1; import de.stephanlindauer.criticalmaps.interfaces.IChatMessage; public class OutgoingChatMessage implements IChatMessage { private final Date timestamp; private final String urlEncodedMessage; private final String identifier; private final String message; public OutgoingChatMessage(String message) { this.message = message; this.urlEncodedMessage = urlEncodeMessage(message); this.timestamp = new Date(); this.identifier = AeSimpleSHA1.SHA1(message + Math.random()); } public Date getTimestamp() { return timestamp; } public String getUrlEncodedMessage() { return urlEncodedMessage; } public String getMessage() { return message; } public String getIdentifier() { return identifier; } private String urlEncodeMessage(String messageToEncode) { try { return URLEncoder.encode(messageToEncode, Util.UTF_8.name()); } catch (UnsupportedEncodingException e) { return ""; } } }
package de.stephanlindauer.criticalmaps.vo.chat; import com.squareup.okhttp.internal.Util; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.Date; import de.stephanlindauer.criticalmaps.utils.AeSimpleSHA1; import de.stephanlindauer.criticalmaps.interfaces.IChatMessage; public class OutgoingChatMessage implements IChatMessage { private final Date timestamp; private final String urlEncodedMessage; private final String identifier; private final String message; public OutgoingChatMessage(String message) { this.message = message; this.urlEncodedMessage = urlEncodeMessage(message); this.timestamp = new Date(); this.identifier = AeSimpleSHA1.SHA1(message + Math.random()); } public Date getTimestamp() { return timestamp; } public String getUrlEncodedMessage() { return urlEncodedMessage; } public String getMessage() { return message; } public String getIdentifier() { return identifier; } private String urlEncodeMessage(String messageToEncode) { try { return URLEncoder.encode(messageToEncode, Util.UTF_8.name()); } catch (UnsupportedEncodingException e) { } return ""; } }
Make Sequelize use settings from config file.
var Sequelize = require('sequelize'); var fs = require('fs'); var path = require('path'); var config = require('../config'); var sequelize = new Sequelize(config.db.name, config.db.username, config.db.password, { host: config.db.host, port: config.db.port, dialect: config.db.dialect }); var models = {}; models.sequelize = sequelize; var modelFiles = fs.readdirSync(__dirname); modelFiles.splice(modelFiles.indexOf('index.js'), 1); // Remove self from list. //modelFiles.splice(modelFiles.indexOf('util.js'), 1); // Remove util from list. for (i in modelFiles) { var model = sequelize.import(path.join(__dirname, modelFiles[i])); models[model.name] = model } Object.keys(models).forEach(function(modelName) { if ("addAssociations" in models[modelName]) { models[modelName].addAssociations(models) } }) module.exports = models;
var Sequelize = require('sequelize'); var fs = require('fs'); var path = require('path'); var sequelize = new Sequelize('cacophony_metadata', 'test', 'pass', { host: '192.168.33.10', port: '5432', dialect: 'postgres' }); var models = {}; models.sequelize = sequelize; var modelFiles = fs.readdirSync(__dirname); modelFiles.splice(modelFiles.indexOf('index.js'), 1); // Remove self from list. //modelFiles.splice(modelFiles.indexOf('util.js'), 1); // Remove util from list. for (i in modelFiles) { var model = sequelize.import(path.join(__dirname, modelFiles[i])); models[model.name] = model } Object.keys(models).forEach(function(modelName) { if ("addAssociations" in models[modelName]) { models[modelName].addAssociations(models) } }) module.exports = models;
Fix UnicodeDecodeError error when installing Fix UnicodeDecodeError raised when attempting to install in non-English systems (e.g. Windows 10 Korean).
import io import os from setuptools import setup def read(name): file_path = os.path.join(os.path.dirname(__file__), name) return io.open(file_path, encoding='utf8').read() setup( name='python-dxf', version='7.5.0', description="Package for accessing a Docker v2 registry", long_description=read('README.rst'), keywords='docker registry', author='David Halls', author_email='dave@davedoesdev.com', url='https://github.com/davedoesdev/dxf', license='MIT', packages=['dxf'], entry_points={'console_scripts': ['dxf=dxf.main:main']}, install_requires=['www-authenticate>=0.9.2', 'requests>=2.18.4', 'jwcrypto>=0.4.2', 'tqdm>=4.19.4'] )
import os from setuptools import setup def read(name): return open(os.path.join(os.path.dirname(__file__), name)).read() setup( name='python-dxf', version='7.5.0', description="Package for accessing a Docker v2 registry", long_description=read('README.rst'), keywords='docker registry', author='David Halls', author_email='dave@davedoesdev.com', url='https://github.com/davedoesdev/dxf', license='MIT', packages=['dxf'], entry_points={'console_scripts': ['dxf=dxf.main:main']}, install_requires=['www-authenticate>=0.9.2', 'requests>=2.18.4', 'jwcrypto>=0.4.2', 'tqdm>=4.19.4'] )
Fix the migration script so that the down revision is pointing to the migration scripts in the merge
"""empty message Revision ID: 0003_create_tokens Revises: 0001_initialise_data Create Date: 2016-01-13 17:07:49.061776 """ # revision identifiers, used by Alembic. revision = '0003_create_tokens' down_revision = '0002_add_templates' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('tokens', sa.Column('id', sa.Integer(), nullable=False), sa.Column('token', sa.String(length=255), nullable=False), sa.Column('service_id', sa.Integer(), nullable=False), sa.Column('expiry_date', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['service_id'], ['services.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('token') ) op.create_index(op.f('ix_tokens_service_id'), 'tokens', ['service_id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_tokens_service_id'), table_name='tokens') op.drop_table('tokens') ### end Alembic commands ###
"""empty message Revision ID: 0003_create_tokens Revises: 0001_initialise_data Create Date: 2016-01-13 17:07:49.061776 """ # revision identifiers, used by Alembic. revision = '0003_create_tokens' down_revision = '0001_initialise_data' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.create_table('tokens', sa.Column('id', sa.Integer(), nullable=False), sa.Column('token', sa.String(length=255), nullable=False), sa.Column('service_id', sa.Integer(), nullable=False), sa.Column('expiry_date', sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(['service_id'], ['services.id'], ), sa.PrimaryKeyConstraint('id'), sa.UniqueConstraint('token') ) op.create_index(op.f('ix_tokens_service_id'), 'tokens', ['service_id'], unique=False) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_index(op.f('ix_tokens_service_id'), table_name='tokens') op.drop_table('tokens') ### end Alembic commands ###
Use ADMIN_APIKEY from the env in tests.
/* * Suite-global initialization that should occur before any other files are required. It's probably * a code smell that I have to do this. */ var config = require('../../src/config'); function reconfigure () { if (process.env.INTEGRATION) { console.log('Integration test mode active.'); config.configure(process.env); console.log('NOTE: This will leave files uploaded in Cloud Files containers.'); console.log('Be sure to clear these containers after:'); console.log('[' + config.contentContainer() + '] and [' + config.assetContainer() + ']'); } else { config.configure({ STORAGE: 'memory', RACKSPACE_USERNAME: 'me', RACKSPACE_APIKEY: '12345', RACKSPACE_REGION: 'space', ADMIN_APIKEY: process.env.ADMIN_APIKEY || '12345', CONTENT_CONTAINER: 'the-content-container', ASSET_CONTAINER: 'the-asset-container', MONGODB_URL: 'mongodb-url', CONTENT_LOG_LEVEL: process.env.CONTENT_LOG_LEVEL || 'error' }); } } reconfigure(); exports.reconfigure = reconfigure;
/* * Suite-global initialization that should occur before any other files are required. It's probably * a code smell that I have to do this. */ var config = require('../../src/config'); function reconfigure () { if (process.env.INTEGRATION) { console.log('Integration test mode active.'); config.configure(process.env); console.log('NOTE: This will leave files uploaded in Cloud Files containers.'); console.log('Be sure to clear these containers after:'); console.log('[' + config.contentContainer() + '] and [' + config.assetContainer() + ']'); } else { config.configure({ STORAGE: 'memory', RACKSPACE_USERNAME: 'me', RACKSPACE_APIKEY: '12345', RACKSPACE_REGION: 'space', ADMIN_APIKEY: '12345', CONTENT_CONTAINER: 'the-content-container', ASSET_CONTAINER: 'the-asset-container', MONGODB_URL: 'mongodb-url', CONTENT_LOG_LEVEL: process.env.CONTENT_LOG_LEVEL || 'error' }); } } reconfigure(); exports.reconfigure = reconfigure;
Remove modal from DOM after hide
window.bindModals = function() { $('a[data-toggle=modal]').on('click', function() { var template = $($(this).attr('href')).html(); var output = Mustache.render(template, { content: $(this).data('content') }); $(output).appendTo($('body')); $('.modal').on('hidden.bs.modal', function(e) { $(this).remove(); }); }); }; $(function() { $('a[data-toggle="tab"]').bind('shown.bs.tab', function(e) { var currentTab = e.target; var tabContent = $($(currentTab).attr('href')); var dataUrl = tabContent.data('url'); $.getJSON(dataUrl).success(function(data){ var template = $('#dj_reports_template').html(); if(data.length > 0) { var output = Mustache.render(template, data); } else { var output = "<div class='alert alert-warning'>No Jobs</div>"; } tabContent.html(output); bindModals(); }); }); $('.nav.nav-tabs li.active a[data-toggle="tab"]').trigger('shown.bs.tab'); (function refreshCount() { $.getJSON(dj_counts_dj_reports_path).success(function(data){ var template = $('#dj_counts_template').html(); var output = Mustache.render(template, data); $('#dj-counts-view').html(output); setTimeout(refreshCount, 5000); }); })(); });
window.bindModalClicks = function() { $('a[data-toggle=modal]').on('click', function() { var template = $($(this).attr('href')).html(); var output = Mustache.render(template, { content: $(this).data('content') }); $(output).appendTo($('body')); }); }; $(function() { $('a[data-toggle="tab"]').bind('shown.bs.tab', function(e) { var currentTab = e.target; var tabContent = $($(currentTab).attr('href')); var dataUrl = tabContent.data('url'); $.getJSON(dataUrl).success(function(data){ var template = $('#dj_reports_template').html(); if(data.length > 0) { var output = Mustache.render(template, data); } else { var output = "<div class='alert alert-warning'>No Jobs</div>"; } tabContent.html(output); bindModalClicks(); }); }); $('.nav.nav-tabs li.active a[data-toggle="tab"]').trigger('shown.bs.tab'); bindModalClicks(); (function refreshCount() { $.getJSON(dj_counts_dj_reports_path).success(function(data){ var template = $('#dj_counts_template').html(); var output = Mustache.render(template, data); $('#dj-counts-view').html(output); setTimeout(refreshCount, 5000); }); })(); });
Fix the issue when reseting the form on successful calls
// Execute JavaScript on page load $(function () { $("#userNumber, #salesNumber").intlTelInput({ responsiveDropdown: true, autoFormat: true }); var $form = $("#contactform"), $submit = $("#contactform input[type=submit]"); // Intercept form submission $form.on("submit", function (e) { // Prevent form submission and repeat clicks e.preventDefault(); $submit.attr("disabled", "disabled"); // Submit the form via AJAX $.post("/CallCenter/Call", $form.serialize(), null, "json") .done(function (data) { alert(data.message); if (data.success) { $form[0].reset(); } }).fail(function () { alert("There was a problem calling you - please try again later."); }).always(function () { $submit.removeAttr("disabled"); }); }); });
// Execute JavaScript on page load $(function () { $("#userNumber, #salesNumber").intlTelInput({ responsiveDropdown: true, autoFormat: true }); var $form = $("#contactform"), $submit = $("#contactform input[type=submit]"); // Intercept form submission $form.on("submit", function (e) { // Prevent form submission and repeat clicks e.preventDefault(); $submit.attr("disabled", "disabled"); // Submit the form via AJAX $.post("/CallCenter/Call", $form.serialize(), null, "json") .done(function (data) { alert(data.message); if (data.success) { $form.reset(); } }).fail(function () { alert("There was a problem calling you - please try again later."); }).always(function () { $submit.removeAttr("disabled"); }); }); });
Update Webfilings info to Workiva
from setuptools import find_packages, setup def get_version(): import imp import os with open(os.path.join('furious', '_pkg_meta.py'), 'rb') as f: mod = imp.load_source('_pkg_meta', 'biloba', f) return mod.version setup_args = dict( name='furious', version=get_version(), license='Apache', description='Furious is a lightweight library that wraps Google App Engine' 'taskqueues to make building dynamic workflows easy.', author='Robert Kluin', author_email='robert.kluin@workiva.com', url='http://github.com/Workiva/furious', packages=find_packages(exclude=['example']), download_url = "https://github.com/Workiva/furious/tarball/v1.3.0", keywords = ['async', 'gae', 'appengine', 'taskqueue'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) if __name__ == '__main__': setup(**setup_args)
from setuptools import find_packages, setup def get_version(): import imp import os with open(os.path.join('furious', '_pkg_meta.py'), 'rb') as f: mod = imp.load_source('_pkg_meta', 'biloba', f) return mod.version setup_args = dict( name='furious', version=get_version(), license='Apache', description='Furious is a lightweight library that wraps Google App Engine' 'taskqueues to make building dynamic workflows easy.', author='Robert Kluin', author_email='robert.kluin@webfilings.com', url='http://github.com/WebFilings/furious', packages=find_packages(exclude=['example']), download_url = "https://github.com/Workiva/furious/tarball/v1.3.0", keywords = ['async', 'gae', 'appengine', 'taskqueue'], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', 'Programming Language :: Python', ], ) if __name__ == '__main__': setup(**setup_args)
Set Email Address string to be read from l10n
@extends('panelViews::mainTemplate') @section('page-wrapper') @if(Session::has('message')) <div class="alert-box success"> <h2>{{ Session::get('message') }}</h2> </div> @endif @if ($demo_status == true) <h4>You are not allowed to change the password in demo version of panel.</h4> @else <div class="row"> <div class="col-xs-4"> <form action="{{ action('\Serverfireteam\Panel\RemindersController@postChangePassword') }}" method="POST"> <label>{{ \Lang::get('panel::fields.emailAddress') }}</label> <input class="form-control" type="email" name="email"><br /> <label>{{ \Lang::get('panel::fields.currentPassword') }}</label> <input class="form-control" type="password" name="current_password"><br /> <label>{{ \Lang::get('panel::fields.password') }}</label> <input class="form-control" type="password" name="password"><br /> <label>{{ \Lang::get('panel::fields.rePassword') }}</label> <input class="form-control" type="password" name="password_confirmation"><br /> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input class="btn btn-default" type="submit" value="{{ \Lang::get('panel::fields.ChangePassword') }}"> </form> </div> </div> @endif @stop
@extends('panelViews::mainTemplate') @section('page-wrapper') @if(Session::has('message')) <div class="alert-box success"> <h2>{{ Session::get('message') }}</h2> </div> @endif @if ($demo_status == true) <h4>You are not allowed to change the password in demo version of panel.</h4> @else <div class="row"> <div class="col-xs-4"> <form action="{{ action('\Serverfireteam\Panel\RemindersController@postChangePassword') }}" method="POST"> <label>Email Address:</label> <input class="form-control" type="email" name="email"><br /> <label>{{ \Lang::get('panel::fields.currentPassword') }}</label> <input class="form-control" type="password" name="current_password"><br /> <label>{{ \Lang::get('panel::fields.password') }}</label> <input class="form-control" type="password" name="password"><br /> <label>{{ \Lang::get('panel::fields.rePassword') }}</label> <input class="form-control" type="password" name="password_confirmation"><br /> <input type="hidden" name="_token" value="{{{ csrf_token() }}}" /> <input class="btn btn-default" type="submit" value="{{ \Lang::get('panel::fields.ChangePassword') }}"> </form> </div> </div> @endif @stop
Return 0 if the Birth Date is in the future.
(function(global) { var getAge = function(birthday) { if (! (birthday instanceof Date) ) { birthday = new Date(birthday); } var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch var age = ageDate.getUTCFullYear() - 1970; return (age > 0) ? age : 0; }; var getAgeDate = function(birthday) { if (! (birthday instanceof Date) ) { birthday = new Date(birthday); } var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); return ageDate; }; global.getAge = getAge; global.getAgeDate = getAgeDate; }(this));
(function(global) { var getAge = function(birthday) { if (! (birthday instanceof Date) ) { birthday = new Date(birthday); } var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); // miliseconds from epoch return Math.abs(ageDate.getUTCFullYear() - 1970); }; var getAgeDate = function(birthday) { if (! (birthday instanceof Date) ) { birthday = new Date(birthday); } var ageDifMs = Date.now() - birthday.getTime(); var ageDate = new Date(ageDifMs); return ageDate; }; global.getAge = getAge; global.getAgeDate = getAgeDate; }(this));
Remove set requirement in training text class constructor
package org.granite.classification.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.TreeSet; @JsonIgnoreProperties(ignoreUnknown = true) public class TrainingText implements Comparable<TrainingText> { private int id; private TreeSet<String> classifications = new TreeSet<>(); private TreeSet<String> wordBag = new TreeSet<>(); private String text; TrainingText(){} public TrainingText(final int id, final String text) { this.id = id; this.text = text; } public int getId() { return id; } public TreeSet<String> getClassifications() { return classifications; } public TreeSet<String> getWordBag() { return wordBag; } public String getText() { return text; } @Override public int compareTo(TrainingText trainingText) { return Integer.compare(id, trainingText.getId()); } @Override public boolean equals(Object obj) { return obj instanceof TrainingText && getId() == ((TrainingText) obj).getId(); } @Override public int hashCode() { return getId(); } }
package org.granite.classification.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import java.util.TreeSet; @JsonIgnoreProperties(ignoreUnknown = true) public class TrainingText implements Comparable<TrainingText> { private int id; private TreeSet<String> classifications = new TreeSet<>(); private TreeSet<String> wordBag = new TreeSet<>(); private String text; TrainingText(){} public TrainingText(final int id, final TreeSet<String> classifications, final String text) { this.id = id; this.classifications = classifications; this.text = text; } public int getId() { return id; } public TreeSet<String> getClassifications() { return classifications; } public TreeSet<String> getWordBag() { return wordBag; } public String getText() { return text; } @Override public int compareTo(TrainingText trainingText) { return Integer.compare(id, trainingText.getId()); } @Override public boolean equals(Object obj) { return obj instanceof TrainingText && getId() == ((TrainingText) obj).getId(); } @Override public int hashCode() { return getId(); } }
Add note about cloudflare caching
const webpack = require("webpack"); const merge = require("webpack-merge"); const workboxPlugin = require("workbox-webpack-plugin"); const common = require("./webpack.common.js"); const config = merge(common, { devtool: "source-map", plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") }, SENTRY_DSN: JSON.stringify( "https://12b6be8ef7c44f28ac37ab5ed98fd294@sentry.io/146021" ) }), new webpack.optimize.UglifyJsPlugin({ // TODO: Is this needed with the devtool setting above? sourceMap: true }), new workboxPlugin.GenerateSW({ // Note: CloudFlare is configued to not cache this file, as suggested in the: // "Avoid changing the URL of your service worker script" sectio of: // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle swDest: "service-worker.js", clientsClaim: true, skipWaiting: true }) ] }); config.entry.winamp.unshift("./js/googleAnalytics.min.js"); module.exports = config;
const webpack = require("webpack"); const merge = require("webpack-merge"); const workboxPlugin = require("workbox-webpack-plugin"); const common = require("./webpack.common.js"); const config = merge(common, { devtool: "source-map", plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("production") }, SENTRY_DSN: JSON.stringify( "https://12b6be8ef7c44f28ac37ab5ed98fd294@sentry.io/146021" ) }), new webpack.optimize.UglifyJsPlugin({ // TODO: Is this needed with the devtool setting above? sourceMap: true }), new workboxPlugin.GenerateSW({ swDest: "service-worker.js", clientsClaim: true, skipWaiting: true }) ] }); config.entry.winamp.unshift("./js/googleAnalytics.min.js"); module.exports = config;
Add some search fields to Zaad
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] search_fields = ['account_name', 'account_number'] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
from django.contrib import admin from bluebottle.funding.admin import PaymentChildAdmin, PaymentProviderChildAdmin, BankAccountChildAdmin from bluebottle.funding.models import PaymentProvider, Payment from bluebottle.funding_telesom.models import TelesomPayment, TelesomPaymentProvider, TelesomBankAccount @admin.register(TelesomPayment) class TelesomPaymentAdmin(PaymentChildAdmin): base_model = Payment fields = PaymentChildAdmin.fields + [ 'account_name', 'account_number', 'response', 'unique_id', 'reference_id', 'transaction_id', 'transaction_amount', 'issuer_transaction_id', 'amount', 'currency' ] list_display = ['created', 'account_name', 'account_number', 'amount', 'status'] @admin.register(TelesomPaymentProvider) class TelesomPaymentProviderAdmin(PaymentProviderChildAdmin): base_model = PaymentProvider @admin.register(TelesomBankAccount) class TelesomBankAccountAdmin(BankAccountChildAdmin): model = TelesomBankAccount fields = ('account_name', 'mobile_number') + BankAccountChildAdmin.fields list_filter = ['reviewed'] search_fields = ['account_name', 'mobile_number'] list_display = ['created', 'account_name', 'mobile_number', 'reviewed']
Add notify in git wrapper [ci skip]
var Q = require('q'); var _ = require('lodash'); var spawn = require('child_process').spawn; module.exports = function(args, options) { var deferred = Q.defer(); options = options || {}; var defaults = { cwd: process.cwd(), verbose: false }; options = _.extend({}, defaults, options); var child = spawn('git', args, _.omit(options, 'verbose')); child.on('exit', function(code) { if (code === 128) { deferred.reject("git did not exit cleanly"); } else { deferred.resolve(code); } }); child.stdout.on('data', function(data) { deferred.notify(data.toString()); }); child.stderr.on('data', function(data) { deferred.reject(data.toString()); }); return deferred.promise; };
var Q = require('q'); var _ = require('lodash'); var spawn = require('child_process').spawn; module.exports = function(args, options) { var deferred = Q.defer(); options = options || {}; var defaults = { cwd: process.cwd(), verbose: false }; options = _.extend({}, defaults, options); var child = spawn('git', args, _.omit(options, 'verbose')); child.on('exit', function(code) { if (code === 128) { deferred.reject("git did not exit cleanly"); } else { deferred.resolve(code); } }); child.stderr.on('data', function(data) { deferred.notify(data.toString()); }); return deferred.promise; };
Remove log chown step from post-deployment process.
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
import os from fabric.api import task, run, local, sudo, cd, env env.hosts = [ os.environ['TWWEB_HOST'], ] def virtualenv(command, user=None): run('source /var/www/envs/twweb/bin/activate && ' + command) @task def deploy(): local('git push origin development') local('git checkout master') local('git merge development') local('git push origin master') with cd('/var/www/twweb'): run('git fetch origin') run('git merge origin/master') run('npm install') run('grunt ember_handlebars sass browserify uglify') virtualenv('pip install -r /var/www/twweb/requirements.txt') virtualenv('python manage.py collectstatic --noinput') virtualenv('python manage.py migrate') sudo('chown -R www-data:www-data logs') sudo('/usr/sbin/service twweb restart', shell=False) sudo('/usr/sbin/service twweb-status restart', shell=False) sudo('/usr/sbin/service twweb-celery restart', shell=False) local('git checkout development')
main: Raise exception on empty device name
from .timings import * from .pattern import * from .exceptions import * import serial import logging logger = logging.getLogger(__name__) class HDSignalGenerator(TimingsMixin, PatternMixin): def __init__(self, device): if not device: raise HDSignalGeneratorException("Invalid serial device: %s" % device) self.serial = serial.Serial(device, 19200, 8, 'N', 1, timeout=5) def _execute(self, msg, readsize=6): """Send msg and waits for response of readsize bytes""" logger.debug(">> %s" % msg) self.serial.write(msg) response = self.serial.read(readsize) logger.debug("<< %s" % response) return response def _parsenum(self, msg): return int(msg[3:]) def _formatreq(self, prefix, number): return '%.3s%03.3d' % (prefix, number) def get_firmware_version(self): response = self._execute('VER999') return self._parsenum(response)/10.0
from .timings import * from .pattern import * from .exceptions import * import serial import logging logger = logging.getLogger(__name__) class HDSignalGenerator(TimingsMixin, PatternMixin): def __init__(self, device): self.serial = serial.Serial(device, 19200, 8, 'N', 1, timeout=5) def _execute(self, msg, readsize=6): """Send msg and waits for response of readsize bytes""" logger.debug(">> %s" % msg) self.serial.write(msg) response = self.serial.read(readsize) logger.debug("<< %s" % response) return response def _parsenum(self, msg): return int(msg[3:]) def _formatreq(self, prefix, number): return '%.3s%03.3d' % (prefix, number) def get_firmware_version(self): response = self._execute('VER999') return self._parsenum(response)/10.0
Load the tasks from lib/tasks
var gulp = require('gulp') , path = require('path') , fs = require('fs') , helpers = require(path.resolve(__dirname, 'lib', 'helpers')) require('gulp-help')(gulp, { aliases: ['h'] }) fs .readdirSync(path.resolve(__dirname, 'lib', 'tasks')) .filter(function(file) { return file.indexOf('.') !== 0 }) .map(function(file) { return require(path.resolve(__dirname, 'lib', 'tasks', file)) }) .forEach(function(tasks) { Object.keys(tasks).forEach(function(taskName) { helpers.addTask(gulp, taskName, tasks[taskName]) helpers.addHelp(gulp, taskName, tasks[taskName]) }) })
var gulp = require('gulp') , gutil = require('gulp-util') , help = require('gulp-help') , path = require('path') , packageJson = require(path.resolve(__dirname, 'package.json')) , noop = function(){} help(gulp, { aliases: ['h'] }) gulp.task('version', 'Prints the version number.', [], function() { console.log(packageJson.version) }, { aliases: ['v'] }) gulp.task('init', 'Initializes the project.', function() { }) gulp.task('migrate', 'Run pending migrations.', function() { }) gulp.task('migrate:undo', 'Undo the last migration.', function() { }) gulp.task('migration:create', 'Creates a new migration.', function() { })
Add charset to HTML5 doc (and make more XHTML friendly) git-svn-id: e52e7dec99011c9686d89c3d3c01e7ff0d333eee@2609 eee81c28-f429-11dd-99c0-75d572ba1ddd
<!DOCTYPE html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script> </head><body></body> </html>
<!doctype html> <?php /* * fileopen.php * To be used with ext-server_opensave.js for SVG-edit * * Licensed under the MIT License * * Copyright(c) 2010 Alexis Deveria * */ // Very minimal PHP file, all we do is Base64 encode the uploaded file and // return it to the editor $file = $_FILES['svg_file']['tmp_name']; $output = file_get_contents($file); $type = $_REQUEST['type']; $prefix = ''; // Make Data URL prefix for import image if($type == 'import_img') { $info = getimagesize($file); $prefix = 'data:' . $info['mime'] . ';base64,'; } ?> <script> window.top.window.svgEditor.processFile("<?php echo $prefix . base64_encode($output); ?>", "<?php echo htmlentities($type); ?>"); </script>
Remove arrow functions ... to support older versions of node
'use strict' var isObject = require('is-object') var startsWith = require('starts-with') var startsWithPrefix = function (prefix, key) { return startsWith(key, prefix) } module.exports = function (input, scripts) { var prefixes = input.split('.') var startsWithFilter var isLastPrefix var matches var results var keys // Ensure script begins as an array for interal loop if (!Array.isArray(scripts)) scripts = [scripts] for (var i = 0; i < prefixes.length; i++) { startsWithFilter = startsWithPrefix.bind(null, prefixes[i]) isLastPrefix = i === (prefixes.length - 1) results = [] for (var script of scripts) { keys = Object.keys(script) matches = keys.filter(startsWithFilter).filter(function (key) { // Ignore non-objects unless we're at the last level return isLastPrefix || isObject(script[key]) }) results = results.concat(matches.map(function (match) { return script[match] })) } scripts = results } return results }
'use strict' var isObject = require('is-object') var startsWith = require('starts-with') var startsWithPrefix = (prefix, key) => { return startsWith(key, prefix) } module.exports = (input, scripts) => { var prefixes = input.split('.') var startsWithFilter var isLastPrefix var matches var results var keys // Ensure script begins as an array for interal loop if (!Array.isArray(scripts)) scripts = [scripts] for (var i = 0; i < prefixes.length; i++) { startsWithFilter = startsWithPrefix.bind(null, prefixes[i]) isLastPrefix = i === (prefixes.length - 1) results = [] for (var script of scripts) { keys = Object.keys(script) matches = keys.filter(startsWithFilter).filter(key => { // Ignore non-objects unless we're at the last level return isLastPrefix || isObject(script[key]) }) results = results.concat(matches.map(match => { return script[match] })) } scripts = results } return results }
Use cookieSession instead of normal sessions.
var express = require('express') , http = require('http') , passport = require('passport') , path = require('path') , User = require('./models/User.js'); var app = express(); app.set('views', __dirname + '/app'); app.set('view engine', 'jade'); app.use(express.logger('dev')) app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(path.join(__dirname, 'app'))); app.use(express.cookieSession( { secret: "Superdupersecret" })); app.use(passport.initialize()); app.use(passport.session()); passport.use(User.localStrategy); passport.serializeUser(User.serializeUser); passport.deserializeUser(User.deserializeUser); require('./routes.js')(app); app.set('port', process.env.PORT || 8000); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
var express = require('express') , http = require('http') , passport = require('passport') , path = require('path') , User = require('./models/User.js'); var app = express(); app.set('views', __dirname + '/app'); app.set('view engine', 'jade'); app.use(express.logger('dev')) app.use(express.cookieParser()); app.use(express.bodyParser()); app.use(express.methodOverride()); app.use(express.static(path.join(__dirname, 'app'))); app.use(express.session( { secret: "Superdupersecret"/*, cookie: { maxAge: 3600000 * 24 * 7 } */ })); app.use(passport.initialize()); app.use(passport.session()); passport.use(User.localStrategy); passport.serializeUser(User.serializeUser); passport.deserializeUser(User.deserializeUser); require('./routes.js')(app); app.set('port', process.env.PORT || 8000); http.createServer(app).listen(app.get('port'), function(){ console.log("Express server listening on port " + app.get('port')); });
Remove unused postal field from form
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.innerHTML = ` <input id="stripe-cardnumber" placeholder="cardnumber" size="16" type="text"> <input placeholder="exp-date" size="6" type="text"> <input placeholder="cvc" size="3" type="text"> `; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
class Element { mount(el) { if (typeof el === "string") { el = document.querySelector(el); } el.innerHTML = ` <input id="stripe-cardnumber" placeholder="cardnumber" size="16" type="text"> <input placeholder="exp-date" size="6" type="text"> <input placeholder="cvc" size="3" type="text"> <input placeholder="postal" size="6" type="text"> `; } } window.Stripe = () => { const fetchLastFour = () => { return document.getElementById("stripe-cardnumber").value.substr(-4, 4); }; return { elements: () => { return { create: (type, options) => new Element() }; }, createToken: card => { return new Promise(resolve => { resolve({ token: { id: "tok_123", card: { last4: fetchLastFour() } } }); }); } }; };
Add documentation generation to the deploy step
<?php use Illuminate\Console\Command; class SiteDeployCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'site:deploy'; /** * The console command description. * * @var string */ protected $description = 'Deploy the site on live'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { SSH::run([ "cd " . @$_ENV["SSH_ROOT"], "php artisan down", "git pull origin develop", "composer update", "php artisan up", "aglio -i API.md -o public/docs/index.html", ]); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return []; } /** * Get the console command options. * * @return array */ protected function getOptions() { return []; } }
<?php use Illuminate\Console\Command; class SiteDeployCommand extends Command { /** * The console command name. * * @var string */ protected $name = 'site:deploy'; /** * The console command description. * * @var string */ protected $description = 'Deploy the site on live'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function fire() { SSH::run([ "cd " . @$_ENV["SSH_ROOT"], "php artisan down", "git pull origin develop", "composer update", "php artisan up", ]); } /** * Get the console command arguments. * * @return array */ protected function getArguments() { return []; } /** * Get the console command options. * * @return array */ protected function getOptions() { return []; } }
migrations: Enforce evaluation order in 0306 WHERE clause. Depending on PostgreSQL’s query plan, it was possible for the value condition to be evaluated before the field_type condition was checked, leading to errors like psycopg2.errors.InvalidDatetimeFormat: invalid value "stri" for "YYYY" DETAIL: Value must be an integer. Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
from django.db import migrations class Migration(migrations.Migration): """ We previously accepted invalid ISO 8601 dates like 1909-3-5 for date values of custom profile fields. Correct them by adding the missing leading zeros: 1909-03-05. """ dependencies = [ ("zerver", "0305_realm_deactivated_redirect"), ] operations = [ migrations.RunSQL( sql="""\ UPDATE zerver_customprofilefieldvalue SET value = to_char(to_date(value, 'YYYY-MM-DD'), 'YYYY-MM-DD') FROM zerver_customprofilefield AS f WHERE f.id = field_id AND f.field_type = 4 AND CASE WHEN f.field_type = 4 THEN value <> to_char(to_date(value, 'YYYY-MM-DD'), 'YYYY-MM-DD') END; """, reverse_sql="", ), ]
from django.db import migrations class Migration(migrations.Migration): """ We previously accepted invalid ISO 8601 dates like 1909-3-5 for date values of custom profile fields. Correct them by adding the missing leading zeros: 1909-03-05. """ dependencies = [ ("zerver", "0305_realm_deactivated_redirect"), ] operations = [ migrations.RunSQL( sql="""\ UPDATE zerver_customprofilefieldvalue SET value = to_char(to_date(value, 'YYYY-MM-DD'), 'YYYY-MM-DD') FROM zerver_customprofilefield AS f WHERE f.id = field_id AND f.field_type = 4 AND value <> to_char(to_date(value, 'YYYY-MM-DD'), 'YYYY-MM-DD'); """, reverse_sql="", ), ]
Bring formified inputs into the world of the filter.
$(function(){ $('.more-or-less').each(function(i, el) { console.log(el); $(el).find("li a").click(function() { $(el).find("button").html($(this).text() + ' <span class="caret"></span>'); $(el).find("input.more-or-less-type").val($(this).text()); }); }); $(".formify").each(function (_, element) { var value = $(element).find("[data-selected='true']").first().addClass("active").data("value"); $(element).append('<input class="formify-value" type="hidden" name="filter[' + $(this).data('name') + ']" value="' + value + '" >'); }); $(".formify .btn").click(function () { $(this).addClass("active"); var val = $(this).data("value"); var input = $(this).parent().find(".formify-value") console.log(val) $(input).val(val) }); $(".incident").click(function() { $(this).toggleClass("selected"); }); $(".select-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", true); event.preventDefault(); }); $(".clear-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", false); event.preventDefault(); }); })
$(function(){ $('.more-or-less').each(function(i, el) { console.log(el); $(el).find("li a").click(function() { $(el).find("button").html($(this).text() + ' <span class="caret"></span>'); $(el).find("input.more-or-less-type").val($(this).text()); }); }); $(".formify").each(function (_, element) { var value = $(element).find("[data-selected='true']").first().addClass("active").data("value"); $(element).append('<input class="formify-value" type="hidden" name="' + $(this).data('name') + '" value="' + value + '" >'); }); $(".formify .btn").click(function () { $(this).addClass("active"); var val = $(this).data("value"); var input = $(this).parent().find(".formify-value") console.log(val) $(input).val(val) }); $(".incident").click(function() { $(this).toggleClass("selected"); }); $(".select-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", true); event.preventDefault(); }); $(".clear-all").click(function(event) { $(event.target).parent().parent().find("input").prop("checked", false); event.preventDefault(); }); })
Use Array.from({ length: n }, factory) PR-URL: https://github.com/metarhia/metasync/pull/306
'use strict'; const poolified = Symbol('poolified'); const mixFlag = { [poolified]: true }; const duplicate = (factory, n) => Array .from({ length: n }, factory) .map(instance => Object.assign(instance, mixFlag)); const provide = callback => item => { setImmediate(() => { callback(item); }); }; const poolify = (factory, min, norm, max) => { let allocated = norm; const pool = (par) => { if (par && par[poolified]) { const delayed = pool.delayed.shift(); if (delayed) delayed(par); else pool.items.push(par); return; } if (pool.items.length < min && allocated < max) { const grow = Math.min(max - allocated, norm - pool.items.length); allocated += grow; const items = duplicate(factory, grow); pool.items.push(...items); } const res = pool.items.pop(); if (!par) return res; const callback = provide(par); if (res) callback(res); else pool.delayed.push(callback); }; return Object.assign(pool, { items: duplicate(factory, norm), delayed: [] }); }; module.exports = { poolify, };
'use strict'; const poolified = Symbol('poolified'); const mixFlag = { [poolified]: true }; const duplicate = (factory, n) => ( new Array(n).fill().map(() => { const instance = factory(); return Object.assign(instance, mixFlag); }) ); const provide = callback => item => { setImmediate(() => { callback(item); }); }; const poolify = (factory, min, norm, max) => { let allocated = norm; const pool = (par) => { if (par && par[poolified]) { const delayed = pool.delayed.shift(); if (delayed) delayed(par); else pool.items.push(par); return; } if (pool.items.length < min && allocated < max) { const grow = Math.min(max - allocated, norm - pool.items.length); allocated += grow; const items = duplicate(factory, grow); pool.items.push(...items); } const res = pool.items.pop(); if (!par) return res; const callback = provide(par); if (res) callback(res); else pool.delayed.push(callback); }; return Object.assign(pool, { items: duplicate(factory, norm), delayed: [] }); }; module.exports = { poolify, };
Make the transform cli command work
var fs = require("fs"); var _assign = require("lodash/assign"); var stealTools = require("../../index"); var _clone = require("lodash/cloneDeep"); var makeStealConfig = require("./make_steal_config"); var options = _clone(require("./options")); module.exports = { command: "transform", builder: _assign({}, options, { out: { alias: "o", type: "string", describe: "Specify an output file" }, ignore: { type: "string", describe: "Comma-separated list of modules to not include in the output" } }), describe: "Transform a module to other formats", handler: function(argv) { var ignore = []; var options = argv; var config = makeStealConfig(argv); // ignore would be a comma-separated list like jquery,underscore,moment if (argv.ignore) { ignore = argv.ignore.split(","); } return stealTools.transform(config, options) .then(function(transform){ return transform(null, { ignore: ignore }); }).then(function(result){ var code = result.code; var map = result.map; // Write out the contents fs.writeFileSync(argv.out, code, "utf8"); if (map) { fs.writeFileSync(argv.out + ".map", map.toString(), "utf8"); } }); } };
var fs = require("fs"); var _assign = require("lodash/assign"); var stealTools = require("../../index"); var _clone = require("lodash/cloneDeep"); var makeStealConfig = require("./make_steal_config"); var options = _clone(require("./options")); module.exports = { command: "transform", builder: _assign({}, options, { out: { alias: "o", type: "string", describe: "Specify an output file" }, ignore: { type: "string", describe: "Comma-separated list of modules to not include in the output" } }), describe: "Transform a module to other formats", handler: function(argv) { var ignore = []; var options = argv; var config = makeStealConfig(argv); // ignore would be a comma-separated list like jquery,underscore,moment if (argv.ignore) { ignore = argv.ignore.split(","); } return stealTools.transform(config, options) .then(function(transform){ var result = transform(null, { ignore: ignore }); var code = result.code; var map = result.map; // Write out the contents fs.writeFileSync(argv.out, code, "utf8"); if (map) { fs.writeFileSync(argv.out + ".map", map.toString(), "utf8"); } }); } };
Remove redundant _is_multivariate in ConditionSet Signed-off-by: Harsh Gupta <c4bd8559369e527b4bb1785ff84e8ff50fde87c0@gmail.com>
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
from __future__ import print_function, division from sympy.core.basic import Basic from sympy.logic.boolalg import And, Or, Not, true, false from sympy.sets.sets import (Set, Interval, Intersection, EmptySet, Union, FiniteSet) from sympy.core.singleton import Singleton, S from sympy.core.sympify import _sympify from sympy.core.decorators import deprecated from sympy.core.function import Lambda class ConditionSet(Set): """ Set of elements which satisfies a given condition. {x | condition(x) is True for x in S} Examples ======== >>> from sympy import Symbol, S, CondSet, Lambda, pi, Eq, sin >>> x = Symbol('x') >>> sin_sols = CondSet(Lambda(x, Eq(sin(x), 0)), S.Reals) >>> 2*pi in sin_sols True """ def __new__(cls, lamda, base_set): return Basic.__new__(cls, lamda, base_set) condition = property(lambda self: self.args[0]) base_set = property(lambda self: self.args[1]) def _is_multivariate(self): return len(self.lamda.variables) > 1 def contains(self, other): return And(self.condition(other), self.base_set.contains(other))
Fix test naming spelling errors
def test_rover_init_with_default_parameters(): from rover import Rover rover = Rover() assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' def test_rover_init_with_custom_parameters(): from rover import Rover rover = Rover(3, 7, 'W') assert rover.x == 3 assert rover.y == 7 assert rover.direction == 'W' def test_rover_init_custom_grid(): from rover import Rover rover = Rover(grid_x=100, grid_y=150) assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' assert rover.grid_x == 100 assert rover.grid_y == 150 def test_rover_init_full_custom_grid(): from rover import Rover rover = Rover(5, 9, 'E', 100, 150) assert rover.x == 5 assert rover.y == 9 assert rover.direction == 'E' assert rover.grid_x == 100 assert rover.grid_y == 150
def test_rover_init_with_default_parameters(): from rover import Rover rover = Rover() assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' def test_rover_init_with_custom_paramaters(): from rover import Rover rover = Rover(3, 7, 'W') assert rover.x == 3 assert rover.y == 7 assert rover.direction == 'W' def test_rover_Init_custom_grid(): from rover import Rover rover = Rover(grid_x=100, grid_y=150) assert rover.x == 0 assert rover.y == 0 assert rover.direction == 'N' assert rover.grid_x == 100 assert rover.grid_y == 150 def test_rover_init_full_custom_grid(): from rover import Rover rover = Rover(5, 9, 'E', 100, 150) assert rover.x == 5 assert rover.y == 9 assert rover.direction == 'E' assert rover.grid_x == 100 assert rover.grid_y == 150
Fix route name in unit test
require('rootpath')(); const { describe, it, expect, server } = require('tests/helper'); const route = require('app/features/status'); const { name, version, description } = require('package'); describe('Unit | Route | Status Index ', function() { describe('Server', () => { it('should have an attributes', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('status-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route Get /status', () => { it('should exist', () => { // when server.inject({ method: 'GET', url: '/api/status', payload: {} }, (res) => { // then expect(res.statusCode).to.equal(200); expect(res.result).to.deep.equal({ name, version, description }); }); }); }); });
require('rootpath')(); const { describe, it, expect, server } = require('tests/helper'); const route = require('app/features/status'); const { name, version, description } = require('package'); describe('Unit | Handler | Status Index ', function() { describe('Server', () => { it('should have an attributes', () => { // then expect(route.register.attributes).to.exist; expect(route.register.attributes).to.be.an('object'); expect(route.register.attributes.name).to.equal('status-api'); expect(route.register.attributes).to.have.property('version'); }); }); describe('Route Get /status', () => { it('should exist', () => { // when server.inject({ method: 'GET', url: '/api/status', payload: {} }, (res) => { // then expect(res.statusCode).to.equal(200); expect(res.result).to.deep.equal({ name, version, description }); }); }); }); });
Fix ALL failures in Java
package fp.grados.tipos; import java.time.LocalDate; import java.util.Comparator; import java.util.Map; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; public class AlumnoImpl2 extends AlumnoImpl implements Alumno { public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){ super(DNI, nombre, apellidos, fecha, email); } public AlumnoImpl2(String s) { super(s); } @Override public Integer getCurso() { Integer res = 0; Stream<Asignatura> stream = this.getAsignaturas().stream(); Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso)); if(opt.isPresent()) { res = opt.get().getCurso(); } return res; } public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() { Map<Asignatura, Calificacion> res = getExpediente().getNotas().stream().collect(Collectors.toMap(n -> n.getAsignatura(), n -> n.getCalificacion(), (p1, p2)->calificacionMayor(p1, p2))); return new TreeMap<Asignatura, Calificacion>(res); } private Calificacion calificacionMayor(Calificacion c1, Calificacion c2) { if (c1.compareTo(c2) >= 0) { return c1; } else { return c2; } } }
package fp.grados.tipos; import java.time.LocalDate; import java.util.Comparator; import java.util.Optional; import java.util.SortedMap; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; public class AlumnoImpl2 extends AlumnoImpl implements Alumno { public AlumnoImpl2(String DNI, String nombre, String apellidos, LocalDate fecha, String email){ super(DNI, nombre, apellidos, fecha, email); } public AlumnoImpl2(String s) { super(s); } @Override public Integer getCurso() { Integer res = 0; Stream<Asignatura> stream = this.getAsignaturas().stream(); Optional<Asignatura> opt = stream.max(Comparator.comparing(Asignatura::getCurso)); if(opt.isPresent()) { res = opt.get().getCurso(); } return res; } public SortedMap<Asignatura, Calificacion> getCalificacionPorAsignatura() { return this.getExpediente().getNotas().stream().collect(Collectors.toMap(Nota::getAsignatura, Nota::getCalificacion, (p1, p2) -> p1, TreeMap::new)); } }
Set offset to multiple of NUMBER
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { // Number of entries to be pulled. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. const OFFSET = NUMBER * 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
import * as React from "react"; import {BuildSnapshot} from "./BuildSnapshot"; /** * Container Component for BuildSnapshots. * * @param {*} props input property containing an array of build data to be * rendered through BuildSnapshot. */ export const BuildSnapshotContainer = React.memo((props) => { // Number of entries to be pulled. const NUMBER = 2; // The starting point from which the entries are selected. // Relative to the starting index. const OFFSET = 0; const SOURCE = `/builders/number=${NUMBER}/offset=${OFFSET}`; const [data, setData] = React.useState([]); /** * Fetch data when component is mounted. * Pass in empty array as second paramater to prevent * infinite callbacks as component refreshes. * @see <a href="www.robinwieruch.de/react-hooks-fetch-data">Fetching</a> */ React.useEffect(() => { fetch(SOURCE) .then(res => res.json()) .then(json => setData(json)) .catch(setData([])); }, []); return ( <div> {data.map(snapshotData => <BuildSnapshot buildData={snapshotData}/>)} </div> ); } );
pkg/shell: Add a short delay in signal handling test.
//go:build !windows && !plan9 && !js package shell import ( "fmt" "strings" "syscall" "testing" "time" "src.elv.sh/pkg/must" . "src.elv.sh/pkg/prog/progtest" "src.elv.sh/pkg/testutil" ) func TestSignal_USR1(t *testing.T) { Test(t, &Program{}, ThatElvish("-c", killCmd("USR1")).WritesStderrContaining("src.elv.sh/pkg/shell")) } func TestSignal_Ignored(t *testing.T) { testutil.InTempDir(t) Test(t, &Program{}, ThatElvish("-log", "logCHLD", "-c", killCmd("CHLD")).DoesNothing()) wantLogCHLD := "signal " + syscall.SIGCHLD.String() if logCHLD := must.ReadFileString("logCHLD"); !strings.Contains(logCHLD, wantLogCHLD) { t.Errorf("want log when getting SIGCHLD to contain %q; got:\n%s", wantLogCHLD, logCHLD) } } func killCmd(name string) string { // Add a delay after kill to ensure that the signal is handled. return fmt.Sprintf("kill -%v $pid; sleep %v", name, testutil.Scaled(10*time.Millisecond)) }
//go:build !windows && !plan9 && !js package shell import ( "strings" "syscall" "testing" "src.elv.sh/pkg/must" . "src.elv.sh/pkg/prog/progtest" "src.elv.sh/pkg/testutil" ) func TestSignal_USR1(t *testing.T) { Test(t, &Program{}, ThatElvish("-c", "kill -USR1 $pid").WritesStderrContaining("src.elv.sh/pkg/shell")) } func TestSignal_Ignored(t *testing.T) { testutil.InTempDir(t) Test(t, &Program{}, ThatElvish("-log", "logCHLD", "-c", "kill -CHLD $pid").DoesNothing()) wantLogCHLD := "signal " + syscall.SIGCHLD.String() if logCHLD := must.ReadFileString("logCHLD"); !strings.Contains(logCHLD, wantLogCHLD) { t.Errorf("want log when getting SIGCHLD to contain %q; got:\n%s", wantLogCHLD, logCHLD) } }
Fix date processing on RPL_TOPIC_WHO_TIME
module.exports = function () { return function (irc) { irc.topic = function (channel, topic, fn) { if (typeof topic === 'function') { fn = topic; topic = ''; } this.write('TOPIC ' + channel + (topic && ' :' + topic || ''), fn); }; irc.on('RPL_NOTOPIC', function (msg, channel) { var e = {}; e.target = channel; e.message = null; e.raw = msg.string; irc.emit('topic', e); }); irc.on('RPL_TOPIC', function (msg, channel, topic) { var e = {}; e.target = channel; e.message = topic; e.raw = msg.string; irc.emit('topic', e); }); irc.on('RPL_TOPIC_WHO_TIME', function (msg, channel, nick, time) { irc.emit('topic:time', { target: channel, nick: nick, time: new Date(parseFloat(time)*1000), raw: msg.string }); }); irc.on('TOPIC', function (msg) { var e = {}; e.nick = msg.nick; e.target = msg.params.split(' ')[0]; e.message = msg.trailing; e.raw = msg.string; irc.emit('topic', e); irc.emit('topic:changed', e); }); }; };
module.exports = function () { return function (irc) { irc.topic = function (channel, topic, fn) { if (typeof topic === 'function') { fn = topic; topic = ''; } this.write('TOPIC ' + channel + (topic && ' :' + topic || ''), fn); }; irc.on('RPL_NOTOPIC', function (msg, channel) { var e = {}; e.target = channel; e.message = null; e.raw = msg.string; irc.emit('topic', e); }); irc.on('RPL_TOPIC', function (msg, channel, topic) { var e = {}; e.target = channel; e.message = topic; e.raw = msg.string; irc.emit('topic', e); }); irc.on('RPL_TOPIC_WHO_TIME', function (msg, channel, nick, time) { irc.emit('topic:time', { target: channel, nick: nick, time: new Date(time), raw: msg.string }); }); irc.on('TOPIC', function (msg) { var e = {}; e.nick = msg.nick; e.target = msg.params.split(' ')[0]; e.message = msg.trailing; e.raw = msg.string; irc.emit('topic', e); }); }; };
Disable debug on sample client
"""This example show a full http server. """ from flask import Flask from flask import render_template from flask import request import config from libs.polybanking import PolyBanking import uuid api = PolyBanking(config.POLYBANKING_SERVER, config.CONFIG_ID, config.KEY_REQUESTS, config.KEY_IPN, config.KEY_API) app = Flask(__name__) @app.route("/") def home(): """Display the home page""" return render_template('home.html') @app.route('/start') def start(): """Start a new paiement""" (result, url) = api.new_transaction(request.args.get('amount', ''), str(uuid.uuid4())) return render_template('start.html', result=result, url=url) @app.route('/back') def back(): transaction_list = api.get_transactions(max_transaction=3) transaction_details = api.get_transaction(transaction_list[0]['reference']) transaction_logs = api.get_transaction_logs(transaction_list[0]['reference']) return render_template('back.html', result='ok' in request.args, last_transactions=transaction_list, last_transaction_detail=transaction_details, last_transaction_logs=transaction_logs) @app.route('/ipn', methods=['POST']) def ipn(): print api.check_ipn(request.form) return '' if __name__ == "__main__": app.run(debug=False)
"""This example show a full http server. """ from flask import Flask from flask import render_template from flask import request import config from libs.polybanking import PolyBanking import uuid api = PolyBanking(config.POLYBANKING_SERVER, config.CONFIG_ID, config.KEY_REQUESTS, config.KEY_IPN, config.KEY_API) app = Flask(__name__) @app.route("/") def home(): """Display the home page""" return render_template('home.html') @app.route('/start') def start(): """Start a new paiement""" (result, url) = api.new_transaction(request.args.get('amount', ''), str(uuid.uuid4())) return render_template('start.html', result=result, url=url) @app.route('/back') def back(): transaction_list = api.get_transactions(max_transaction=3) transaction_details = api.get_transaction(transaction_list[0]['reference']) transaction_logs = api.get_transaction_logs(transaction_list[0]['reference']) return render_template('back.html', result='ok' in request.args, last_transactions=transaction_list, last_transaction_detail=transaction_details, last_transaction_logs=transaction_logs) @app.route('/ipn', methods=['POST']) def ipn(): print api.check_ipn(request.form) return '' if __name__ == "__main__": app.run(debug=True)
Update: Update command from 'organize it' to 'organize files'
#!/usr/bin/env node 'use strict'; const yargs = require('yargs'); const chalk = require('chalk'); const Helper = require('./Helper'); const formats = require('./formats'); const helperInstance = new Helper(); const argv = yargs .usage('organize <command>') .command('files', 'Organizes current directory', (yargs) => { let fileNames = helperInstance.getFileNames(process.cwd()); console.log(chalk.green('Scanning')); for (let i = 0; i < fileNames.length; i++) { let fileExtension = helperInstance.getExtension(fileNames[i]).toUpperCase(); for (let type in formats) { if (formats.hasOwnProperty(type) && formats[type].indexOf(fileExtension) >= 0) { helperInstance.organize(process.cwd(), fileNames[i], type); } } } console.log(chalk.green('Done!')); }) .help('h') .alias('h', 'help') .argv;
#!/usr/bin/env node 'use strict'; const yargs = require('yargs'); const chalk = require('chalk'); const Helper = require('./Helper'); const formats = require('./formats'); const helperInstance = new Helper(); const argv = yargs .usage('organize <command>') .command('it', 'Organizes current directory', (yargs) => { let fileNames = helperInstance.getFileNames(process.cwd()); console.log(chalk.green('Scanning')); for (let i = 0; i < fileNames.length; i++) { let fileExtension = helperInstance.getExtension(fileNames[i]).toUpperCase(); for (let type in formats) { if (formats.hasOwnProperty(type) && formats[type].indexOf(fileExtension) >= 0) { helperInstance.organize(process.cwd(), fileNames[i], type); } } } console.log(chalk.green('Done!')); }) .help('h') .alias('h', 'help') .argv;
Fix apc extension checking condition
<?php use Pux\Dispatcher\APCDispatcher; use Pux\Mux; class APCDispatcherTest extends PHPUnit_Framework_TestCase { public function test() { if ( ! extension_loaded('apc') && ! extension_loaded('apcu') ) { skip('APC or APCu extension is required.'); } $mux = new Mux; $mux->add('/product/add', ['ProductController', 'addAction']); $dispatcher = new APCDispatcher($mux, array( 'namespace' => 'tests', 'expiry' => 10, )); ok($dispatcher); $route = $dispatcher->dispatch('/product/add'); ok($route); $route = $dispatcher->dispatch('/product/add'); ok($route); $route = $dispatcher->dispatch('/product/del'); ok($route == false); } }
<?php use Pux\Dispatcher\APCDispatcher; use Pux\Mux; class APCDispatcherTest extends PHPUnit_Framework_TestCase { public function test() { if ( ! extension_loaded('apc') || ! extension_loaded('apcu') ) { skip('APC or APCu extension is required.'); } $mux = new Mux; $mux->add('/product/add', ['ProductController', 'addAction']); $dispatcher = new APCDispatcher($mux, array( 'namespace' => 'tests', 'expiry' => 10, )); ok($dispatcher); $route = $dispatcher->dispatch('/product/add'); ok($route); $route = $dispatcher->dispatch('/product/add'); ok($route); $route = $dispatcher->dispatch('/product/del'); ok($route == false); } }
Change application name in page title
(function () { 'use strict'; angular.module('core') .directive('pageTitle', pageTitle); pageTitle.$inject = ['$rootScope', '$timeout', '$interpolate', '$state']; function pageTitle($rootScope, $timeout, $interpolate, $state) { var directive = { restrict: 'A', link: link }; return directive; function link(scope, element) { $rootScope.$on('$stateChangeSuccess', listener); function listener(event, toState) { var title = (getTitle($state.$current)); $timeout(function () { element.text(title); }, 0, false); } function getTitle(currentState) { var applicationCoreTitle = 'OpenSM'; var workingState = currentState; if (currentState.data) { workingState = (typeof workingState.locals !== 'undefined') ? workingState.locals.globals : workingState; var stateTitle = $interpolate(currentState.data.pageTitle)(workingState); return applicationCoreTitle + ' | ' + stateTitle; } else { return applicationCoreTitle; } } } } }());
(function () { 'use strict'; angular.module('core') .directive('pageTitle', pageTitle); pageTitle.$inject = ['$rootScope', '$timeout', '$interpolate', '$state']; function pageTitle($rootScope, $timeout, $interpolate, $state) { var directive = { restrict: 'A', link: link }; return directive; function link(scope, element) { $rootScope.$on('$stateChangeSuccess', listener); function listener(event, toState) { var title = (getTitle($state.$current)); $timeout(function () { element.text(title); }, 0, false); } function getTitle(currentState) { var applicationCoreTitle = 'Pythia'; var workingState = currentState; if (currentState.data) { workingState = (typeof workingState.locals !== 'undefined') ? workingState.locals.globals : workingState; var stateTitle = $interpolate(currentState.data.pageTitle)(workingState); return applicationCoreTitle + ' | ' + stateTitle; } else { return applicationCoreTitle; } } } } }());
Add emoji handling to push notifications
'use strict' // Load requirements const emoji = require('node-emoji') // Create a pushover instance const pushover = new (require('pushover-notifications'))({ user: process.env.PUSHOVER_USER, token: process.env.PUSHOVER_TOKEN }) // Load utilities const i18n = require('../../locale') const logger = require('../../log') // Get package data const pkg = require('../../../../package') // Send notification to mobile device module.exports = function (msg) { // DEBUG logger.verbose(i18n.t('utils.methods.notify.send', msg)) // Send the message return pushover.send({ message: emoji.emojify(msg), title: pkg.name, sound: 'magic', priority: 1 }, (err, result) => { if (err !== undefined && result && !result.status) { return logger.error(i18n.t('utils.methods.notify.error', msg)) } }) }
'use strict' // Create a pushover instance const pushover = new (require('pushover-notifications'))({ user: process.env.PUSHOVER_USER, token: process.env.PUSHOVER_TOKEN }) // Load utilities const i18n = require('../../locale') const logger = require('../../log') // Get package data const pkg = require('../../../../package') // Send notification to mobile device module.exports = function (msg) { // DEBUG logger.verbose(i18n.t('utils.methods.notify.send', msg)) // Send the message return pushover.send({ message: msg, title: pkg.name, sound: 'magic', priority: 1 }, (err, result) => { if (err !== undefined && result && !result.status) { return logger.error(i18n.t('utils.methods.notify.error', msg)) } }) }
Fix packagename spelling for testing header
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function import os # This is to figure out the astroquery version, rather than using Astropy's from . import version # this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. from astropy.tests.pytest_plugins import * try: packagename = os.path.basename(os.path.dirname(__file__)) TESTED_VERSIONS[packagename] = version.version except NameError: pass # Add astropy to test header information and remove unused packages. # Pytest header customisation was introduced in astropy 1.0. try: PYTEST_HEADER_MODULES['Astropy'] = 'astropy' PYTEST_HEADER_MODULES['APLpy'] = 'aplpy' PYTEST_HEADER_MODULES['pyregion'] = 'pyregion' del PYTEST_HEADER_MODULES['h5py'] del PYTEST_HEADER_MODULES['Scipy'] except NameError: pass
# Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import print_function import os # This is to figure out the astroquery version, rather than using Astropy's from . import version # this contains imports plugins that configure py.test for astropy tests. # by importing them here in conftest.py they are discoverable by py.test # no matter how it is invoked within the source tree. from astropy.tests.pytest_plugins import * try: packagename = os.path.basename(os.path.dirname(__file__)) TESTED_VERSIONS[packagename] = version.version except NameError: pass # Add astropy to test header information and remove unused packages. # Pytest header customisation was introduced in astropy 1.0. try: PYTEST_HEADER_MODULES['Astropy'] = 'astropy' PYTEST_HEADER_MODULES['APLpy'] = 'APLpy' PYTEST_HEADER_MODULES['pyregion'] = 'pyregion' del PYTEST_HEADER_MODULES['h5py'] del PYTEST_HEADER_MODULES['Scipy'] except NameError: pass
Change import path to match GitHub URL
package main import ( "encoding/json" "flag" "io/ioutil" log "github.com/Sirupsen/logrus" "github.com/GinjaNinja32/DisGoIRC/bot" ) func main() { debug := flag.Bool("debug", false, "Debug mode") confLocation := flag.String("config", "conf.json", "Config file location") flag.Parse() if *debug { log.SetLevel(log.DebugLevel) } else { log.SetLevel(log.InfoLevel) } var conf bot.Config confJson, err := ioutil.ReadFile(*confLocation) if err != nil { log.Fatalf("Failed to read config file %s: %s", confLocation, err) } err = json.Unmarshal(confJson, &conf) if err != nil { log.Fatalf("Failed to parse config file: %s", err) } bot.Init(conf) log.Infof("Bot running.") <-make(chan struct{}) return }
package main import ( "encoding/json" "flag" "io/ioutil" log "github.com/Sirupsen/logrus" "github.com/GinjaNinja32/disgoirc/bot" ) func main() { debug := flag.Bool("debug", false, "Debug mode") confLocation := flag.String("config", "conf.json", "Config file location") flag.Parse() if *debug { log.SetLevel(log.DebugLevel) } else { log.SetLevel(log.InfoLevel) } var conf bot.Config confJson, err := ioutil.ReadFile(*confLocation) if err != nil { log.Fatalf("Failed to read config file %s: %s", confLocation, err) } err = json.Unmarshal(confJson, &conf) if err != nil { log.Fatalf("Failed to parse config file: %s", err) } bot.Init(conf) log.Infof("Bot running.") <-make(chan struct{}) return }
Fix fish max lifespan being 300 ticks instead of 300 minutes.
package mariculture.fishery.fish.dna; import mariculture.api.fishery.fish.FishDNA; import mariculture.api.fishery.fish.FishSpecies; import mariculture.core.config.FishMechanics.FussyFish; import net.minecraft.item.ItemStack; public class FishDNALifespan extends FishDNA { @Override public Integer getDNAFromSpecies(FishSpecies species) { return species.getLifeSpan() * 20 * 60; } @Override public ItemStack addDNA(ItemStack stack, Integer data) { super.addDNA(stack, data); stack.stackTagCompound.setInteger("CurrentLife", data); return stack; } @Override public int getCopyChance() { return 12; } public Integer sanitize(Integer i) { return Math.min(360000, Math.max(1, i)); } @Override public Integer getDNA(ItemStack stack) { return sanitize(super.getDNA(stack) + FussyFish.LIFESPAN_BOOSTER); } @Override public Integer getLowerDNA(ItemStack stack) { return sanitize(super.getLowerDNA(stack) + FussyFish.LIFESPAN_BOOSTER); } }
package mariculture.fishery.fish.dna; import mariculture.api.fishery.fish.FishDNA; import mariculture.api.fishery.fish.FishSpecies; import mariculture.core.config.FishMechanics.FussyFish; import net.minecraft.item.ItemStack; public class FishDNALifespan extends FishDNA { @Override public Integer getDNAFromSpecies(FishSpecies species) { return species.getLifeSpan() * 20 * 60; } @Override public ItemStack addDNA(ItemStack stack, Integer data) { super.addDNA(stack, data); stack.stackTagCompound.setInteger("CurrentLife", data); return stack; } @Override public int getCopyChance() { return 12; } public Integer sanitize(Integer i) { return Math.min(300, Math.max(1, i)); } @Override public Integer getDNA(ItemStack stack) { return sanitize(super.getDNA(stack) + FussyFish.LIFESPAN_BOOSTER); } @Override public Integer getLowerDNA(ItemStack stack) { return sanitize(super.getLowerDNA(stack) + FussyFish.LIFESPAN_BOOSTER); } }
Remove left over merge conflict text
"""Base test class with methods implemented for Django testing.""" from django.test import TestCase from django.contrib.auth.models import User from django.test.client import Client from django.utils.translation import activate class BaseTest(SimpleTestCase): """Base test class with methods implemented for Django testing.""" def __init__(self, *args, **kwargs): """Create the BaseTest object by calling the parent's constructor.""" super().__init__(*args, **kwargs) self.language = None @classmethod def setUpClass(cls): """Automatically called before tests in class.""" super(BaseTest, cls).setUpClass() @classmethod def tearDownClass(cls): """Automatically called after each test.""" super(BaseTest, cls).tearDownClass() def setUp(self): """Automatically called before each test. Sets the language if specified and creates a new client. """ if self.language is not None: activate(self.language) self.client = Client() def tearDown(self): """Automatically called after each test. Deletes test user. """ pass
"""Base test class with methods implemented for Django testing.""" from django.test import TestCase from django.contrib.auth.models import User from django.test.client import Client from django.utils.translation import activate <<<<<<< HEAD class BaseTest(SimpleTestCase): """Base test class with methods implemented for Django testing.""" def __init__(self, *args, **kwargs): """Create the BaseTest object by calling the parent's constructor.""" super().__init__(*args, **kwargs) self.language = None @classmethod def setUpClass(cls): """Automatically called before tests in class.""" super(BaseTest, cls).setUpClass() @classmethod def tearDownClass(cls): """Automatically called after each test.""" super(BaseTest, cls).tearDownClass() def setUp(self): """Automatically called before each test. Sets the language if specified and creates a new client. """ if self.language is not None: activate(self.language) self.client = Client() def tearDown(self): """Automatically called after each test. Deletes test user. """ pass
Allow dumping illegal utf-8 contents
import sys import bsddb3 from xclib.utf8 import utf8, unutf8 def perform(args): domain_db = bsddb3.hashopen(args.domain_db, 'c', 0o600) if args.get: print(unutf8(domain_db[utf8(args.get)], 'illegal')) elif args.put: domain_db[utf8(args.put[0])] = args.put[1] elif args.delete: del domain_db[utf8(args.delete)] elif args.unload: for k in list(domain_db.keys()): print('%s\t%s' % (unutf8(k, 'illegal'), unutf8(domain_db[k], 'illegal'))) # Should work according to documentation, but doesn't # for k, v in DOMAIN_DB.iteritems(): # print k, '\t', v elif args.load: for line in sys.stdin: k, v = line.rstrip('\r\n').split('\t', 1) domain_db[utf8(k)] = v domain_db.close() # vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4
import sys import bsddb3 from xclib.utf8 import utf8, unutf8 def perform(args): domain_db = bsddb3.hashopen(args.domain_db, 'c', 0o600) if args.get: print(unutf8(domain_db[utf8(args.get)])) elif args.put: domain_db[utf8(args.put[0])] = args.put[1] elif args.delete: del domain_db[utf8(args.delete)] elif args.unload: for k in list(domain_db.keys()): print('%s\t%s' % (unutf8(k), unutf8(domain_db[k]))) # Should work according to documentation, but doesn't # for k, v in DOMAIN_DB.iteritems(): # print k, '\t', v elif args.load: for line in sys.stdin: k, v = line.rstrip('\r\n').split('\t', 1) domain_db[utf8(k)] = v domain_db.close() # vim: tabstop=8 softtabstop=0 expandtab shiftwidth=4
Remove max amount for jeh in repartitionjehtype
<?php /* * This file is part of the Incipio package. * * (c) Florian Lefevre * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mgate\SuiviBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class RepartitionJEHType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('nbrJEH', 'integer', array('required' => true)) ->add('prixJEH', 'integer', array('required' => true, 'attr' => array('min' => 80))); } public function getName() { return 'Mgate_suivibundle_RepartitionJEHType'; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'Mgate\SuiviBundle\Entity\RepartitionJEH', 'type' => '', 'prospect' => '', 'phases' => '', )); } }
<?php /* * This file is part of the Incipio package. * * (c) Florian Lefevre * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Mgate\SuiviBundle\Form\Type; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class RepartitionJEHType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('nbrJEH', 'integer', array('required' => true)) ->add('prixJEH', 'integer', array('required' => true, 'attr' => array('min' => 80, 'max' => 320))); } public function getName() { return 'Mgate_suivibundle_RepartitionJEHType'; } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults(array( 'data_class' => 'Mgate\SuiviBundle\Entity\RepartitionJEH', 'type' => '', 'prospect' => '', 'phases' => '', )); } }
Fix ReStructuredText extension in Python3 environment
from docutils.core import publish_parts import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_parts(source=source, writer_name='html') return html['html_body'] def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus(plugins={'nib':{}}) return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
from docutils.core import publish_string import coffeescript from scss import Scss from stylus import Stylus from .util import as_unicode def rst_to_html(source): # This code was taken from http://wiki.python.org/moin/ReStructuredText # You may also be interested in http://www.tele3.cz/jbar/rest/about.html html = publish_string(source=source, writer_name='html') return html[html.find('<body>')+6:html.find('</body>')].strip() def coffee_to_js(source): return as_unicode('<script>{js}</script>').format(js=coffeescript.compile(source)) def scss_to_css(source): css = Scss().compile(source).strip() return as_unicode('<style>{css}</style>').format(css=css) def stylus_to_css(source): compiler = Stylus(plugins={'nib':{}}) return as_unicode('<style>{css}</style>').format(css=compiler.compile(source).strip())
Return promise from listen call.
const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor() { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; ctx.body = await client.request(url, options); }); } listen(port = 80, address) { return new Promise((resolve, reject) => { try { this.app.listen(port, address, () => { resolve(); }); } catch (error) { reject(error); } }); } } module.exports = Server;
const Koa = require('koa'); const bodyParser = require('koa-bodyparser'); const request = require('./request'); class Server { constructor() { this.app = new Koa(); this.app.use(async (ctx, next) => { try { await next(); } catch (error) { ctx.status = 400; ctx.body = {error: error.message}; } }); this.app.use(bodyParser({ enableTypes: ['json'], strict: true, })); this.app.use(async (ctx) => { let url = ctx.request.body.url; if (!url) throw new Error('Missing parameter url'); let options = ctx.request.body.options; ctx.body = await client.request(url, options); }); } listen(port = 80, address) { this.app.listen(port, address); } } module.exports = Server;
Remove datatables css from general header, move to cases header git-svn-id: 245d8f85226f8eeeaacc1269b037bb4851d63c96@771 54a900ba-8191-11dd-a5c9-f1483cedc3eb
<!DOCTYPE html> <head> <title>ClinicCases - Online Case Management Software for Law School Clinics</title> <meta name="robots" content="noindex"> <link rel="stylesheet" href="html/css/cm.css" type="text/css"> <link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css"> <link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css"> <script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>
<!DOCTYPE html> <head> <title>ClinicCases - Online Case Management Software for Law School Clinics</title> <meta name="robots" content="noindex"> <link rel="stylesheet" href="html/css/cm.css" type="text/css"> <link rel="stylesheet" href="html/css/cm_tabs.css" type="text/css"> <link rel="stylesheet" href="lib/jqueryui/css/custom-theme/jquery-ui-1.8.9.custom.css" type="text/css"> <link rel="stylesheet" href="lib/DataTables-1.7.5/media/css/data_table.css" type="text/css"> <link rel="stylesheet" href="lib/DataTables-1.7.5/extras/TableTools-2.0.0/media/css/TableTools.css" type="text/css"> <script src="lib/jqueryui/js/jquery-1.4.4.min.js" type="text/javascript"></script> <script src="lib/jqueryui/js/jquery-ui-1.8.9.custom.min.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimer.js" type="text/javascript"></script> <script src="lib/javascripts/jquery.idletimeout.js" type="text/javascript"></script>
Modify the create user table
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('email'); $table->string('first_name'); $table->string('password'); $table->rememberToken(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->timestamps(); $table->string('email')->unique(); $table->string('password', 60); $table->rememberToken(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('users'); } }
Print and return the correct data
''' Execute overstate functions ''' # Import Salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) overstate.stages() salt.output.display_output(overstate.over_run, 'pprint', opts=__opts__) return overstate.over_run def show_stages(env='base', os_fn=None): ''' Display the stage data to be executed ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) salt.output.display_output(overstate.over, 'pprint', opts=__opts__) return overstate.over
''' Execute overstate functions ''' # Import Salt libs import salt.overstate import salt.output def over(env='base', os_fn=None): ''' Execute an overstate sequence to orchestrate the executing of states over a group of systems ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) over_run = overstate.stages() salt.output.display_output(over_run, 'pprint', opts=__opts__) return over_run def show_stages(env='base', os_fn=None): ''' Display the stage data to be executed ''' overstate = salt.overstate.OverState(__opts__, env, os_fn) salt.output.display_output(overstate.over, 'pprint', opts=__opts__) return overstate.over
Enable tests with SpiderMonkey WasmTextToBinary()
/* * Copyright 2017 - 2019 Volker Berlin (i-net software) * * 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 de.inetsoftware.jwebassembly; import java.util.Arrays; import java.util.Collection; /** * @author Volker Berlin */ public enum ScriptEngine { NodeJS, SpiderMonkey, NodeWat, SpiderMonkeyWat, Wat2Wasm, ; public static Collection<ScriptEngine[]> testParams() { ScriptEngine[][] val = { // { ScriptEngine.SpiderMonkey }, // { ScriptEngine.NodeJS }, // { ScriptEngine.NodeWat }, // { ScriptEngine.SpiderMonkeyWat },// { ScriptEngine.Wat2Wasm }, // }; return Arrays.asList(val); } }
/* * Copyright 2017 - 2018 Volker Berlin (i-net software) * * 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 de.inetsoftware.jwebassembly; import java.util.Arrays; import java.util.Collection; /** * @author Volker Berlin */ public enum ScriptEngine { NodeJS, SpiderMonkey, NodeWat, SpiderMonkeyWat, Wat2Wasm, ; public static Collection<ScriptEngine[]> testParams() { ScriptEngine[][] val = { // { ScriptEngine.SpiderMonkey }, // { ScriptEngine.NodeJS }, // { ScriptEngine.NodeWat }, // // { ScriptEngine.SpiderMonkeyWat },// { ScriptEngine.Wat2Wasm }, // }; return Arrays.asList(val); } }