text
stringlengths
16
4.96k
positive
stringlengths
321
2.24k
negative
stringlengths
310
2.21k
Update UT for removed fields
package cli import ( "testing" "github.com/libopenstorage/openstorage/api" "github.com/stretchr/testify/require" ) func TestCmdMarshalProto(t *testing.T) { volumeSpec := &api.VolumeSpec{ Size: 64, Format: api.FSType_FS_TYPE_EXT4, } data := cmdMarshalProto(volumeSpec, false) require.Equal( t, `{ "ephemeral": false, "size": "64", "format": "ext4", "block_size": "0", "ha_level": "0", "cos": "none", "io_profile": "sequential", "dedupe": false, "snapshot_interval": 0, "shared": false, "aggregation_level": 0, "encrypted": false, "passphrase": "", "snapshot_schedule": "", "scale": 0, "sticky": false, "group_enforced": false }`, data, ) }
package cli import ( "testing" "github.com/libopenstorage/openstorage/api" "github.com/stretchr/testify/require" ) func TestCmdMarshalProto(t *testing.T) { volumeSpec := &api.VolumeSpec{ Size: 64, Format: api.FSType_FS_TYPE_EXT4, } data := cmdMarshalProto(volumeSpec, false) require.Equal( t, `{ "ephemeral": false, "size": "64", "format": "ext4", "block_size": "0", "ha_level": "0", "cos": "none", "io_profile": "sequential", "dedupe": false, "snapshot_interval": 0, "shared": false, "aggregation_level": 0, "encrypted": false, "passphrase": "", "snapshot_schedule": "", "scale": 0, "sticky": false, "max_backups": 0, "backup_schedule": "", "group_enforced": false }`, data, ) }
Fix compile error in tests.
package com.codingchili.core.logging; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import com.codingchili.core.context.ServiceContext; import com.codingchili.core.testing.ContextMock; import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING; /** * @author Robin Duda * * Verify that the remote logger is pushing events to a remote. */ @RunWith(VertxUnitRunner.class) public class RemoteLoggerTest { private ServiceContext context; @Before public void setUp() { context = new ContextMock(Vertx.vertx()); } @After public void tearDown(TestContext test) { context.vertx().close(test.asyncAssertSuccess()); } @Test public void testLogRemote(TestContext test) { mockNode(test.async()); new RemoteLogger(context).log("text"); } private void mockNode(Async async) { context.bus().consumer(NODE_LOGGING).handler(message -> { async.complete(); }); } }
package com.codingchili.core.logging; import io.vertx.core.Vertx; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import org.junit.*; import org.junit.runner.RunWith; import com.codingchili.core.context.SystemContext; import com.codingchili.core.testing.ContextMock; import static com.codingchili.core.configuration.CoreStrings.NODE_LOGGING; /** * @author Robin Duda * * Verify that the remote logger is pushing events to a remote. */ @RunWith(VertxUnitRunner.class) public class RemoteLoggerTest { private SystemContext context; @Before public void setUp() { context = new ContextMock(Vertx.vertx()); } @After public void tearDown(TestContext test) { context.vertx().close(test.asyncAssertSuccess()); } @Test public void testLogRemote(TestContext test) { mockNode(test.async()); new RemoteLogger(context).log("text"); } private void mockNode(Async async) { context.bus().consumer(NODE_LOGGING).handler(message -> { async.complete(); }); } }
Correct code to match db scheme
var express = require('express'); var mysql = require('mysql'); var app = express(); app.use(express.static('public')); var connection = mysql.createConnection({ host : process.env.MYSQL_HOST ||, user : process.env.MYSQL_USER ||, password : process.env.MYSQL_PASS ||, database : process.env.MYSQL_DB || }); connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); app.get('/getVisits', function(req,res){ var nVisits = 0; connection.query('SELECT value FROM stats WHERE stats.id_stat=\'visits\'', function (error, results, fields) { if (error) throw error; console.log(results[0].value); nVisits = results[0].value + 1; res.send(JSON.stringify(nVisits)); var sql = 'UPDATE stats SET value=' + nVisits + ' WHERE id_stat=\'visits\''; connection.query(sql, function (error, results, fields) { if (error) throw error; }); }); }); var server = app.listen(process.env.PORT || 8080, function(){ var port = server.address().port; var host = server.address().address; console.log("Server running on http://" + host + ":" +port); });
var express = require('express'); var mysql = require('mysql'); var app = express(); app.use(express.static('public')); var connection = mysql.createConnection({ host : process.env.MYSQL_HOST, user : process.env.MYSQL_USER, password : process.env.MYSQL_PASS, database : process.env.MYSQL_DB }); connection.connect(function(err) { if (err) { console.error('error connecting: ' + err.stack); return; } console.log('connected as id ' + connection.threadId); }); app.get('/getVisits', function(req,res){ var nVisits = 0; connection.query('SELECT visits FROM stats', function (error, results, fields) { if (error) throw error; nVisits = results + 1; res.end(JSON.stringify(nVisits)); console.log("GetVisits: " + nVisits); connection.query('UPDATE stats SET ?', {visits: nVisits}, function (error, results, fields) { if (error) throw error; }); }); }); var server = app.listen(process.env.PORT || 8080, function(){ var port = server.address().port; var host = server.address().address; console.log("Server running on http://" + host + ":" +port); });
Update service to use new IoC container.
<?php namespace Craft; class SmartdownService extends BaseApplicationComponent { /** * @var \Experience\Smartdown\App\Utilities\Parser; */ protected $parser; /** * Initialises the parser instance. */ public function __construct() { $this->parser = SmartdownPlugin::$container->get('Parser'); } /** * Runs the given string through all of the available parsers. * * @param $source * * @return string */ public function parseAll($source) { return $this->parser->parseAll($source); } /** * Runs the given string through "markup" parser. * * @param $source * * @return string */ public function parseMarkup($source) { return $this->parser->parseMarkup($source); } /** * Runs the given string through "typography" parser. * * @param string $source * * @return string */ public function parseTypography($source) { return $this->parser->parseTypography($source); } }
<?php namespace Craft; class SmartdownService extends BaseApplicationComponent { protected $parser; /** * Initialises the parser instance. */ public function __construct() { $this->parser = smartdown()->parser; } /** * Runs the given string through all of the available parsers. * * @param $source * * @return string */ public function parseAll($source) { return $this->parser->parseAll($source); } /** * Runs the given string through "markup" parser. * * @param $source * * @return string */ public function parseMarkup($source) { return $this->parser->parseMarkup($source); } /** * Runs the given string through "typography" parser. * * @param string $source * * @return string */ public function parseTypography($source) { return $this->parser->parseTypography($source); } }
Add some more comments to the example
/* A bot that welcomes new guild members when they join */ // Import the discord.js module const Discord = require('discord.js'); // Create an instance of a Discord Client const client = new Discord.Client(); // The token of your bot - https://discordapp.com/developers/applications/me const token = 'your bot token here'; // The ready event is vital, it means that your bot will only start reacting to information // from Discord _after_ ready is emitted client.on('ready', () => { console.log('I am ready!'); }); // Create an event listener for new guild members client.on('guildMemberAdd', member => { // Send the message, mentioning the member to the guilds default channel (usually #general) member.guild.defaultChannel.send(`Welcome to the server, ${member}!`); // If you want to send the message to a designated channel on a server instead // you can do the following: const channel = member.guild.channels.find('name', 'member-log'); // Do nothing if the channel wasn't found on this server if (!channel) return; // Send the message, mentioning the member channel.send(`Welcome to the server, ${member}`); }); // Log our bot in client.login(token);
/* A bot that welcomes new guild members when they join */ // Import the discord.js module const Discord = require('discord.js'); // Create an instance of a Discord Client const client = new Discord.Client(); // The token of your bot - https://discordapp.com/developers/applications/me const token = 'your bot token here'; // The ready event is vital, it means that your bot will only start reacting to information // from Discord _after_ ready is emitted client.on('ready', () => { console.log('I am ready!'); }); // Create an event listener for new guild members client.on('guildMemberAdd', member => { // Send the message, mentioning the member member.guild.defaultChannel.send(`Welcome to the server, ${member}!`); // If you want to send the message to a designated channel on a server instead // you can do the following: const channel = member.guild.channels.find('name', 'member-log'); // Do nothing if the channel wasn't found on this server if (!channel) return; channel.send(`Welcome to the server, ${member}`); }); // Log our bot in client.login(token);
Test for setOption in AdapterAbstract
<?php namespace Versionable\Tests\Prospect\Adapter; use Versionable\Prospect\Adapter\AdapterAbstract; /** * Test class for AdapterAbstract. * Generated by PHPUnit on 2011-04-08 at 08:43:07. */ class AdapterAbstractTest extends \PHPUnit_Framework_TestCase { /** * @var AdapterAbstract */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = $this->getMockForAbstractClass('Versionable\Prospect\Adapter\AdapterAbstract'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @todo Implement testSetOption(). */ public function testSetOption() { $this->object->setOption('foo', 'bar'); $attrs = $this->readAttribute($this->object, 'options'); $this->assertEquals('bar', $attrs['foo']); } }
<?php namespace Versionable\Tests\Prospect\Adapter; use Versionable\Prospect\Adapter\AdapterAbstract; /** * Test class for AdapterAbstract. * Generated by PHPUnit on 2011-04-08 at 08:43:07. */ class AdapterAbstractTest extends \PHPUnit_Framework_TestCase { /** * @var AdapterAbstract */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = $this->getMockForAbstractClass('Versionable\Prospect\Adapter\AdapterAbstract'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed. */ protected function tearDown() { } /** * @todo Implement testSetOption(). */ public function testSetOption() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } } ?>
FIX Ensure required HTTPRequest arguments are provided
<?php /** * Composer update checker job. Runs the check as a queuedjob. * * @author Peter Thaleikis * @license MIT */ class CheckComposerUpdatesJob extends AbstractQueuedJob implements QueuedJob { /** * The task to run * * @var BuildTask */ protected $task; /** * define the title * * @return string */ public function getTitle() { return _t( 'ComposerUpdateChecker.Title', 'Check if composer updates are available' ); } /** * define the type. */ public function getJobType() { $this->totalSteps = 1; return QueuedJob::QUEUED; } /** * init */ public function setup() { // create the instance of the task $this->task = new CheckComposerUpdatesTask(); } /** * processes the task as a job */ public function process() { // run the task $this->task->run(new SS_HTTPRequest('GET', '/')); // mark job as completed $this->isComplete = true; } }
<?php /** * Composer update checker job. Runs the check as a queuedjob. * * @author Peter Thaleikis * @license MIT */ class CheckComposerUpdatesJob extends AbstractQueuedJob implements QueuedJob { /** * The task to run * * @var BuildTask */ protected $task; /** * define the title * * @return string */ public function getTitle() { return _t( 'ComposerUpdateChecker.Title', 'Check if composer updates are available' ); } /** * define the type. */ public function getJobType() { $this->totalSteps = 1; return QueuedJob::QUEUED; } /** * init */ public function setup() { // create the instance of the task $this->task = new CheckComposerUpdatesTask(); } /** * processes the task as a job */ public function process() { // run the task $this->task->run(new SS_HTTPRequest()); // mark job as completed $this->isComplete = true; } }
Improve determination of array shape for constant expressions When Evaluating a constant expression, I only used to look at the first column in the df dictionary. But that could also be a constant or expression. So look instead at all columns and find the first numpy array.
import numpy as np import numpy.ma as ma import projections.r2py.reval as reval import projections.r2py.rparser as rparser class SimpleExpr(): def __init__(self, name, expr): self.name = name self.tree = reval.make_inputs(rparser.parse(expr)) lokals = {} exec(reval.to_py(self.tree, name), lokals) self.func = lokals[name + '_st'] @property def syms(self): return reval.find_inputs(self.tree) def eval(self, df): try: res = self.func(df) except KeyError as e: print("Error: input '%s' not defined" % e) raise e if not isinstance(res, np.ndarray): arrays = filter(lambda v: isinstance(v, np.ndarray), df.values()) res = ma.masked_array(np.full(tuple(arrays)[0].shape, res, dtype=np.float32)) return res
import numpy as np import numpy.ma as ma import projections.r2py.reval as reval import projections.r2py.rparser as rparser class SimpleExpr(): def __init__(self, name, expr): self.name = name self.tree = reval.make_inputs(rparser.parse(expr)) lokals = {} exec(reval.to_py(self.tree, name), lokals) self.func = lokals[name + '_st'] @property def syms(self): return reval.find_inputs(self.tree) def eval(self, df): try: res = self.func(df) except KeyError as e: print("Error: input '%s' not defined" % e) raise e if not isinstance(res, np.ndarray): res = ma.masked_array(np.full(tuple(df.values())[0].shape, res, dtype=np.float32)) return res
Move ProgramLine style into head
import React from 'react' import PropTypes from 'prop-types' import Moment from 'react-moment' import Link from 'next/link' import Head from 'next/head' import generateUrl from 'utils/urlGenerator' import EditButton from 'containers/EditButton' import stylesheet from './style.scss' const ProgramLine = (props) => ( <div className='program-line'> <Head> <style dangerouslySetInnerHTML={{ __html: stylesheet }} /> </Head> <div className='columns is-shadowless'> <div className='column is-narrow'> <Moment format='DD/MM/YYYY' unix>{Math.trunc(props.date / 1000)}</Moment> </div> <div className='column is-expanded'> <Link href={`/program?id=${props.id}`} as={`/program/${props.id}`}><a>{props.title}</a></Link> </div> <div className='column is-narrow'> <EditButton id={props.id} /> </div> <div className='column is-narrow'> <a href={generateUrl(props.url)}><i className='fa fa-download' /></a> </div> </div> </div> ) ProgramLine.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string, date: PropTypes.number, url: PropTypes.string } export default ProgramLine
import React from 'react' import PropTypes from 'prop-types' import Moment from 'react-moment' import Link from 'next/link' import generateUrl from 'utils/urlGenerator' import EditButton from 'containers/EditButton' import stylesheet from './style.scss' const ProgramLine = (props) => ( <div className='program-line'> <style dangerouslySetInnerHTML={{ __html: stylesheet }} /> <div className='columns is-shadowless'> <div className='column is-narrow'> <Moment format='DD/MM/YYYY' unix>{Math.trunc(props.date / 1000)}</Moment> </div> <div className='column is-expanded'> <Link href={`/program?id=${props.id}`} as={`/program/${props.id}`}><a>{props.title}</a></Link> </div> <div className='column is-narrow'> <EditButton id={props.id} /> </div> <div className='column is-narrow'> <a href={generateUrl(props.url)}><i className='fa fa-download' /></a> </div> </div> </div> ) ProgramLine.propTypes = { id: PropTypes.string.isRequired, title: PropTypes.string, date: PropTypes.number, url: PropTypes.string } export default ProgramLine
Set status 500 on error
<?php namespace Stratify\ErrorHandlerModule; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Whoops\Handler\PrettyPageHandler; use Whoops\Run; class ErrorHandlerMiddleware { private $whoops; public function __invoke( ServerRequestInterface $request, ResponseInterface $response, callable $next ) : ResponseInterface { try { return $next($request, $response); } catch (\Exception $e) { if (! $this->whoops) { $this->whoops = new Run(); $this->whoops->writeToOutput(false); $this->whoops->allowQuit(false); $this->whoops->pushHandler(new PrettyPageHandler); } $output = $this->whoops->handleException($e); $response->getBody()->write($output); return $response->withStatus(500); } } }
<?php namespace Stratify\ErrorHandlerModule; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Whoops\Handler\PrettyPageHandler; use Whoops\Run; class ErrorHandlerMiddleware { private $whoops; public function __invoke( ServerRequestInterface $request, ResponseInterface $response, callable $next ) : ResponseInterface { try { return $next($request, $response); } catch (\Exception $e) { if (! $this->whoops) { $this->whoops = new Run(); $this->whoops->writeToOutput(false); $this->whoops->allowQuit(false); $this->whoops->pushHandler(new PrettyPageHandler); } $output = $this->whoops->handleException($e); $response->getBody()->write($output); return $response; } } }
Make sitemap file names static, move metadata to redis
// Collect urls to include in sitemap // 'use strict'; const pump = require('pump'); const through2 = require('through2'); module.exports = function (N, apiPath) { N.wire.on(apiPath, function get_users_sitemap(data) { let stream = pump( N.models.users.User.collection .find({ exists: true }, { hid: 1, last_active_ts: 1 }) .sort({ hid: 1 }) .stream(), through2.obj(function (user, encoding, callback) { this.push({ loc: N.router.linkTo('users.member', { user_hid: user.hid }), lastmod: user.last_active_ts }); callback(); }) ); data.streams.push({ name: 'users', stream }); }); };
// Collect urls to include in sitemap // 'use strict'; const pump = require('pump'); const through2 = require('through2'); module.exports = function (N, apiPath) { N.wire.on(apiPath, function get_users_sitemap(data) { data.streams.push( pump( N.models.users.User.collection .find({ exists: true }, { hid: 1, last_active_ts: 1 }) .sort({ hid: 1 }) .stream(), through2.obj(function (user, encoding, callback) { this.push({ loc: N.router.linkTo('users.member', { user_hid: user.hid }), lastmod: user.last_active_ts }); callback(); }) ) ); }); };
Solve small issue with ifs
package model.solvers.problems; import model.population.Population; import model.population.PopulationFactory; import model.solvers.fitness.Fitness; public class MultiplexProblem extends Problem { private int numA; private int creationMethod; private int maxDepth; private boolean ifsAllowed; public MultiplexProblem(int populationSize, int numberGenerations, Fitness fitness, int numA, int treeCreationMethod, boolean ifsAllowed, int maxTreeDepth) { super(populationSize, numberGenerations, fitness, 1, true); this.numA = numA; this.creationMethod = treeCreationMethod; this.ifsAllowed = ifsAllowed; this.maxDepth = maxTreeDepth; } @Override public Population createRandomPopulation(int seed) { switch(creationMethod) { case 0: return PopulationFactory.createProgramIncremental(ifsAllowed, maxDepth, populationSize, numA); case 1: return PopulationFactory.createProgramComplete(ifsAllowed, maxDepth, populationSize, numA); case 2: return PopulationFactory.createProgramRampAndHalf(ifsAllowed, maxDepth, populationSize, numA); case 3: return PopulationFactory.createProgramWeighed(ifsAllowed, maxDepth, populationSize, numA); default: throw new RuntimeException("No known tree creation method selected"); } } }
package model.solvers.problems; import model.population.Population; import model.population.PopulationFactory; import model.solvers.fitness.Fitness; public class MultiplexProblem extends Problem { private int numA; private int creationMethod; private int maxDepth; private boolean ifsAllowed; public MultiplexProblem(int populationSize, int numberGenerations, Fitness fitness, int numA, int treeCreationMethod, boolean ifsAllowed, int maxTreeDepth) { super(populationSize, numberGenerations, fitness, 1, true); this.numA = numA; this.creationMethod = treeCreationMethod; this.ifsAllowed = false; this.maxDepth = maxTreeDepth; } @Override public Population createRandomPopulation(int seed) { switch(creationMethod) { case 0: return PopulationFactory.createProgramIncremental(ifsAllowed, maxDepth, populationSize, numA); case 1: return PopulationFactory.createProgramComplete(ifsAllowed, maxDepth, populationSize, numA); case 2: return PopulationFactory.createProgramRampAndHalf(ifsAllowed, maxDepth, populationSize, numA); case 3: return PopulationFactory.createProgramWeighed(ifsAllowed, maxDepth, populationSize, numA); default: throw new RuntimeException("No known tree creation method selected"); } } }
Fix for demo controller not always updating the page
function ctrl($rootScope) { if(!$rootScope.initialized) { $rootScope.initialized = true; $rootScope.$on('ADE-start', function(e,data) { $rootScope.lastMessage = 'started edit'; }); $rootScope.$on('ADE-finish', function(e,data) { console.log(data); var exit = 'Exited via clicking outside'; switch (data.exit) { case 1: exit = 'Exited via tab'; break; case -1: exit = 'Exited via shift+tab'; break; case 2: exit = 'Exited via return'; break; case -2: exit = 'Exited via shift+return'; break; case 3: exit = 'Exited via esc key'; break; } var oldvalue = data.oldVal; var newvalue = data.newVal; //convert arrays to strings so I can compare them for changes. if (angular.isArray(data.oldVal)) oldvalue = data.oldVal.toString(); if (angular.isArray(data.newVal)) newValue = data.newVal.toString(); $rootScope.lastMessage = 'Finished edit without changes. '+ exit; if (oldvalue != newvalue) { $rootScope.lastMessage = 'Finished edit with changes. Was: '+ data.oldVal + '. Now: '+ data.newVal + '. '+ exit; } $rootScope.$digest(); }); } }
function ctrl($rootScope) { if(!$rootScope.initialized) { $rootScope.initialized = true; $rootScope.$on('ADE-start', function(e,data) { $rootScope.lastMessage = 'started edit'; }); $rootScope.$on('ADE-finish', function(e,data) { console.log(data); var exit = 'Exited via clicking outside'; switch (data.exit) { case 1: exit = 'Exited via tab'; break; case -1: exit = 'Exited via shift+tab'; break; case 2: exit = 'Exited via return'; break; case -2: exit = 'Exited via shift+return'; break; case 3: exit = 'Exited via esc key'; break; } var oldvalue = data.oldVal; var newvalue = data.newVal; //convert arrays to strings so I can compare them for changes. if (angular.isArray(data.oldVal)) oldvalue = data.oldVal.toString(); if (angular.isArray(data.newVal)) newValue = data.newVal.toString(); $rootScope.lastMessage = 'Finished edit without changes. '+ exit; if (oldvalue != newvalue) { $rootScope.lastMessage = 'Finished edit with changes. Was: '+ data.oldVal + '. Now: '+ data.newVal + '. '+ exit; } }); } }
Add DatabaseError to list of errors that kill a historian
from flow import exit_codes from flow.configuration.settings.injector import setting from flow.handler import Handler from flow.util.exit import exit_process from flow_workflow.historian.messages import UpdateMessage from injector import inject from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError from twisted.internet import defer import flow.interfaces import logging import os LOG = logging.getLogger(__name__) @inject(storage=flow.interfaces.IStorage, queue_name=setting('workflow.historian.queue')) class WorkflowHistorianMessageHandler(Handler): message_class = UpdateMessage def _handle_message(self, message): message_dict = message.to_dict() LOG.info("Updating [net_key='%s', operation_id='%s']: %r", message.net_key, message.operation_id, message_dict) try: self.storage.update(message_dict) return defer.succeed(None) except (ResourceClosedError, TimeoutError, DisconnectionError, DatabaseError): LOG.exception("This historian cannot handle messages anymore, " "because it lost access to Oracle... exiting.") exit_process(exit_codes.EXECUTE_FAILURE)
from flow import exit_codes from flow.configuration.settings.injector import setting from flow.handler import Handler from flow.util.exit import exit_process from flow_workflow.historian.messages import UpdateMessage from injector import inject from sqlalchemy.exc import ResourceClosedError, TimeoutError, DisconnectionError from twisted.internet import defer import flow.interfaces import logging import os LOG = logging.getLogger(__name__) @inject(storage=flow.interfaces.IStorage, queue_name=setting('workflow.historian.queue')) class WorkflowHistorianMessageHandler(Handler): message_class = UpdateMessage def _handle_message(self, message): message_dict = message.to_dict() LOG.info("Updating [net_key='%s', operation_id='%s']: %r", message.net_key, message.operation_id, message_dict) try: self.storage.update(message_dict) return defer.succeed(None) except (ResourceClosedError, TimeoutError, DisconnectionError): LOG.exception("This historian cannot handle messages anymore, " "because it lost access to Oracle... exiting.") exit_process(exit_codes.EXECUTE_FAILURE)
Fix incorrect import in CLI file
#!/usr/bin/env node /* eslint-disable no-negated-condition */ 'use strict'; const meow = require('meow'); const chalk = require('chalk'); const scow = require('..'); const cli = meow(` Usage $ scow <input> <output> Options -c, --compress Compress HTML Examples $ scow emails/*.html dist `, { flags: { compress: { type: 'boolean', alias: 'c' } } }); // Must provide input and output if (cli.input.length < 2) { cli.showHelp(1); } const opts = { compress: cli.flags.compress }; scow(cli.input[0], cli.input[1], opts).then(paths => { console.log(chalk.green(`${paths.length} bundle${paths.length !== 1 ? 's' : 's'} created.`)); paths.map(path => console.log(chalk.gray(` ${path}`))); }).catch(error => { console.log(error); });
#!/usr/bin/env node /* eslint-disable no-negated-condition */ 'use strict'; const meow = require('meow'); const chalk = require('chalk'); const scow = require('.'); const cli = meow(` Usage $ scow <input> <output> Options -c, --compress Compress HTML Examples $ scow emails/*.html dist `, { flags: { compress: { type: 'boolean', alias: 'c' } } }); // Must provide input and output if (cli.input.length < 2) { cli.showHelp(1); } const opts = { compress: cli.flags.compress }; scow(cli.input[0], cli.input[1], opts).then(paths => { console.log(chalk.green(`${paths.length} bundle${paths.length !== 1 ? 's' : 's'} created.`)); paths.map(path => console.log(chalk.gray(` ${path}`))); }).catch(error => { console.log(error); });
Cut indiehackers parser | Add hackernews parser
// The schedule object saves the times at which each source bundle should be updated // Documentation on how to write crontab: http://crontab.org/ const schedules = [ // { // source: 'elmundo', // hourFreq: '*', // timeZone: 'America/Los_Angeles' // }, // { // source: 'hackernews', // hourFreq: '*/2', // timeZone: 'America/Los_Angeles' // }, // { // source: 'newyorktimes', // hourFreq: '*/6', // timeZone: 'America/Los_Angeles' // }, // { // source: 'indiehackers', // hourFreq: '*/3', // timeZone: 'America/Los_Angeles' // }, { source: 'askhackernews', hourFreq: '*', timeZone: 'America/Los_Angeles' }, { source: 'hackernews', hourFreq: '*', timeZone: 'America/Los_Angeles' } ] export default schedules;
// The schedule object saves the times at which each source bundle should be updated // Documentation on how to write crontab: http://crontab.org/ const schedules = [ // { // source: 'elmundo', // hourFreq: '*', // timeZone: 'America/Los_Angeles' // }, // { // source: 'hackernews', // hourFreq: '*/2', // timeZone: 'America/Los_Angeles' // }, // { // source: 'newyorktimes', // hourFreq: '*/6', // timeZone: 'America/Los_Angeles' // }, { source: 'indiehackers', hourFreq: '*/3', timeZone: 'America/Los_Angeles' }, { source: 'askhackernews', hourFreq: '*', timeZone: 'America/Los_Angeles' }, { source: 'hackernews', hourFreq: '*', timeZone: 'America/Los_Angeles' } ] export default schedules;
Fix checking if a path is absolute in windows.
/******************************************************************************* * Copyright 2014 Rafael Garcia Moreno. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.bladecoder.engine.assets; import java.io.File; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; public class BasePathResolver implements FileHandleResolver { String basePath; @Override public FileHandle resolve(String fileName) { String fullName; if (new File(fileName).isAbsolute()) { fullName = fileName; } else { StringBuilder sb = new StringBuilder(); sb.append(basePath); sb.append("/"); sb.append(fileName); fullName = sb.toString(); } //EngineLogger.debug(fullName); return Gdx.files.absolute(fullName); } public BasePathResolver(String base) { basePath = base; } }
/******************************************************************************* * Copyright 2014 Rafael Garcia Moreno. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.bladecoder.engine.assets; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.assets.loaders.FileHandleResolver; import com.badlogic.gdx.files.FileHandle; public class BasePathResolver implements FileHandleResolver { String basePath; @Override public FileHandle resolve(String fileName) { String fullName; if (fileName.startsWith("/")) { fullName = fileName; } else { StringBuilder sb = new StringBuilder(); sb.append(basePath); sb.append("/"); sb.append(fileName); fullName = sb.toString(); } //EngineLogger.debug(fullName); return Gdx.files.absolute(fullName); } public BasePathResolver(String base) { basePath = base; } }
Stop throwing yellew boxes when we warn from native Summary: This caused a bunch of stuff to break, reverting and will fix the problems before committing next time. Reviewed By: fkgozali Differential Revision: D4363398 fbshipit-source-id: 55146c9da998f6a3883307c36422a9d440ea7f52
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RCTLog * @flow */ 'use strict'; var BatchedBridge = require('BatchedBridge'); var invariant = require('fbjs/lib/invariant'); var levelsMap = { log: 'log', info: 'info', warn: 'warn', error: 'error', fatal: 'error', }; class RCTLog { // level one of log, info, warn, error, mustfix static logIfNoNativeHook() { var args = Array.prototype.slice.call(arguments); var level = args.shift(); var logFn = levelsMap[level]; invariant( logFn, 'Level "' + level + '" not one of ' + Object.keys(levelsMap) ); if (typeof global.nativeLoggingHook === 'undefined') { // We already printed in xcode, so only log here if using a js debugger console[logFn].apply(console, args); } return true; } } BatchedBridge.registerCallableModule( 'RCTLog', RCTLog ); module.exports = RCTLog;
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule RCTLog * @flow */ 'use strict'; var BatchedBridge = require('BatchedBridge'); var invariant = require('fbjs/lib/invariant'); var levelsMap = { log: 'log', info: 'info', warn: 'warn', error: 'error', fatal: 'error', }; class RCTLog { // level one of log, info, warn, error, mustfix static logIfNoNativeHook() { var args = Array.prototype.slice.call(arguments); var level = args.shift(); var logFn = levelsMap[level]; invariant( logFn, 'Level "' + level + '" not one of ' + Object.keys(levelsMap) ); if (typeof global.nativeLoggingHook === 'undefined' || level === 'warn') { // We already printed in xcode, so only log here if using a js debugger // or if we're trying to send a yellow box from native down. console[logFn].apply(console, args); } return true; } } BatchedBridge.registerCallableModule( 'RCTLog', RCTLog ); module.exports = RCTLog;
Fix indentation to be a multiple of 4
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type class Attribute: def __init__(self, isa=None, private=False, default=None, required=False, listof=None, priority=0, always_post_validate=False): self.isa = isa self.private = private self.default = default self.required = required self.listof = listof self.priority = priority self.always_post_validate = always_post_validate def __cmp__(self, other): return cmp(other.priority, self.priority) class FieldAttribute(Attribute): pass
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type class Attribute: def __init__(self, isa=None, private=False, default=None, required=False, listof=None, priority=0, always_post_validate=False): self.isa = isa self.private = private self.default = default self.required = required self.listof = listof self.priority = priority self.always_post_validate = always_post_validate def __cmp__(self, other): return cmp(other.priority, self.priority) class FieldAttribute(Attribute): pass
Use Model.remoteMethod instead of loopback's fn. Rework Todo model to define the remote method `stats` using the new method `Model.remoteMethod` instead of the deprecated `loopback.remoteMethod`.
var loopback = require('loopback'); var async = require('async'); module.exports = function(Todo/*, Base*/) { Todo.definition.properties.created.default = Date.now; Todo.beforeSave = function(next, model) { if (!model.id) model.id = 't-' + Math.floor(Math.random() * 10000).toString(); next(); }; Todo.stats = function(filter, cb) { var stats = {}; cb = arguments[arguments.length - 1]; var Todo = this; async.parallel([ countComplete, count ], function(err) { if (err) return cb(err); stats.remaining = stats.total - stats.completed; cb(null, stats); }); function countComplete(cb) { Todo.count({completed: true}, function(err, count) { stats.completed = count; cb(err); }); } function count(cb) { Todo.count(function(err, count) { stats.total = count; cb(err); }); } }; Todo.remoteMethod('stats', { accepts: {arg: 'filter', type: 'object'}, returns: {arg: 'stats', type: 'object'}, http: { path: '/stats' } }, Todo.stats); };
var loopback = require('loopback'); var async = require('async'); module.exports = function(Todo/*, Base*/) { Todo.definition.properties.created.default = Date.now; Todo.beforeSave = function(next, model) { if (!model.id) model.id = 't-' + Math.floor(Math.random() * 10000).toString(); next(); }; Todo.stats = function(filter, cb) { var stats = {}; cb = arguments[arguments.length - 1]; var Todo = this; async.parallel([ countComplete, count ], function(err) { if (err) return cb(err); stats.remaining = stats.total - stats.completed; cb(null, stats); }); function countComplete(cb) { Todo.count({completed: true}, function(err, count) { stats.completed = count; cb(err); }); } function count(cb) { Todo.count(function(err, count) { stats.total = count; cb(err); }); } }; loopback.remoteMethod(Todo.stats, { accepts: {arg: 'filter', type: 'object'}, returns: {arg: 'stats', type: 'object'} }); };
[SwiftmailerBundle] Fix expected default value in SwiftmailerExtension unit test
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection; use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase; use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; class SwiftmailerExtensionTest extends TestCase { public function testConfigLoad() { $container = new ContainerBuilder(); $loader = new SwiftmailerExtension(); $loader->load(array(array()), $container); $this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded'); $loader->load(array(array('transport' => 'sendmail')), $container); $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options'); $loader->load(array(array()), $container); $this->assertEquals('smtp', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() provides default values for configuration options'); } }
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien.potencier@symfony-project.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Bundle\SwiftmailerBundle\Tests\DependencyInjection; use Symfony\Bundle\SwiftmailerBundle\Tests\TestCase; use Symfony\Bundle\SwiftmailerBundle\DependencyInjection\SwiftmailerExtension; use Symfony\Component\DependencyInjection\ContainerBuilder; class SwiftmailerExtensionTest extends TestCase { public function testConfigLoad() { $container = new ContainerBuilder(); $loader = new SwiftmailerExtension(); $loader->load(array(array()), $container); $this->assertEquals('Swift_Mailer', $container->getParameter('swiftmailer.class'), '->mailerLoad() loads the swiftmailer.xml file if not already loaded'); $loader->load(array(array('transport' => 'sendmail')), $container); $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options'); $loader->load(array(array()), $container); $this->assertEquals('sendmail', $container->getParameter('swiftmailer.transport.name'), '->mailerLoad() overrides existing configuration options'); } }
Allow vertices to define a `prepare_vertex` function which will be called just once at some point in the build process.
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None): # Build the model self.builder = builder.Builder() self.dao = self.builder(model, dt, seed) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) # Preparation functions # Consider moving this into PACMAN103 for vertex in self.dao.vertices: if hasattr(vertex, 'prepare_vertex'): vertex.prepare_vertex() self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
import sys from pacman103.core import control from pacman103 import conf from . import builder class Simulator(object): def __init__(self, model, dt=0.001, seed=None): # Build the model self.builder = builder.Builder() self.dao = self.builder(model, dt, seed) self.dao.writeTextSpecs = True def run(self, time): """Run the model, currently ignores the time.""" self.controller = control.Controller( sys.modules[__name__], conf.config.get('Machine', 'machineName') ) self.controller.dao = self.dao self.dao.set_hostname(conf.config.get('Machine', 'machineName')) self.controller.map_model() self.controller.generate_output() self.controller.load_targets() self.controller.load_write_mem() self.controller.run(self.dao.app_id)
Fix production webpack for static pages
const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); const webpackFiles = require('../lib/build/files/webpack_files'); const Package = require('./../package.json'); const VERSION = Package.version; module.exports = { entry: './lib/assets/javascripts/dashboard/statics/static.js', output: { filename: `${VERSION}/javascripts/[name].js`, path: path.resolve(__dirname, '../public/assets'), publicPath: '/assets/' }, devtool: 'source-map', plugins: Object.keys(webpackFiles).map((entryName) => { return new HtmlWebpackPlugin({ inject: false, cache: false, filename: path.resolve(__dirname, `../public/static/${entryName}/index.html`), template: path.resolve(__dirname, '../lib/assets/javascripts/dashboard/statics/index.jst.ejs'), config: webpackFiles[entryName] }); }) };
const HtmlWebpackPlugin = require('html-webpack-plugin'); const path = require('path'); const webpackFiles = require('../lib/build/files/webpack_files'); const Package = require('./../package.json'); const VERSION = Package.version; module.exports = { entry: './lib/assets/javascripts/cartodb/static.js', output: { filename: `${VERSION}/javascripts/[name].js`, path: path.resolve(__dirname, '../public/assets'), publicPath: '/assets/' }, devtool: 'source-map', plugins: Object.keys(webpackFiles).map((entryName) => { return new HtmlWebpackPlugin({ inject: false, cache: false, filename: path.resolve(__dirname, `../public/static/${entryName}/index.html`), template: path.resolve(__dirname, '../lib/assets/javascripts/cartodb/static/index.jst.ejs'), config: webpackFiles[entryName] }); }) };
Save the settings from the database step.
<?php namespace ForkCMS\Bundle\InstallerBundle\Form\Handler; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; /** * Validates and saves the data from the databases form * * @author Wouter Sioen <wouter.sioen@wijs.be> */ class DatabaseHandler { public function process(Form $form, Request $request) { if (!$request->isMethod('POST')) { return false; } $form->handleRequest($request); if ($form->isValid()) { return $this->processValidForm($form, $request); } return false; } public function processValidForm(Form $form, $request) { $session = $request->getSession(); $data = $form->getData(); $session->set('db_hostname', $data['hostname']); $session->set('db_username', $data['username']); $session->set('db_database', $data['database']); $session->set('db_port', $data['port']); $session->set('db_password', $data['password']); return true; } }
<?php namespace ForkCMS\Bundle\InstallerBundle\Form\Handler; use Symfony\Component\Form\Form; use Symfony\Component\HttpFoundation\Request; /** * Validates and saves the data from the databases form * * @author Wouter Sioen <wouter.sioen@wijs.be> */ class DatabaseHandler { public function process(Form $form, Request $request) { if (!$request->isMethod('POST')) { return false; } $form->handleRequest($request); if ($form->isValid()) { return $this->processValidForm($form, $request); } return false; } public function processValidForm(Form $form, $request) { var_dump('ok', $form->getData());exit; /*$session = $request->getSession(); $data = $form->getData(); $session->set('modules', $data['modules']); $session->set('example_data', $data['example_data']); $session->set('example_data', $data['different_debug_email']); $session->set('debug_email', $data['debug_email']);*/ return true; } }
Change ordering to FeaturedRep model.
from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from south.signals import post_migrate from remo.base.utils import add_permissions_to_groups class FeaturedRep(models.Model): """Featured Rep model. Featured Rep -or Rep of the Month- relates existing users with some text explaining why they are so cool. """ created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='reps_featured') text = models.TextField(blank=False, null=False) users = models.ManyToManyField(User, related_name='featuredrep_users') class Meta: ordering = ['-updated_on'] get_latest_by = 'updated_on' permissions = (('can_edit_featured', 'Can edit featured reps'), ('can_delete_featured', 'Can delete featured reps')) @receiver(post_migrate, dispatch_uid='featuredrep_set_groups_signal') def featuredrep_set_groups(app, sender, signal, **kwargs): """Set permissions to groups.""" if (isinstance(app, basestring) and app != 'featuredrep'): return True perms = {'can_edit_featured': ['Admin', 'Council'], 'can_delete_featured': ['Admin', 'Council']} add_permissions_to_groups('featuredrep', perms)
from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver from south.signals import post_migrate from remo.base.utils import add_permissions_to_groups class FeaturedRep(models.Model): """Featured Rep model. Featured Rep -or Rep of the Month- relates existing users with some text explaining why they are so cool. """ created_on = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now=True) created_by = models.ForeignKey(User, related_name='reps_featured') text = models.TextField(blank=False, null=False) users = models.ManyToManyField(User, related_name='featuredrep_users') class Meta: ordering = ['-updated_on'] get_latest_by = 'created_on' permissions = (('can_edit_featured', 'Can edit featured reps'), ('can_delete_featured', 'Can delete featured reps')) @receiver(post_migrate, dispatch_uid='featuredrep_set_groups_signal') def featuredrep_set_groups(app, sender, signal, **kwargs): """Set permissions to groups.""" if (isinstance(app, basestring) and app != 'featuredrep'): return True perms = {'can_edit_featured': ['Admin', 'Council'], 'can_delete_featured': ['Admin', 'Council']} add_permissions_to_groups('featuredrep', perms)
Add mode for changing what file it is, and fix a bug where a line without an equals wouldn't work
class ConfigReader(): def __init__(self,name="config.txt"): self.keys={} self.name = name #Read Keys from file def readKeys(self): keysFile=open(self.name,"r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): item=item[:-1] #If a commented line if (item[0]=='#'): continue #If a new line is the first char elif (item[0]=='\n'): continue else: #Get Position of equal sign pos=item.find('=') if pos != -1: #Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end) self.keys[item[0:pos]]=item[pos+1:] #Return the keys, read allows you to get the keys without re-reading the file. def getKeys(self,read=True): if read: self.readKeys() return self.keys
class ConfigReader(): def __init__(self): self.keys={} #Read Keys from file def readKeys(self): keysFile=open("config.txt","r") fileLines=keysFile.readlines() keysFile.close() self.keys.clear() for item in fileLines: #If last char is \n if (item[-1]=='\n'): item=item[:-1] #If a commented line if (item[0]=='#'): continue #If a new line is the first char elif (item[0]=='\n'): continue else: #Get Position of equal sign pos=item.index('=') #Name of the key is [0:pos], Value of the key is [pos+1:-1] (Stripping the \n char at the end) self.keys[item[0:pos]]=item[pos+1:] #Return the keys, read allows you to get the keys without re-reading the file. def getKeys(self,read=True): if read: self.readKeys() return self.keysFile
Add ref to stub router component for accessibility
import _ from 'lodash'; import React from 'react/addons'; var stubRouterContext = (Component, props, stubs) => { return React.createClass({ childContextTypes: { getCurrentPath: React.PropTypes.func, getCurrentRoutes: React.PropTypes.func, getCurrentPathname: React.PropTypes.func, getCurrentParams: React.PropTypes.func, getCurrentQuery: React.PropTypes.func }, getChildContext: function() { return _.extend({ getCurrentPath () {}, getCurrentRoutes () {}, getCurrentPathname () {}, getCurrentParams () {}, getCurrentQuery () {} }, stubs); }, render: function() { return <Component ref='stub' {...props} />; } }); }; export default stubRouterContext;
import _ from 'lodash'; import React from 'react/addons'; var stubRouterContext = (Component, props, stubs) => { return React.createClass({ childContextTypes: { getCurrentPath: React.PropTypes.func, getCurrentRoutes: React.PropTypes.func, getCurrentPathname: React.PropTypes.func, getCurrentParams: React.PropTypes.func, getCurrentQuery: React.PropTypes.func }, getChildContext: function() { return _.extend({ getCurrentPath () {}, getCurrentRoutes () {}, getCurrentPathname () {}, getCurrentParams () {}, getCurrentQuery () {} }, stubs); }, render: function() { return <Component {...props} />; } }); }; export default stubRouterContext;
Update administration tool copyright year
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2010 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
<?php /* $Id$ osCommerce, Open Source E-Commerce Solutions http://www.oscommerce.com Copyright (c) 2008 osCommerce Released under the GNU General Public License */ ?> <br> <table border="0" width="100%" cellspacing="0" cellpadding="2"> <tr> <td align="center" class="smallText"> <?php /* The following copyright announcement is in compliance to section 2c of the GNU General Public License, and can not be removed, or can only be modified appropriately with additional copyright notices. For more information please read the osCommerce Copyright Policy at: http://www.oscommerce.com/about/copyright This comment must be left intact together with the copyright announcement. */ ?> osCommerce Online Merchant Copyright &copy; 2008 <a href="http://www.oscommerce.com" target="_blank">osCommerce</a><br> osCommerce provides no warranty and is redistributable under the <a href="http://www.fsf.org/licenses/gpl.txt" target="_blank">GNU General Public License</a> </td> </tr> <tr> <td><?php echo tep_image(DIR_WS_IMAGES . 'pixel_trans.gif', '', '1', '5'); ?></td> </tr> <tr> <td align="center" class="smallText">Powered by <a href="http://www.oscommerce.com" target="_blank">osCommerce</a></td> </tr> </table>
Use correct version of antiscroll in blueprint
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/Addepar/antiscroll.git#e0d1538cf4f3fd61c5bedd6168df86d651f125da' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
module.exports = { normalizeEntityName: function() {}, afterInstall: function(options) { // We assume that handlebars, ember, and jquery already exist return this.addBowerPackagesToProject([ { // Antiscroll seems to be abandoned by its original authors. We need // two things: (1) a version in package.json, and (2) the name of the // package must be "antiscroll" to satisfy ember-cli. 'name': 'git://github.com/azirbel/antiscroll.git#90391fb371c7be769bc32e7287c5271981428356' }, { 'name': 'jquery-mousewheel', 'target': '~3.1.4' }, { 'name': 'jquery-ui', 'target': '~1.11.4' } ]); } };
Use Error instead of Errorf
// Cozy Cloud is a personal platform as a service with a focus on data. // Cozy Cloud can be seen as 4 layers, from inside to outside: // // 1. A place to keep your personal data // // 2. A core API to handle the data // // 3. Your web apps, and also the mobile & desktop clients // // 4. A coherent User Experience // // It's also a set of values: Simple, Versatile, Yours. These values mean a lot // for Cozy Cloud in all aspects. From an architectural point, it declines to: // // - Simple to deploy and understand, not built as a galaxy of optimized // microservices managed by kubernetes that only experts can debug. // // - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on // multiple servers by specialized hosting. Users can install apps. // // - Yours, you own your data and you control it. If you want to take back your // data to go elsewhere, you can. package main import ( "os" log "github.com/Sirupsen/logrus" "github.com/cozy/cozy-stack/cmd" ) func main() { if err := cmd.RootCmd.Execute(); err != nil { log.Error(err.Error()) os.Exit(1) } }
// Cozy Cloud is a personal platform as a service with a focus on data. // Cozy Cloud can be seen as 4 layers, from inside to outside: // // 1. A place to keep your personal data // // 2. A core API to handle the data // // 3. Your web apps, and also the mobile & desktop clients // // 4. A coherent User Experience // // It's also a set of values: Simple, Versatile, Yours. These values mean a lot // for Cozy Cloud in all aspects. From an architectural point, it declines to: // // - Simple to deploy and understand, not built as a galaxy of optimized // microservices managed by kubernetes that only experts can debug. // // - Versatile, can be hosted on a Raspberry Pi for geeks to massive scale on // multiple servers by specialized hosting. Users can install apps. // // - Yours, you own your data and you control it. If you want to take back your // data to go elsewhere, you can. package main import ( "os" log "github.com/Sirupsen/logrus" "github.com/cozy/cozy-stack/cmd" ) func main() { if err := cmd.RootCmd.Execute(); err != nil { log.Errorf(err.Error()) os.Exit(1) } }
Support for Watchify. We hook onto the pipeline on every reset and a new through object gets created.
/* jshint -W040 */ 'use strict'; var path = require('path'), through = require('through'); module.exports = sourcemapify; /** * Transforms the browserify sourcemap * * @param browserify * @param options */ function sourcemapify(browserify, options) { options = options || browserify._options || {}; function write(data) { if (options.base) { // Determine the relative path // from the bundle file's directory to the source file var base = path.resolve(process.cwd(), options.base); data.sourceFile = path.relative(base, data.file); } if (options.root) { // Prepend the root path to the file path data.sourceFile = path.join(options.root, data.sourceFile); } this.queue(data); } // Add our transform stream to Browserify's "debug" pipeline // https://github.com/substack/node-browserify#bpipeline configurePipeline(); browserify.on('reset', function(){ configurePipeline(); }); function configurePipeline() { browserify.pipeline.get('debug').push(new through(write)); } return this; }
/* jshint -W040 */ 'use strict'; var path = require('path'), through = require('through'); module.exports = sourcemapify; /** * Transforms the browserify sourcemap * * @param browserify * @param options */ function sourcemapify(browserify, options) { options = options || browserify._options || {}; // Create a stream to transform the sourcemap var transformStream = through(write, end); function write(data) { if (options.base) { // Determine the relative path // from the bundle file's directory to the source file var base = path.resolve(process.cwd(), options.base); data.sourceFile = path.relative(base, data.file); } if (options.root) { // Prepend the root path to the file path data.sourceFile = path.join(options.root, data.sourceFile); } this.queue(data); } function end() { this.queue(null); } // Add our transform stream to Browserify's "debug" pipeline // https://github.com/substack/node-browserify#bpipeline browserify.pipeline.get('debug').push(transformStream); return this; }
Fix deprecated option of Redux Dev Tools.
/* eslint-disable global-require */ /* global window */ import { createStore, applyMiddleware, combineReducers } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { isTest } from 'worona-deps'; import { reduxReactRouter, routerStateReducer as router } from 'redux-router'; import { composeWithDevTools } from 'redux-devtools-extension'; import build from '../reducers'; const sagaMiddleware = createSagaMiddleware(); const reducers = { build: build(), router }; const sagas = {}; const composeEnhancers = composeWithDevTools({ serialize: false, }); export const store = createStore( combineReducers(reducers), composeEnhancers( reduxReactRouter({ createHistory: !isTest ? require('history').createHistory : require('history').createMemoryHistory, }), applyMiddleware(sagaMiddleware), ) ); export default store; export const dispatch = action => store.dispatch(action); export const reloadReducers = () => store.replaceReducer(combineReducers(reducers)); export const addReducer = (namespace, reducer) => { if (reducer) reducers[namespace] = reducer; }; export const removeReducer = namespace => { if (reducers[namespace]) delete reducers[namespace]; }; export const startSaga = (namespace, saga) => { sagas[namespace] = sagaMiddleware.run(saga); }; export const stopSaga = (namespace) => { if (sagas[namespace]) sagas[namespace].cancel(); }; export const getState = store.getState.bind(store); export const history = store.history;
/* eslint-disable global-require */ /* global window */ import { createStore, applyMiddleware, combineReducers } from 'redux'; import createSagaMiddleware from 'redux-saga'; import { isTest } from 'worona-deps'; import { reduxReactRouter, routerStateReducer as router } from 'redux-router'; import { composeWithDevTools } from 'redux-devtools-extension'; import build from '../reducers'; const sagaMiddleware = createSagaMiddleware(); const reducers = { build: build(), router }; const sagas = {}; const composeEnhancers = composeWithDevTools({ serializeState: false, }); export const store = createStore( combineReducers(reducers), composeEnhancers( reduxReactRouter({ createHistory: !isTest ? require('history').createHistory : require('history').createMemoryHistory, }), applyMiddleware(sagaMiddleware), ) ); export default store; export const dispatch = action => store.dispatch(action); export const reloadReducers = () => store.replaceReducer(combineReducers(reducers)); export const addReducer = (namespace, reducer) => { if (reducer) reducers[namespace] = reducer; }; export const removeReducer = namespace => { if (reducers[namespace]) delete reducers[namespace]; }; export const startSaga = (namespace, saga) => { sagas[namespace] = sagaMiddleware.run(saga); }; export const stopSaga = (namespace) => { if (sagas[namespace]) sagas[namespace].cancel(); }; export const getState = store.getState.bind(store); export const history = store.history;
Move searchPortal ref function to constructor
import React, { Component } from 'react'; export default class EmojiSuggestionsPortal extends Component { constructor(props) { super(props); this.searchPortalRef = (element) => { this.searchPortal = element; }; } componentWillMount() { this.props.store.register(this.props.offsetKey); this.updatePortalClientRect(this.props); // trigger a re-render so the EmojiSuggestions becomes active this.props.setEditorState(this.props.getEditorState()); } componentWillReceiveProps(nextProps) { this.updatePortalClientRect(nextProps); } componentWillUnmount() { this.props.store.unregister(this.props.offsetKey); } updatePortalClientRect(props) { this.props.store.updatePortalClientRect( props.offsetKey, () => ( this.searchPortal.getBoundingClientRect() ), ); } render() { return ( <span className={this.key} ref={this.searchPortalRef} > {this.props.children} </span> ); } }
import React, { Component } from 'react'; export default class EmojiSuggestionsPortal extends Component { componentWillMount() { this.props.store.register(this.props.offsetKey); this.updatePortalClientRect(this.props); // trigger a re-render so the EmojiSuggestions becomes active this.props.setEditorState(this.props.getEditorState()); } componentWillReceiveProps(nextProps) { this.updatePortalClientRect(nextProps); } componentWillUnmount() { this.props.store.unregister(this.props.offsetKey); } updatePortalClientRect(props) { this.props.store.updatePortalClientRect( props.offsetKey, () => ( this.searchPortal.getBoundingClientRect() ), ); } render() { return ( <span className={this.key} ref={(element) => { this.searchPortal = element; }} > {this.props.children} </span> ); } }
Set all older tracks to be "visible".
<?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; final class Version20220706235608 extends AbstractMigration { public function getDescription(): string { return 'Add "is_visible" denormalization to song_history table.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE song_history ADD is_visible TINYINT(1) NOT NULL'); $this->addSql('CREATE INDEX idx_is_visible ON song_history (is_visible)'); $this->addSql('UPDATE song_history SET is_visible=1'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX idx_is_visible ON song_history'); $this->addSql('ALTER TABLE song_history DROP is_visible'); } }
<?php declare(strict_types=1); namespace App\Entity\Migration; use Doctrine\DBAL\Schema\Schema; use Doctrine\Migrations\AbstractMigration; final class Version20220706235608 extends AbstractMigration { public function getDescription(): string { return 'Add "is_visible" denormalization to song_history table.'; } public function up(Schema $schema): void { $this->addSql('ALTER TABLE song_history ADD is_visible TINYINT(1) NOT NULL'); $this->addSql('CREATE INDEX idx_is_visible ON song_history (is_visible)'); } public function down(Schema $schema): void { $this->addSql('DROP INDEX idx_is_visible ON song_history'); $this->addSql('ALTER TABLE song_history DROP is_visible'); } }
Add extra momentjs locales for 'de' and 'es' refs #1909
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require lodash //= require handlebars.runtime //= require diacritics // To use placeholders in inputs in browsers that do not support it // natively yet. //= require jquery/jquery.placeholder // Notifications (flash messages). //= require jquery/jquery.noty // To crop logos. //= require jquery/jquery.Jcrop // For modals. //= require bootstrap/bootstrap-modal //= require bootstrap/bootstrap-modalmanager // Used in crop, modals and possibly other places. Grep for `ajaxForm` // and `ajaxSubmit`. //= require jquery/jquery.form // Use to search for models (e.g. users) dynamically. //= require select2 //= require i18n/translations // Moment.js for dates //= require moment //= require moment/pt-br //= require moment/de //= require moment/es // Datetime picker for bootstrap //= require bootstrap-datetimepicker //= require fineuploader // 'base' HAS to be the first one included //= require ./app/application/base //= require_tree ./templates //= require_tree ./app/application/ //= require_tree ./app/_all/
//= require jquery //= require jquery_ujs //= require twitter/bootstrap //= require lodash //= require handlebars.runtime //= require diacritics // To use placeholders in inputs in browsers that do not support it // natively yet. //= require jquery/jquery.placeholder // Notifications (flash messages). //= require jquery/jquery.noty // To crop logos. //= require jquery/jquery.Jcrop // For modals. //= require bootstrap/bootstrap-modal //= require bootstrap/bootstrap-modalmanager // Used in crop, modals and possibly other places. Grep for `ajaxForm` // and `ajaxSubmit`. //= require jquery/jquery.form // Use to search for models (e.g. users) dynamically. //= require select2 //= require i18n/translations // Moment.js for dates //= require moment //= require moment/pt-br // Datetime picker for bootstrap //= require bootstrap-datetimepicker //= require fineuploader // 'base' HAS to be the first one included //= require ./app/application/base //= require_tree ./templates //= require_tree ./app/application/ //= require_tree ./app/_all/
Fix for PHP < 5 error
<?php # let people know if they are running an unsupported version of PHP if(phpversion() < 5) { echo '<h3>Stacey requires PHP/5.0 or higher.<br>You are currently running PHP/".phpversion().".</h3><p>You should contact your host to see if they can upgrade your version of PHP.</p>'; } else { # require helpers class so we can use rglob require_once './app/helpers.inc.php'; # include any php files which sit in the app folder foreach(Helpers::rglob('./app/**.inc.php') as $include) include_once $include; try { # try start the app new Stacey($_GET); } catch(Exception $e) { if($e->getMessage() == "404") { # return 404 headers header('HTTP/1.0 404 Not Found'); if(file_exists('./public/404.html')) echo file_get_contents('./public/404.html'); else echo '<h1>404</h1><h2>Page could not be found.</h2><p>Unfortunately, the page you were looking for does not exist here.</p>'; } else { echo '<h3>'.$e->getMessage().'</h3>'; } } } ?>
<?php # let people know if they are running an unsupported version of PHP if(phpversion() < 5) { echo '<h3>Stacey requires PHP/5.0 or higher.<br>You are currently running PHP/".phpversion().".</h3><p>You should contact your host to see if they can upgrade your version of PHP.</p>'; return; } # require helpers class so we can use rglob require_once './app/helpers.inc.php'; # include any php files which sit in the app folder foreach(Helpers::rglob('./app/**.inc.php') as $include) include_once $include; try { # try start the app new Stacey($_GET); } catch(Exception $e) { if($e->getMessage() == "404") { # return 404 headers header('HTTP/1.0 404 Not Found'); if(file_exists('./public/404.html')) echo file_get_contents('./public/404.html'); else echo '<h1>404</h1><h2>Page could not be found.</h2><p>Unfortunately, the page you were looking for does not exist here.</p>'; } else { echo '<h3>'.$e->getMessage().'</h3>'; } } ?>
Fix Forgotten Key Error in Read Campaign Setting Model Logic
var configuration = require('../../../config/configuration.json') module.exports = { getCampaignSettingModel: function (redisClient, CampaignHashID, callback) { var tableName = configuration.TableMACampaignModelSettingModel + CampaignHashID var model = {} redisClient.hget(tableName, configuration.ConstantSMPriority, function (err, replies) { if (err) { callback(err, null) return } model[configuration.ConstantSMPriority] = replies var settingKeys = Object.keys(configuration.settingEnum) var counter = 0 for (var i = 0; i < settingKeys.length; i++) { if (settingKeys[i] === configuration.settingEnum.Priority) continue var key = settingKeys[i] var table = configuration.TableModel.general.CampaignModel + campaignHashID utility.stringReplace(table, '@', key) multi.zrange(table, '0', '-1', function (err, replies) { if (err) { callback(err, null) return } model[settingKeys[i]] = replies counter++ if (counter == settingKeys.length) callback(null, model) }) } }) } }
var configuration = require('../../../config/configuration.json') module.exports = { getCampaignSettingModel: function (redisClient, CampaignHashID, callback) { var tableName = configuration.TableMACampaignModelSettingModel + CampaignHashID var model = {} redisClient.hget(tableName, configuration.ConstantSMPriority, function (err, replies) { if (err) { callback(err, null) return } var settingKeys = Object.keys(configuration.settingEnum) var counter = 0 for (var i = 0; i < settingKeys.length; i++) { if (settingKeys[i] === configuration.settingEnum.Priority) continue var key = settingKeys[i] var table = configuration.TableModel.general.CampaignModel + campaignHashID utility.stringReplace(table, '@', key) multi.zrange(table, '0', '-1', function (err, replies) { if (err) { callback(err, null) return } model[settingKeys[i]] = replies counter++ if (counter == settingKeys.length) callback(null, model) }) } }) } }
Fix coding standard [skip fix]
<?php namespace Miaoxing\Config\Service; use Wei\Env; use Wei\RetTrait; /** * 配置服务 * * @property Env $env */ class ConfigV1 extends \Wei\Config { use RetTrait; /** * 配置文件的路径 * * @var string */ protected $configFile = 'data/config.php'; /** * {@inheritdoc} */ public function __construct(array $options = []) { parent::__construct($options); // If the config service is not constructed, the service container can't set config for it if (!$this->wei->isInstanced('configV1')) { $this->wei->set('configV1', $this); } $this->env->loadConfigFile($this->configFile); } }
<?php namespace Miaoxing\Config\Service; use Wei\Env; use Exception; use League\Flysystem\Adapter\Local; use League\Flysystem\Sftp\SftpAdapter; use League\Flysystem\Filesystem; use Wei\RetTrait; /** * 配置服务 * * @property Env $env */ class ConfigV1 extends \Wei\Config { use RetTrait; /** * 配置文件的路径 * * @var string */ protected $configFile = 'data/config.php'; /** * {@inheritdoc} */ public function __construct(array $options = []) { parent::__construct($options); // If the config service is not constructed, the service container can't set config for it if (!$this->wei->isInstanced('configV1')) { $this->wei->set('configV1', $this); } $this->env->loadConfigFile($this->configFile); } }
Add method to obtain max compressed length
/* * 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 io.airlift.compress; import java.nio.ByteBuffer; public interface Compressor { int maxCompressedLength(int uncompressedSize); /** * @return number of bytes written to the output */ int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength); /** * @return number of bytes written to the output */ int compress(ByteBuffer input, int inputOffset, int inputLength, ByteBuffer output, int outputOffset, int maxOutputLength); }
/* * 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 io.airlift.compress; import java.nio.ByteBuffer; public interface Compressor { /** * @return number of bytes written to the output */ int compress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength); /** * @return number of bytes written to the output */ int compress(ByteBuffer input, int inputOffset, int inputLength, ByteBuffer output, int outputOffset, int maxOutputLength); }
Add overwriting of set methods.
<?PHP /** * An Uri value object. * This is just a wrapper for Zend Uri. * * @link https://github.com/zendframework/zend-uri * * @todo This has to be a Guzzle Uri or https://github.com/mvdbos/vdb-uri * * @package Serendipity\Framework * @subpackage ValueObjects * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Framework\ValueObjects\Uri; use \Zend\Uri\Uri as BaseUri; use \SerendipityHQ\Framework\ValueObjects\Uri\UriInterface; class Uri extends BaseUri implements UriInterface { public function __construct($uri = null) { parent::__construct($uri); } public function __set($field, $value){} }
<?PHP /** * An Uri value object. * This is just a wrapper for Zend Uri. * * @link https://github.com/zendframework/zend-uri * * @todo This has to be a Guzzle Uri or https://github.com/mvdbos/vdb-uri * * @package Serendipity\Framework * @subpackage ValueObjects * * @author Adamo Crespi <hello@aerendir.me> * @copyright Copyright (c) 2015, Adamo Crespi * @license MIT License */ namespace SerendipityHQ\Framework\ValueObjects\Uri; use \Zend\Uri\Uri as BaseUri; use \SerendipityHQ\Framework\ValueObjects\Uri\UriInterface; class Uri extends BaseUri implements UriInterface { public function __construct($uri = null) { parent::__construct($uri); } }
Set initial size for main toggle box
package com.easternedgerobotics.rov.fx; import javafx.geometry.Insets; import javafx.scene.Parent; import javafx.scene.control.ToggleButton; import javafx.scene.layout.BorderPane; import javax.inject.Inject; public class MainView implements View { static final int SPACING = 10; static final int TOGGLE_BOX_W = 256; static final int TOGGLE_BOX_H = 64; final BorderPane box = new BorderPane(); final ToggleButton button = new ToggleButton("Start"); @Inject public MainView() { button.setMaxWidth(Double.MAX_VALUE); button.setMaxHeight(Double.MAX_VALUE); button.setPrefSize(TOGGLE_BOX_W, TOGGLE_BOX_H); box.setPadding(new Insets(SPACING)); box.setCenter(button); } @Override public final Parent getParent() { return box; } }
package com.easternedgerobotics.rov.fx; import javafx.geometry.Insets; import javafx.scene.Parent; import javafx.scene.control.ToggleButton; import javafx.scene.layout.BorderPane; import javax.inject.Inject; public class MainView implements View { static final int SPACING = 10; final BorderPane box = new BorderPane(); final ToggleButton button = new ToggleButton("Start"); @Inject public MainView() { button.setMaxWidth(Double.MAX_VALUE); button.setMaxHeight(Double.MAX_VALUE); box.setPadding(new Insets(SPACING)); box.setCenter(button); } @Override public final Parent getParent() { return box; } }
Add read static files feature.
#!/usr/bin/env python3 class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 # Check the route for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break # Check static files if found != 1: found = self._ReadStaticFiles(uri, res) # It is really not found if found != 1: self._NotFound(req, res) def _ReadStaticFiles(self, uri, res): found = 0 try: f = open("static/{}".format(uri), "r") res.Body = f.read() f.close() found = 1 except: pass return found def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
#!/usr/bin/env python3 class Routes: '''Define the feature of route for URIs.''' def __init__(self): self._Routes = [] def AddRoute(self, uri, callback): '''Add an URI into the route table.''' self._Routes.append([uri, callback]) def Dispatch(self, req, res): '''Dispatch an URI according to the route table.''' uri = "" for fv in req.Header: if fv[0] == "URI": uri = fv[1] found = 1 break found = 0 for r in self._Routes: if r[0] == uri: r[1](req, res) found = 1 break if found != 1: self._NotFound(req, res) def _NotFound(self, req, res): '''Define the default error page for not found URI.''' res.Header.append(["Status", "404 Not Found"])
Add deferred register to test sounds
package info.u_team.u_team_test.init; import info.u_team.u_team_core.soundevent.USoundEvent; import info.u_team.u_team_test.TestMod; import net.minecraft.util.SoundEvent; import net.minecraftforge.eventbus.api.IEventBus; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; import net.minecraftforge.registries.*; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestSounds { public static final DeferredRegister<SoundEvent> SOUND_EVENTS = DeferredRegister.create(ForgeRegistries.SOUND_EVENTS, TestMod.MODID); public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use"); public static void register(IEventBus bus) { SOUND_EVENTS.register(bus); } }
package info.u_team.u_team_test.init; import info.u_team.u_team_core.soundevent.USoundEvent; import info.u_team.u_team_core.util.registry.BaseRegistryUtil; import info.u_team.u_team_test.TestMod; import net.minecraft.util.SoundEvent; import net.minecraftforge.event.RegistryEvent.Register; import net.minecraftforge.eventbus.api.SubscribeEvent; import net.minecraftforge.fml.common.Mod.EventBusSubscriber; import net.minecraftforge.fml.common.Mod.EventBusSubscriber.Bus; @EventBusSubscriber(modid = TestMod.MODID, bus = Bus.MOD) public class TestSounds { public static final SoundEvent BETTER_ENDERPEARL_USE = new USoundEvent("better_enderpearl_use"); @SubscribeEvent public static void register(Register<SoundEvent> event) { BaseRegistryUtil.getAllRegistryEntriesAndApplyNames(TestMod.MODID, SoundEvent.class).forEach(event.getRegistry()::register); } }
Use only accelerometer for orientation.
from flask import Flask, Response from sense_hat import SenseHat sense = SenseHat() sense.set_imu_config(False, False, True) app = Flask(__name__) @app.route('/') def all_sensors(): return "Hello, world!" @app.route('/humidity') def humidity(): return "Hello, world!" @app.route('/pressure') def pressure(): return "Hello, world!" @app.route('/temperature') def temperature(): return "Hello, world!" @app.route('/orientation') def orientation(): return str(sense.orientation) @app.route('/accelerometer') def accelerometer(): return "Hello, world!" @app.route('/magnetometer') def magnetometer(): return "Hello, world!" @app.route('/gyroscope') def gyroscope(): return "Hello, world!"
from flask import Flask, Response from sense_hat import SenseHat sense = SenseHat() sense.set_imu_config(True, True, True) app = Flask(__name__) @app.route('/') def all_sensors(): return "Hello, world!" @app.route('/humidity') def humidity(): return "Hello, world!" @app.route('/pressure') def pressure(): return "Hello, world!" @app.route('/temperature') def temperature(): return "Hello, world!" @app.route('/orientation') def orientation(): return str(sense.orientation) @app.route('/accelerometer') def accelerometer(): return "Hello, world!" @app.route('/magnetometer') def magnetometer(): return "Hello, world!" @app.route('/gyroscope') def gyroscope(): return "Hello, world!"
Add missing var error for windows, minor change pushing in
// +build windows /* * Minio Client (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this fs 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 fs import ( "path/filepath" "syscall" "github.com/minio/minio/pkg/iodine" ) func normalizePath(path string) (string, error) { var err error if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { path, err = syscall.FullPath(path) if err != nil { return "", iodine.New(err, nil) } } return path, nil }
// +build windows /* * Minio Client (C) 2015 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this fs 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 fs import ( "path/filepath" "syscall" "github.com/minio/minio/pkg/iodine" ) func normalizePath(path string) (string, error) { if filepath.VolumeName(path) == "" && filepath.HasPrefix(path, "\\") { path, err = syscall.FullPath(path) if err != nil { return "", iodine.New(err, nil) } } return path, nil }
Fix more db connection strings
from __future__ import with_statement from alembic import context import sqlalchemy import logging logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s") target_metadata = None def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ context.configure(url=context.config.get_section_option("lrrbot", "postgres", 'postgresql:///lrrbot'), target_metadata=target_metadata, literal_binds=True) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = sqlalchemy.create_engine(context.config.get_section_option("lrrbot", "postgres", 'postgresql:///lrrbot')) with connectable.connect() as connection: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
from __future__ import with_statement from alembic import context import sqlalchemy import logging logging.basicConfig(level=logging.INFO, format="[%(asctime)s] %(levelname)s:%(name)s:%(message)s") target_metadata = None def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ context.configure(url=context.config.get_section_option("lrrbot", "postgres", 'postgres:///lrrbot'), target_metadata=target_metadata, literal_binds=True) with context.begin_transaction(): context.run_migrations() def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ connectable = sqlalchemy.create_engine(context.config.get_section_option("lrrbot", "postgres", 'postgres:///lrrbot')) with connectable.connect() as connection: context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online()
Debug mode for redis (commented out).
// Global registry for our Redis connection. // Use this instead of passing around a single 'client' handle. // Also allows us to select a database within Redis. var redis = require("redis"); var _ = require("underscore"); var client; var db = 0; var sessionclient; var session_db = 1; exports.initClient = function(select_db) { client = redis.createClient(); //redis.debug_mode = true; if (select_db) {db = select_db;} client.select(db,function(){}); return client; }; exports.getClient = function() { if (_.isUndefined(client)) { console.log("Error: client has not been initialized"); } return client; }; exports.initSessionClient = function(select_db) { sessionclient = redis.createClient(); if (select_db) {session_db = select_db;} sessionclient.select(session_db,function(){}); return sessionclient; }; exports.getSessionClient = function() { if (_.isUndefined(client)) { console.log("Error: session client has not been initialized"); } return sessionclient; };
// Global registry for our Redis connection. // Use this instead of passing around a single 'client' handle. // Also allows us to select a database within Redis. var redis = require("redis"); var _ = require("underscore"); var client; var db = 0; var sessionclient; var session_db = 1; exports.initClient = function(select_db) { client = redis.createClient(); if (select_db) {db = select_db;} client.select(db,function(){}); return client; }; exports.getClient = function() { if (_.isUndefined(client)) { console.log("Error: client has not been initialized"); } return client; }; exports.initSessionClient = function(select_db) { sessionclient = redis.createClient(); if (select_db) {session_db = select_db;} sessionclient.select(session_db,function(){}); return sessionclient; }; exports.getSessionClient = function() { if (_.isUndefined(client)) { console.log("Error: session client has not been initialized"); } return sessionclient; };
Add update_reservation to dummy plugin update_reservation is now an abstract method. It needs to be added to all plugins. Change-Id: I921878bd5233613b804b17813af1aac5bdfed9e7 (cherry picked from commit 1dbc30202bddfd4f03bdc9a8005de3c363d2ac1d)
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from blazar.plugins import base class DummyVMPlugin(base.BasePlugin): """Plugin for VM resource that does nothing.""" resource_type = 'virtual:instance' title = 'Dummy VM Plugin' description = 'This plugin does nothing.' def reserve_resource(self, reservation_id, values): return None def update_reservation(self, reservation_id, values): return None def on_start(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be waked up this moment.' % resource_id def on_end(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be deleted this moment.' % resource_id
# Copyright (c) 2013 Mirantis Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or # implied. # See the License for the specific language governing permissions and # limitations under the License. from blazar.plugins import base class DummyVMPlugin(base.BasePlugin): """Plugin for VM resource that does nothing.""" resource_type = 'virtual:instance' title = 'Dummy VM Plugin' description = 'This plugin does nothing.' def reserve_resource(self, reservation_id, values): return None def on_start(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be waked up this moment.' % resource_id def on_end(self, resource_id): """Dummy VM plugin does nothing.""" return 'VM %s should be deleted this moment.' % resource_id
Add the correct classname to the view button in the browse template to be consistent with the other buttons.
<?php namespace TCG\Voyager\Actions; class ViewAction extends AbstractAction { public function getTitle() { return __('voyager::generic.view'); } public function getIcon() { return 'voyager-eye'; } public function getPolicy() { return 'read'; } public function getAttributes() { return [ 'class' => 'btn btn-sm btn-warning pull-right view', ]; } public function getDefaultRoute() { return route('voyager.'.$this->dataType->slug.'.show', $this->data->{$this->data->getKeyName()}); } }
<?php namespace TCG\Voyager\Actions; class ViewAction extends AbstractAction { public function getTitle() { return __('voyager::generic.view'); } public function getIcon() { return 'voyager-eye'; } public function getPolicy() { return 'read'; } public function getAttributes() { return [ 'class' => 'btn btn-sm btn-warning pull-right edit', ]; } public function getDefaultRoute() { return route('voyager.'.$this->dataType->slug.'.show', $this->data->{$this->data->getKeyName()}); } }
Add click action copy to clipboard
package protocolsupport.api.chat.modifiers; import java.net.MalformedURLException; import java.net.URL; import protocolsupport.utils.Utils; public class ClickAction { private final Type type; private final String value; public ClickAction(Type action, String value) { this.type = action; this.value = value; } public ClickAction(URL url) { this.type = Type.OPEN_URL; this.value = url.toString(); } public Type getType() { return type; } public String getValue() { return value; } public URL getUrl() throws MalformedURLException { if (type == Type.OPEN_URL) { return new URL(value); } throw new IllegalStateException(type + " is not an " + Type.OPEN_URL); } @Override public String toString() { return Utils.toStringAllFields(this); } public static enum Type { OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE, COPY_TO_CLIPBOARD; } }
package protocolsupport.api.chat.modifiers; import java.net.MalformedURLException; import java.net.URL; import protocolsupport.utils.Utils; public class ClickAction { private final Type type; private final String value; public ClickAction(Type action, String value) { this.type = action; this.value = value; } public ClickAction(URL url) { this.type = Type.OPEN_URL; this.value = url.toString(); } public Type getType() { return type; } public String getValue() { return value; } public URL getUrl() throws MalformedURLException { if (type == Type.OPEN_URL) { return new URL(value); } throw new IllegalStateException(type + " is not an " + Type.OPEN_URL); } @Override public String toString() { return Utils.toStringAllFields(this); } public static enum Type { OPEN_URL, OPEN_FILE, RUN_COMMAND, TWITCH_USER_INFO, SUGGEST_COMMAND, CHANGE_PAGE; } }
Rename write all items class and description
<?php /** * Loops through all products and Categories, and sets their URL Segments, if * they do not already have one * * @package commerce * @subpackage tasks */ class CatalogueWriteAllItemsTask extends BuildTask { protected $title = 'Write All Products and Categories'; protected $description = 'Loop through all products and product categories and re-save them.'; public function run($request) { $products = 0; $categories = 0; // First load all products $items = CatalogueProduct::get(); foreach($items as $item) { // Just write product, on before write should deal with the rest $item->write(); $products++; } // Then all categories $items = CatalogueCategory::get(); foreach($items as $item) { // Just write category, on before write should deal with the rest $item->write(); $categories++; } echo "Wrote $products products and $categories categories.\n"; } }
<?php /** * Loops through all products and Categories, and sets their URL Segments, if * they do not already have one * * @package commerce * @subpackage tasks */ class CommerceWriteItemsTask extends BuildTask { protected $title = 'Write All Commerce Items'; protected $description = 'Loop through all products and product categories and re-save them.'; public function run($request) { $products = 0; $categories = 0; // First load all products $items = CatalogueProduct::get(); foreach($items as $item) { // Just write product, on before write should deal with the rest $item->write(); $products++; } // Then all categories $items = CatalogueCategory::get(); foreach($items as $item) { // Just write category, on before write should deal with the rest $item->write(); $categories++; } echo "Wrote $products products and $categories categories.\n"; } }
Change test reporter to something more compact
const gulp = require('gulp'); const bump = require('gulp-bump'); const eslint = require('gulp-eslint'); const mocha = require('gulp-mocha'); const fs = require('fs'); exports.bump = function(src, type){ return () => gulp.src(src) .pipe(bump({type: type})) .pipe(gulp.dest('./')); }; exports.lint = function(src, ci) { if(ci){ return () => gulp .src(src) .pipe(eslint()) .pipe(eslint.format('junit', fs.createWriteStream('tmp/eslint-report.xml'))); } else{ return () => gulp .src(src) .pipe(eslint()) .pipe(eslint.format()); } }; exports.test = function(src, ci, options = {}) { const opts = Object.assign({}, { reporter: 'progress' }, options); if(ci){ opts.reporter = 'mocha-junit-reporter'; opts.reporterOptions = { mochaFile: './tmp/test-results.xml' }; } return () => gulp.src(src) .pipe(mocha(opts)); };
const gulp = require('gulp'); const bump = require('gulp-bump'); const eslint = require('gulp-eslint'); const mocha = require('gulp-mocha'); const fs = require('fs'); exports.bump = function(src, type){ return () => gulp.src(src) .pipe(bump({type: type})) .pipe(gulp.dest('./')); }; exports.lint = function(src, ci) { if(ci){ return () => gulp .src(src) .pipe(eslint()) .pipe(eslint.format('junit', fs.createWriteStream('tmp/eslint-report.xml'))); } else{ return () => gulp .src(src) .pipe(eslint()) .pipe(eslint.format()); } }; exports.test = function(src, ci, options = {}) { const opts = Object.assign({}, { reporter: 'nyan' }, options); if(ci){ opts.reporter = 'mocha-junit-reporter'; opts.reporterOptions = { mochaFile: './tmp/test-results.xml' }; } return () => gulp.src(src) .pipe(mocha(opts)); };
lxc/exec: Fix signal handler for Windows Closes #3496 Signed-off-by: Stéphane Graber <089afc6d81f66f1168a9849e15660feae286e024@ubuntu.com>
// +build windows package main import ( "io" "os" "os/signal" "syscall" "github.com/gorilla/websocket" "github.com/mattn/go-colorable" "github.com/lxc/lxd/shared/logger" ) // Windows doesn't process ANSI sequences natively, so we wrap // os.Stdout for improved user experience for Windows client type WrappedWriteCloser struct { io.Closer wrapper io.Writer } func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) { return wwc.wrapper.Write(p) } func (c *execCmd) getStdout() io.WriteCloser { return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()} } func (c *execCmd) getTERM() (string, bool) { return "dumb", true } func (c *execCmd) controlSocketHandler(control *websocket.Conn) { ch := make(chan os.Signal, 10) signal.Notify(ch, os.Interrupt) closeMsg := websocket.FormatCloseMessage(websocket.CloseNormalClosure, "") defer control.WriteMessage(websocket.CloseMessage, closeMsg) for { sig := <-ch switch sig { case os.Interrupt: logger.Debugf("Received '%s signal', forwarding to executing program.", sig) err := c.forwardSignal(control, syscall.SIGINT) if err != nil { logger.Debugf("Failed to forward signal '%s'.", syscall.SIGINT) return } default: break } } }
// +build windows package main import ( "io" "os" "github.com/gorilla/websocket" "github.com/mattn/go-colorable" "github.com/lxc/lxd/shared/logger" ) // Windows doesn't process ANSI sequences natively, so we wrap // os.Stdout for improved user experience for Windows client type WrappedWriteCloser struct { io.Closer wrapper io.Writer } func (wwc *WrappedWriteCloser) Write(p []byte) (int, error) { return wwc.wrapper.Write(p) } func (c *execCmd) getStdout() io.WriteCloser { return &WrappedWriteCloser{os.Stdout, colorable.NewColorableStdout()} } func (c *execCmd) getTERM() (string, bool) { return "dumb", true } func (c *execCmd) controlSocketHandler(control *websocket.Conn) { // TODO: figure out what the equivalent of signal.SIGWINCH is on // windows and use that; for now if you resize your terminal it just // won't work quite correctly. err := c.sendTermSize(control) if err != nil { logger.Debugf("error setting term size %s", err) } }
Set webpack devtool to false in production
const path = require('path') module.exports = ({ actions }) => { actions.setWebpackConfig({ devtool: process.env.NODE_ENV !== 'production', resolve: { alias: { '@components': path.resolve(__dirname, '../../components/'), '@icons': path.resolve(__dirname, '../../icons/'), '@styles': path.resolve(__dirname, '../../styles/'), '@utils': path.resolve(__dirname, '../../utils/'), '@types': path.resolve(__dirname, '../../types/'), '@assets': path.resolve(__dirname, '../../assets/'), '@sections': path.resolve(__dirname, '../../sections/'), }, extensions: ['.js', '.json', '.ts', '.tsx'], }, }) }
const path = require('path') module.exports = ({ actions }) => { actions.setWebpackConfig({ resolve: { alias: { '@components': path.resolve(__dirname, '../../components/'), '@icons': path.resolve(__dirname, '../../icons/'), '@styles': path.resolve(__dirname, '../../styles/'), '@utils': path.resolve(__dirname, '../../utils/'), '@types': path.resolve(__dirname, '../../types/'), '@assets': path.resolve(__dirname, '../../assets/'), '@sections': path.resolve(__dirname, '../../sections/'), }, extensions: ['.js', '.json', '.ts', '.tsx'], }, }) }
Handle input with a http form, rather than JSON
package main import ( "net/http" "fmt" ) func handlePing(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") } type Input struct { FeedId string FeedUrl string } func handleRequest(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Not allowed", http.StatusMethodNotAllowed) return } input, err := parseInput(r) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } fmt.Fprintf(w, "%s", input.FeedUrl) } func parseInput(r *http.Request) (i Input, err error) { feed_id := r.FormValue("feed_id") feed_url := r.FormValue("feed_url") return Input{feed_id, feed_url}, nil } func init() { http.HandleFunc("/ping", handlePing) http.HandleFunc("/handle", handleRequest) }
package main import ( "net/http" "fmt" "encoding/json" ) func handlePing(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "OK") } func handleRequest(w http.ResponseWriter, r *http.Request) { type Input struct { FeedId string `json:"feed_id"` FeedUrl string `json:"feed_url"` } if r.Method != http.MethodPost { http.Error(w, "Not allowed", http.StatusMethodNotAllowed) return } var inputs []Input err := json.NewDecoder(r.Body).Decode(&inputs) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) } for _, input := range inputs { fmt.Fprintf(w, "%s", input.FeedUrl) } } func init() { http.HandleFunc("/ping", handlePing) http.HandleFunc("/handle", handleRequest) }
Use ‘transformPropsIntoState’, the method was renamed.
import { assert } from 'chai'; import cloneDeep from 'lodash/cloneDeep'; import Attributes from '../Attributes'; import defaultTheme from '../../theme'; describe('Attributes', () => { describe('#processProps', () => { describe('It doesn\'t mutate the default theme', () => { let expectedDefaultTheme; before(() => { expectedDefaultTheme = cloneDeep(defaultTheme); Attributes.prototype.transformPropsIntoState.apply( Attributes.prototype, [ { theme: { KEY_COLOR: 'red', }, element: { element: 'object', meta: {}, content: [], }, }, ] ); }); it('Default theme has not been mutated', () => { assert.deepEqual(defaultTheme, expectedDefaultTheme); }); }); }); });
import { assert } from 'chai'; import cloneDeep from 'lodash/cloneDeep'; import Attributes from '../Attributes'; import defaultTheme from '../../theme'; describe('Attributes', () => { describe('#processProps', () => { describe('It doesn\'t mutate the default theme', () => { let expectedDefaultTheme; before(() => { expectedDefaultTheme = cloneDeep(defaultTheme); Attributes.prototype.processProps.apply( Attributes.prototype, [ { theme: { KEY_COLOR: 'red', }, element: { element: 'object', meta: {}, content: [], }, }, ] ); }); it('Default theme has not been mutated', () => { assert.deepEqual(defaultTheme, expectedDefaultTheme); }); }); }); });
Fix exception when running install-task
from base import BaseMethod from fabric.api import * from lib.utils import SSHTunnel, RemoteSSHTunnel from fabric.colors import green, red from lib import configuration import copy class DrupalConsoleMethod(BaseMethod): @staticmethod def supports(methodName): return methodName == 'drupalconsole' def install(self, config, **kwargs): with cd(config['tmpFolder']): run('curl https://drupalconsole.com/installer -L -o drupal.phar') run('mv drupal.phar /usr/local/bin/drupal') run('chmod +x /usr/local/bin/drupal') run('drupal init') print green('Drupal Console installed successfully.') def run_drupalconsole(self, config, command): with cd(config['rootFolder']): run('drupal %s' % command) def drupalconsole(self, config, **kwargs): if kwargs['command'] == 'install': self.install(config) return self.run_drupalconsole(config, kwargs['command'])
from base import BaseMethod from fabric.api import * from lib.utils import SSHTunnel, RemoteSSHTunnel from fabric.colors import green, red from lib import configuration import copy class DrupalConsoleMethod(BaseMethod): @staticmethod def supports(methodName): return methodName == 'drupalconsole' def install(self, config): with cd(config['tmpFolder']): run('curl https://drupalconsole.com/installer -L -o drupal.phar') run('mv drupal.phar /usr/local/bin/drupal') run('chmod +x /usr/local/bin/drupal') run('drupal init') print green('Drupal Console installed successfully.') def run_drupalconsole(self, config, command): with cd(config['rootFolder']): run('drupal %s' % command) def drupalconsole(self, config, **kwargs): if kwargs['command'] == 'install': self.install(config) return self.run_drupalconsole(config, kwargs['command'])
Use node instead webpack to launch Browsersync session
#!/usr/bin/env node const {spawn} = require('child_process'); const exit = require('signal-exit'); const output = require('./../lib/helpers/output'); const params = ['node_modules/redukt/lib/webpack.watch.js', '--colors', '--watch']; const node = spawn('node', params, { detached: true, stdio: ['ignore', 'pipe', 'pipe'], }); node.stdout.on('data', (data) => { const text = output.data(data); if (text.indexOf('DONE') !== -1 || text.indexOf('WAIT') !== -1 || text.indexOf('WARNING') !== -1) { console.clear(); } output.write(text); }) node.stderr.on('data', (data) => { const text = output.error(data); console.clear(); text.forEach(line => output.write(line)); }); node.unref(); exit((code, signal) => { node.kill(signal); });
#!/usr/bin/env node const {spawn} = require('child_process'); const exit = require('signal-exit'); const output = require('./../lib/helpers/output'); const params = ['--config=node_modules/redukt/lib/webpack.config.js', '--colors', '--watch', '--hide-modules']; const webpack = spawn('webpack', params, { detached: true, stdio: ['ignore', 'pipe', 'pipe'], }); webpack.stdout.on('data', (data) => { const text = output.data(data); if (text.indexOf('DONE') !== -1 || text.indexOf('WAIT') !== -1 || text.indexOf('WARNING') !== -1) { console.clear(); } output.write(text); }) webpack.stderr.on('data', (data) => { const text = output.error(data); console.clear(); text.forEach(line => output.write(line)); }); webpack.unref(); exit((code, signal) => { webpack.kill(signal); });
Add & implement the optional 'onClick' prop, to provide visual interaction if set
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import { TextSmall } from '../typography'; class ProgressStep extends PureComponent { render() { const { label, active, completed, onClick } = this.props; const classNames = cx(theme['step'], { [theme['is-active']]: active, [theme['is-completed']]: completed, [theme['is-clickable']]: onClick, }); return ( <Box className={classNames} onClick={onClick}> <TextSmall className={theme['step-label']}>{label}</TextSmall> <span className={theme['status-bullet']} /> </Box> ); } } ProgressStep.propTypes = { /** The label for the progress step */ label: PropTypes.string.isRequired, /** Whether or not the step is active */ active: PropTypes.bool.isRequired, /** Whether or not the step has been completed */ completed: PropTypes.bool.isRequired, /** Callback function that is fired when the progress step is clicked */ onClick: PropTypes.func, }; ProgressStep.defaultProps = { active: false, completed: false, }; export default ProgressStep;
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import theme from './theme.css'; import Box from '../box'; import { TextSmall } from '../typography'; class ProgressStep extends PureComponent { render() { const { label, active, completed } = this.props; const classNames = cx(theme['step'], { [theme['is-active']]: active, [theme['is-completed']]: completed, }); return ( <Box className={classNames}> <TextSmall className={theme['step-label']}>{label}</TextSmall> <span className={theme['status-bullet']} /> </Box> ); } } ProgressStep.propTypes = { /** The label for the progress step */ label: PropTypes.string.isRequired, /** Whether or not the step is active */ active: PropTypes.bool.isRequired, /** Whether or not the step has been completed */ completed: PropTypes.bool.isRequired, }; ProgressStep.defaultProps = { active: false, completed: false, }; export default ProgressStep;
Fix build URLs on index page
var delegate = require('delegate'); var form = document.querySelector('.component-build-form'); if(form) { var checkboxes = form.querySelectorAll('input[type="checkbox"]'); var buildUrl = form.querySelectorAll('.build-url'); delegate(form, 'input[name^="components"]', 'change', change); function change() { // Get an array of all the components var values = [].map.call(checkboxes, function(el) { if(el.checked) { return el.id; } else { return false; } }); // And filter out any that weren't checked values = values.filter(function(value) { return !!value; }); // Build up a query string var queryString = '?'; values.forEach(function(value, index) { queryString += 'components[' + value + ']=on&'; }); // And stick it in the input fields on the index page [].forEach.call(buildUrl, function(el) { el.value = window.location + 'build' + queryString; }); } }
var delegate = require('delegate'); var form = document.querySelector('.component-build-form'); if(form) { var checkboxes = form.querySelectorAll('input[type="checkbox"]'); var buildUrl = form.querySelectorAll('.build-url'); delegate(form, 'input[name^="components"]', 'change', change); function change() { // Get an array of all the components var values = [].map.call(checkboxes, function(el) { if(el.checked) { return el.id; } else { return false; } }); // And filter out any that weren't checked values = values.filter(function(value) { return !!value; }); // Build up a query string var queryString = '?'; values.forEach(function(value, index) { queryString += 'components[' + index + ']=' + value + '&'; }); // And stick it in the input fields on the index page [].forEach.call(buildUrl, function(el) { el.value = window.location + 'build' + queryString; }); } }
Extend EditText instead of AppCompatEditText
package com.alexstyl.specialdates.search; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.EditText; public class BackKeyEditText extends EditText { public BackKeyEditText(Context context, AttributeSet attrs) { super(context, attrs); } private OnBackKeyPressedListener listener; public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) { this.listener = listener; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) { return true; } return super.onKeyPreIme(keyCode, event); } }
package com.alexstyl.specialdates.search; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.EditText; public class BackKeyEditText extends android.support.v7.widget.AppCompatEditText { public BackKeyEditText(Context context, AttributeSet attrs) { super(context, attrs); } private OnBackKeyPressedListener listener; public void setOnBackKeyPressedListener(OnBackKeyPressedListener listener) { this.listener = listener; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && listener.onBackButtonPressed()) { return true; } return super.onKeyPreIme(keyCode, event); } }
Fix lin. decay NW comment.
package cs437.som.neighborhood; import cs437.som.NeightborhoodWidthFunction; /** * Neighborhood width strategy for self-organizing maps that decays the width * linearly as the iterations progress. * * The exact behavior follows the formula: * w_i * (1 - (-t / t_max)) * where * w_i is the initial width of the neighborhood * t is the current iteration * t_max is the maximum expected iteration */ public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction { private final double initialNeighborhoodWidth; private double expectedIterations = 0.0; public LinearDecayNeighborhoodWidthFunction(double initialWidth) { initialNeighborhoodWidth = initialWidth; } public void setExpectedIterations(int expectedIterations) { this.expectedIterations = expectedIterations; } public double neighborhoodWidth(int iteration) { return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations)); } @Override public String toString() { return "LinearDecayNeighborhoodWidthFunction"; } }
package cs437.som.neighborhood; import cs437.som.NeightborhoodWidthFunction; /** * Neighborhood width strategy for self-organizing maps that decays the width * linearly as the iterations progress. * * The exact behavior follows the formula: * w_i * (1 - (-t / t_max)) * where * w_i is the initial width of the neighborhood * e is the base of the natural logarithm * t is the current iteration * t_max is the maximum expected iteration */ public class LinearDecayNeighborhoodWidthFunction implements NeightborhoodWidthFunction { private final double initialNeighborhoodWidth; private double expectedIterations = 0.0; public LinearDecayNeighborhoodWidthFunction(double initialWidth) { initialNeighborhoodWidth = initialWidth; } public void setExpectedIterations(int expectedIterations) { this.expectedIterations = expectedIterations; } public double neighborhoodWidth(int iteration) { return initialNeighborhoodWidth * (1.0 - (iteration / expectedIterations)); } @Override public String toString() { return "LinearDecayNeighborhoodWidthFunction"; } }
Rename some things to avoid name conflicts
package models import ( "time" ) // ProjectStatus is a type alias which will be used to create an enum of acceptable project status states. type ProjectStatus string // ProjectStatus pseudo-enum values const ( PStatusPublished ProjectStatus = "published" PStatuses = []ProjectStatus{StatusPublished} ) // Errors pertaining to the data in a Project or operations on Projects. var ( ErrInvalidProjectStatus = fmt.Errorf("Project status must be one of the following: %s\n", strings.Join([]string(PStatuses), ", ")) ) // Project contains information about a scanlation project, which has a human-readable name, a unique shorthand name, // and a publishing status amongst other things. type Project struct { Id string `json:"id"` Name string `json:"name"` Shorthand string `json:"projectName"` Description string `json:"description"` Status ProjectStatus `json:"status"` CreatedAt time.Time `json:"createdAt"` } // Validate checks that the "status" of the project is one of the accepted ProjectStatus values. func (p Project) Validate() error { for _, status := range PStatuses { if p.Status == status { return nil } } return ErrInvalidProjectStatus }
package models import ( "time" ) // ProjectStatus is a type alias which will be used to create an enum of acceptable project status states. type ProjectStatus string // ProjectStatus pseudo-enum values const ( StatusPublished ProjectStatus = "published" Statuses = []ProjectStatus{StatusPublished} ) // Errors pertaining to the data in a Project or operations on Projects. var ( ErrInvalidProjectStatus = fmt.Errorf("Project status must be one of the following: %s\n", strings.Join([]string(Statuses), ", ")) ) // Project contains information about a scanlation project, which has a human-readable name, a unique shorthand name, // and a publishing status amongst other things. type Project struct { Id string `json:"id"` Name string `json:"name"` Shorthand string `json:"projectName"` Description string `json:"description"` Status ProjectStatus `json:"status"` CreatedAt time.Time `json:"createdAt"` } // Validate checks that the "status" of the project is one of the accepted ProjectStatus values. func (p Project) Validate() error { for _, status := range Statuses { if p.Status == status { return nil } } return ErrInvalidProjectStatus }
Core: Enable modifying orders with taxes Refs SHOOP-2338 / SHOOP-2578
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.db.transaction import atomic from shoop.core.models import Order from ._creator import OrderProcessor class OrderModifier(OrderProcessor): @atomic def update_order_from_source(self, order_source, order): data = self.get_source_base_data(order_source) Order.objects.filter(pk=order.pk).update(**data) order = Order.objects.get(pk=order.pk) for line in order.lines.all(): line.taxes.all().delete() # Delete all tax lines before OrderLine's line.delete() return self.finalize_creation(order, order_source)
# -*- coding: utf-8 -*- # This file is part of Shoop. # # Copyright (c) 2012-2016, Shoop Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. from django.db.transaction import atomic from shoop.core.models import Order from ._creator import OrderProcessor class OrderModifier(OrderProcessor): @atomic def update_order_from_source(self, order_source, order): data = self.get_source_base_data(order_source) Order.objects.filter(pk=order.pk).update(**data) order = Order.objects.get(pk=order.pk) for line in order.lines.all(): line.delete() return self.finalize_creation(order, order_source)
Clean up temporary package.json files.
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, unlink, } from "../fs/files.js"; const INSTALL_JOB_MESSAGE = "installing dependencies from package.json"; export function install(appDir) { const packageJsonPath = pathJoin(appDir, "package.json"); const needTempPackageJson = ! statOrNull(packageJsonPath); if (needTempPackageJson) { const { dependencies } = require("../static-assets/skel/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( packageJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } const ok = buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(["install"], appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); if (needTempPackageJson) { // Clean up the temporary package.json file created above. unlink(packageJsonPath); } return ok; }
import buildmessage from "../utils/buildmessage.js"; import { pathJoin, statOrNull, writeFile, } from "../fs/files.js"; const INSTALL_JOB_MESSAGE = "installing dependencies from package.json"; export function install(appDir) { const testAppPkgJsonPath = pathJoin(appDir, "package.json"); if (! statOrNull(testAppPkgJsonPath)) { const { dependencies } = require("../static-assets/skel/package.json"); // Write a minimial package.json with the same dependencies as the // default new-app package.json file. writeFile( testAppPkgJsonPath, JSON.stringify({ dependencies }, null, 2) + "\n", "utf8", ); } return buildmessage.enterJob(INSTALL_JOB_MESSAGE, function () { const { runNpmCommand } = require("../isobuild/meteor-npm.js"); const installResult = runNpmCommand(["install"], appDir); if (! installResult.success) { buildmessage.error( "Could not install npm dependencies for test-packages: " + installResult.error); return false; } return true; }); }
Update site URL; update documentation; simplify getSiteUniqueKey()
<?php /** * Extension to sCache. * * @copyright Copyright (c) 2011 Poluza. * @author Andrew Udvare [au] <andrew@poluza.com> * @license http://www.opensource.org/licenses/mit-license.php * * @package Sutra * @link http://www.sutralib.com/ * * @version 1.01 */ class sCache extends fCache { /** * The current working directory. * * @var string */ private static $cwd = ''; /** * Initialises the class. * * @return void */ private static function initialize() { if (!self::$cwd) { self::$cwd = getcwd(); } } /** * Get a key unique to the site. * * @param string $key Key to use. * @param string $prefix Class prefix to use. If not specified, 'sCache' will * be used. * @return string Key that can be used for cache storage. */ public static function getSiteUniqueKey($key, $prefix = NULL) { self::initialize(); if (is_null($prefix)) { $prefix = __CLASS__; } return $prefix.'::'.self::$cwd.'::'.$key; } }
<?php /** * Singleton class to manage Sutra-specific cache. * * @copyright Copyright (c) 2011 Poluza. * @author Andrew Udvare [au] <andrew@poluza.com> * @license http://www.opensource.org/licenses/mit-license.php * * @package Sutra * @link http://www.example.com/ * * @version 1.0 */ class sCache extends fCache { /** * The current working directory. * * @var string */ private static $cwd = ''; /** * Initialises the class. * * @return void */ private static function initialize() { if (!self::$cwd) { self::$cwd = getcwd(); } } /** * Get a key unique to the site. * * @param string $key Key to use. * @param string $class_prefix Class prefix to use. If not specified, sCache * will be used. * @return string Key that can be used for cache storage. */ public static function getSiteUniqueKey($key, $class_prefix = NULL) { self::initialize(); if (is_null($class_prefix)) { $class_prefix = __CLASS__; } return $class_prefix.'::'.self::$cwd.'::'.$key; } }
Fix url to real production url
const LifeforcePlugin = require("../utils/LifeforcePlugin.js"); //const serverhostname = "http://localhost:16001"; const serverhostname = "https://api.repkam09.com"; class MetaEndpoints extends LifeforcePlugin { constructor(restifyserver, logger, name) { super(restifyserver, logger, name); this.apiMap = [ { path: "/api/about", type: "get", handler: handleAboutApi }, { path: "/", type: "get", handler: handleAboutApi } ]; } } function handleAboutApi(req, res, next) { var apis = []; var keys = Object.keys(this.restifyserver.router.mounts); keys.forEach((key) => { var current = this.restifyserver.router.mounts[key]; apis.push({ path: serverhostname + current.spec.path, method: current.method }); }); res.send(200, apis); } module.exports = MetaEndpoints;
const LifeforcePlugin = require("../utils/LifeforcePlugin.js"); const serverhostname = "http://localhost:16001"; //const serverhostname = "https://api.repkam09.com"; class MetaEndpoints extends LifeforcePlugin { constructor(restifyserver, logger, name) { super(restifyserver, logger, name); this.apiMap = [ { path: "/api/about", type: "get", handler: handleAboutApi }, { path: "/", type: "get", handler: handleAboutApi } ]; } } function handleAboutApi(req, res, next) { var apis = []; var keys = Object.keys(this.restifyserver.router.mounts); keys.forEach((key) => { var current = this.restifyserver.router.mounts[key]; apis.push({ path: serverhostname + current.spec.path, method: current.method }); }); res.send(200, apis); } module.exports = MetaEndpoints;
Change pretty-text2 choices dropdown to look like a link instead of a button
'use strict'; var React = require('react/addons'); var _ = require('underscore'); /* Choices drop down component for picking tags. */ var ChoicesDropdown = React.createClass({ handleClick: function (key) { this.props.handleSelection(key); }, render: function() { var self = this; var items = []; var index = 0; var choices = this.props.choices; var len = Object.keys(choices).length; _.each(choices, function (value, key) { index++; var clickHandler = self.handleClick.bind(self, key); items.push( <li key={key} onClick={clickHandler}> <a tabIndex="-1"><span><strong>{value}</strong></span> | <span><em>{key}</em></span></a> </li> ); if (index < len) { var dividerKey = '_' + index; // squelch React warning about needing a key items.push(<li key={dividerKey} role="presentation" className="divider" />); } }); return ( <div className="dropdown"> <a href="#" className="dropdown-toggle" data-toggle="dropdown">Insert...</a> <ul className="dropdown-menu"> {items} </ul> </div> ); } }); module.exports = ChoicesDropdown;
'use strict'; var React = require('react/addons'); var _ = require('underscore'); /* Choices drop down component for picking tags. */ var ChoicesDropdown = React.createClass({ handleClick: function (key) { this.props.handleSelection(key); }, render: function() { var self = this; var items = _.map(this.props.choices, function (value, key) { var clickHandler = self.handleClick.bind(self, key); return ( <li key={key} onClick={clickHandler}> <a tabIndex="-1"><span><strong>{value}</strong></span> | <span><em>{key}</em></span></a> </li> ); }); return ( <div className="dropdown"> <button className="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown"> <span>Insert...</span> <span className="caret"></span> </button> <ul className="dropdown-menu"> {items} </ul> </div> ); } }); module.exports = ChoicesDropdown;
Fix call to observe_if_calendar_available() from window.setTimeout
var calendar_grid = document.querySelector('div[role="grid"]'); var body = document.querySelector('body'); var disable_scroll = function () { $('div[role="grid"]').on('mousewheel', function (e) { if (e.target.id == 'el') return; e.preventDefault(); e.stopPropagation(); }); }; var mutation_breaks_scroll_blocker = function (mutation) { if (mutation.attributeName && mutation.attributeName == 'data-viewfamily') { if ($('body').attr('data-viewfamily') == 'EVENT') return true; } }; var calendar_observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation_breaks_scroll_blocker(mutation)) { disable_scroll(); } }); }); var observe_if_calendar_available = function () { if (!calendar_grid) { window.setTimeout(observe_if_calendar_available, 500); return; } calendar_observer.observe(body, {attributes: true}); }; $(document).ready(function () { observe_if_calendar_available(); });
var calendar_grid = document.querySelector('div[role="grid"]'); var body = document.querySelector('body'); var disable_scroll = function () { // Get a handle on the calendar grid $('div[role="grid"]').on('mousewheel', function (e) { // Scrolling.... hahhahahaha I don't think so if (e.target.id == 'el') return; e.preventDefault(); e.stopPropagation(); }); }; var mutation_breaks_scroll_blocker = function (mutation) { if (mutation.attributeName && mutation.attributeName == 'data-viewfamily') { if ($('body').attr('data-viewfamily') == 'EVENT') return true; } }; var calendar_observer = new MutationObserver(function (mutations) { mutations.forEach(function (mutation) { if (mutation_breaks_scroll_blocker(mutation)) { disable_scroll(); } }); }); // Wait for the first part of the page to load $(document).ready(function () { if (!calendar_grid) { window.setTimeout(observe_if_calendar_available, 500); return; } // start observer calendar_observer.observe(body, {attributes: true}); });
Use border-box style for all elements
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` html { box-sizing: border-box; } *, *:before, *:after { box-sizing: inherit; } body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; overscroll-behavior-y: none; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
import React from 'react' import ReactDOM from 'react-dom' import { createGlobalStyle } from 'styled-components' import { App } from './App' import woff2 from './fonts/source-sans-pro-v11-latin-regular.woff2' import woff from './fonts/source-sans-pro-v11-latin-regular.woff' import registerServiceWorker from './registerServiceWorker' const GlobalStyle = createGlobalStyle` body { margin: 0; padding: 0; font-family: 'Source Sans Pro', sans-serif; overscroll-behavior-y: none; } /* source-sans-pro-regular - latin */ @font-face { font-family: 'Source Sans Pro'; font-style: normal; font-weight: 400; font-display: optional; src: local('Source Sans Pro Regular'), local('SourceSansPro-Regular'), url(${woff2}) format('woff2'), /* Chrome 26+, Opera 23+, Firefox 39+ */ url(${woff}) format('woff'); /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */ } ` ReactDOM.render( <> <GlobalStyle /> <App /> </>, document.getElementById('root') ) registerServiceWorker()
Fix having ver info written twice (divergence). Makes "mk cut_a_release" ver update work.
#!/usr/bin/env python # Copyright (c) 2008-2010 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A small Django app that provides template tags for Markdown using the python-markdown2 library. See <http://github.com/trentm/django-markdown-deux> for more info. """ __version_info__ = (1, 0, 2) __version__ = '.'.join(map(str, __version_info__)) __author__ = "Trent Mick" def markdown(text, style="default"): if not text: return "" import markdown2 return markdown2.markdown(text, **get_style(style)) def get_style(style): from markdown_deux.conf import settings try: return settings.MARKDOWN_DEUX_STYLES[style] except KeyError: return settings.MARKDOWN_DEUX_STYLES.get("default", settings.MARKDOWN_DEUX_DEFAULT_STYLE)
#!/usr/bin/env python # Copyright (c) 2008-2010 ActiveState Corp. # License: MIT (http://www.opensource.org/licenses/mit-license.php) r"""A small Django app that provides template tags for Markdown using the python-markdown2 library. See <http://github.com/trentm/django-markdown-deux> for more info. """ __version_info__ = (1, 0, 2) __version__ = '1.0.1' __author__ = "Trent Mick" def markdown(text, style="default"): if not text: return "" import markdown2 print "XXX markdown_deux.markdown(style=%r) -> %r" % (style, get_style(style)) return markdown2.markdown(text, **get_style(style)) def get_style(style): from markdown_deux.conf import settings try: return settings.MARKDOWN_DEUX_STYLES[style] except KeyError: return settings.MARKDOWN_DEUX_STYLES.get("default", settings.MARKDOWN_DEUX_DEFAULT_STYLE)
Fix Document class unknown in migration
<?php use Phinx\Migration\AbstractMigration; use Pragma\Docs\Models\Document; class AddUidToDocuments extends AbstractMigration { public function change() { $strategy = defined('ORM_UID_STRATEGY') && ORM_UID_STRATEGY == 'mysql' ? 'mysql' : 'php'; $table = $this->table('documents'); $table->addColumn("uid", "string") ->update(); $docs = Document::all(); if(!empty($docs)){ foreach($docs as $d){ $path_elems = explode('/', $d->path); if(!empty($path_elems)){ $file = array_pop($path_elems); $uid = substr($file, 0, strlen($file) - (strlen($d->extension) + 1) ); $d->uid = $uid; $d->save(); } else{ continue; } } } } }
<?php use Phinx\Migration\AbstractMigration; class AddUidToDocuments extends AbstractMigration { public function change() { $strategy = defined('ORM_UID_STRATEGY') && ORM_UID_STRATEGY == 'mysql' ? 'mysql' : 'php'; $table = $this->table('documents'); $table->addColumn("uid", "string") ->update(); $docs = Document::all(); if(!empty($docs)){ foreach($docs as $d){ $path_elems = explode('/', $d->path); if(!empty($path_elems)){ $file = array_pop($path_elems); $uid = substr($file, 0, strlen($file) - (strlen($d->extension) + 1) ); $d->uid = $uid; $d->save(); } else{ continue; } } } } }
Make the access check code a bit more readable. git-svn-id: ed609ce04ec9e3c0bc25e071e87814dd6d976548@383 c7a0535c-eda6-11de-83d8-6d5adf01d787
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.field; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (field(access).isNotPrivate() && field(access).isNotFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } return super.visitField(access, name, desc, signature, value); } }
/* * Mutability Detector * * Copyright 2009 Graham Allan * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.mutabilitydetector.checkers; import static org.mutabilitydetector.checkers.AccessModifierQuery.method; import org.mutabilitydetector.MutabilityReason; import org.objectweb.asm.FieldVisitor; public class PublishedNonFinalFieldChecker extends AbstractMutabilityChecker { @Override public FieldVisitor visitField(int access, String name, String desc, String signature, Object value) { if (method(access).isNotPrivate()){ if (!method(access).isFinal()) { addResult("Field [" + name + "] is visible outwith this class, and is not declared final.", null, MutabilityReason.PUBLISHED_NON_FINAL_FIELD); } } return super.visitField(access, name, desc, signature, value); } }
Put use declaration on two lines
<?php namespace Hipay\MiraklConnector\Api\Hipay; use Hipay\MiraklConnector\Api\ConfigurationInterface as BaseConfigurationInterface; /** * File Config.php * * @author Ivanis Kouamé <ivanis.kouame@smile.fr> * @copyright 2015 Smile */ interface ConfigurationInterface extends BaseConfigurationInterface { /** * Returns the web service login given by HiPay * @return string */ public function getWebServiceLogin(); /** * Returns the web service password given by HiPay * @return string */ public function getWebServicePassword(); /** * Return the entity given to the merchant by Hipay * @return string */ public function getEntity(); /** * Returns the locale used in the webservice calls */ public function getLocale(); /** * Returns the timezone used in the webservice calls */ public function getTimezone(); }
<?php namespace Hipay\MiraklConnector\Api\Hipay; use Hipay\MiraklConnector\Api\ConfigurationInterface as BaseConfigurationInterface; /** * File Config.php * * @author Ivanis Kouamé <ivanis.kouame@smile.fr> * @copyright 2015 Smile */ interface ConfigurationInterface extends BaseConfigurationInterface { /** * Returns the web service login given by HiPay * @return string */ public function getWebServiceLogin(); /** * Returns the web service password given by HiPay * @return string */ public function getWebServicePassword(); /** * Return the entity given to the merchant by Hipay * @return string */ public function getEntity(); /** * Returns the locale used in the webservice calls */ public function getLocale(); /** * Returns the timezone used in the webservice calls */ public function getTimezone(); }
Fix appending of query params.
<?php namespace Yajra\CMS\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Yajra\CMS\Entities\Category; use Yajra\CMS\Events\CategoryWasViewed; class CategoryController extends Controller { /** * Display an article. * * @param \Yajra\CMS\Entities\Category $category * @param \Illuminate\Http\Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Category $category, Request $request) { $category->increment('hits'); $layout = $request->query('layout', 'blog'); $limit = $request->get('limit', $layout == 'list' ? 10 : 5); /** @var \Illuminate\Contracts\Pagination\Paginator $articles */ $articles = $category->articles()->isNotPage()->latest()->simplePaginate($limit); if ($layout === 'list') { $articles->appends('layout', 'list'); } if ($request->has('limit')) { $articles->appends('limit', $limit); } event(new CategoryWasViewed($category)); return view("category.$layout", compact('category', 'articles', 'limit')); } }
<?php namespace Yajra\CMS\Http\Controllers; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Yajra\CMS\Entities\Category; use Yajra\CMS\Events\CategoryWasViewed; class CategoryController extends Controller { /** * Display an article. * * @param \Yajra\CMS\Entities\Category $category * @param \Illuminate\Http\Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function show(Category $category, Request $request) { $category->increment('hits'); $layout = $request->query('layout', 'blog'); $limit = $request->get('limit', $layout == 'list' ? 10 : 5); $articles = $category->articles()->isNotPage()->latest()->simplePaginate($limit); $path = null; if ($layout === 'list') { $path .= '?layout=list'; $articles->setPath($path); } if ($request->has('limit')) { $path .= '&limit=' . $limit; $articles->setPath($path); } event(new CategoryWasViewed($category)); return view("category.$layout", compact('category', 'articles', 'limit')); } }
Use lists, not delimited strings
var webpack = require( 'webpack' ); module.exports = { entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/index' ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loaders: [ 'react-hot', 'babel' ] } ] }, resolve: { extensions: [ '', '.js', '.jsx' ] }, output: { path: __dirname + '/dest', publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './dest', hot: true }, plugins: [ new webpack.HotModuleReplacementPlugin() ] };
var webpack = require( 'webpack' ); module.exports = { entry: [ 'webpack-dev-server/client?http://localhost:8080', 'webpack/hot/only-dev-server', './src/index.jsx' ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'react-hot!babel' } ] }, resolve: { extensions: [ '', '.js', '.jsx' ] }, output: { path: __dirname + '/dest', publicPath: '/', filename: 'bundle.js' }, devServer: { contentBase: './dest', hot: true }, plugins: [ new webpack.HotModuleReplacementPlugin() ] };
Include mac ipv6 localhost, server address.
<?php // if you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // this check prevents access to debug front controllers that are deployed by accident to production servers. // feel free to remove this, extend it, or make something more sophisticated. if (!in_array(@$_SERVER['REMOTE_ADDR'], array( '127.0.0.1', '::1', 'fe80::1', ))) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'.$_SERVER['REMOTE_ADDR']); } require_once __DIR__.'/../app/bootstrap.php.cache'; require_once __DIR__.'/../app/AppKernel.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $kernel->handle(Request::createFromGlobals())->send();
<?php // if you don't want to setup permissions the proper way, just uncomment the following PHP line // read http://symfony.com/doc/current/book/installation.html#configuration-and-setup for more information //umask(0000); // this check prevents access to debug front controllers that are deployed by accident to production servers. // feel free to remove this, extend it, or make something more sophisticated. if (!in_array(@$_SERVER['REMOTE_ADDR'], array( '127.0.0.1', '::1', ))) { header('HTTP/1.0 403 Forbidden'); exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.'); } require_once __DIR__.'/../app/bootstrap.php.cache'; require_once __DIR__.'/../app/AppKernel.php'; use Symfony\Component\HttpFoundation\Request; $kernel = new AppKernel('dev', true); $kernel->loadClassCache(); $kernel->handle(Request::createFromGlobals())->send();
Add comments about asymptotic normality.
package waldo import "math" // Sample represents data drawn from some distribution. To compute // the Wald statistics we need to have a point estimator function // (e.g., the maximum likelihood estimator (MLE)) // as well as the sampling distribution's variance. Recall // that the sampling distribution is defined as the distribution of // the point estimator. // // The estimator in question should be // asymptotically normal, which is to say that the difference between // the estimator (as a random variable of the data size) and the parameter // being estimated over the standard error of the estimator converges // in distribution to a standard normal distribution. type Sample interface { Estimator() float64 Variance() float64 } // sample converts a pair (param estimate, variance) into // a Sample implementation. type sample struct { mle float64 variance float64 } func (s sample) Estimator() float64 { return s.mle } func (s sample) Variance() float64 { return s.variance } // NewSample converts a sample parameter estimate and variance into a // struct that implements the Sample interface. func NewSample(estimate, variance float64) Sample { return sample{mle: estimate, variance: variance} } // StandardError computes an estimate for the standard error // of a point estimator, as encoded in a Sample. // The standard error is the standard deviation of the estimator's distribution. // SInce the variance of this distribution is estimated, hence the overall // calculation itself is an estimate. func StandardError(s Sample) float64 { return math.Pow(s.Variance(), 0.5) }
package waldo import "math" // Sample represents data drawn from some distribution. To compute // the Wald statistics we need to have a point estimator function // (e.g., the maximum likelihood estimator (MLE)) // as well as the sampling distribution's variance. Recall // that the sampling distribution is defined as the distribution of // the point estimator. type Sample interface { Estimator() float64 Variance() float64 } // sample converts a pair (param estimate, variance) into // a Sample implementation. type sample struct { mle float64 variance float64 } func (s sample) Estimator() float64 { return s.mle } func (s sample) Variance() float64 { return s.variance } // NewSample converts a sample parameter estimate and variance into a // struct that implements the Sample interface. func NewSample(estimate, variance float64) Sample { return sample{mle: estimate, variance: variance} } // StandardError computes an estimate for the standard error // of a point estimator, as encoded in a Sample. // The standard error is the standard deviation of the estimator's distribution. // SInce the variance of this distribution is estimated, hence the overall // calculation itself is an estimate. func StandardError(s Sample) float64 { return math.Pow(s.Variance(), 0.5) }
Switch to ES6 Temlate Literals
'use strict'; const google = require('google'); module.exports = exports = {}; const questions = (function() { let methods = {}; methods.search = function(response, convo) { google(response.text, (err, results) => { if(err) { console.log(err); convo.say('Sorry, but an error occurred while attempting to execute your query.'); return convo.next(); } let links = ''; for(let i = 0; i < results.links.length; i++) { let link = results.links[i]; links += `${link.title} - ${link.href} \n\n`; } links = '```' + links + '```'; let message = `Okay I found ${results.links.length} results on ${response.text}, here they are: \n ${links}`; convo.say(message); convo.next(); }); }; methods.what = function(response, convo) { convo.ask('What would you like to know?', (response, convo) => { convo.say(`Okay searching for...${response.text}`); methods.search(response, convo); convo.next(); }) }; return methods; }()); exports.command = (bot, message) => bot.startConversation(message, questions.what);;
'use strict'; const google = require('google'); module.exports = exports = {}; const questions = (function() { let methods = {}; methods.search = function(response, convo) { google(response.text, (err, results) => { if(err) { console.log(err); convo.say('Sorry, but an error occurred while attempting to execute your query.'); return convo.next(); } let links = ''; for(let i = 0; i < results.links.length; i++) { let link = results.links[i]; links += link.title + ' - ' + link.href + "\n\n"; } let message = 'Okay I found ' + results.links.length + ' results on ' + response.text + ', here they are: ' + "\n" + '```' + links + '```'; convo.say(message); convo.next(); }); }; methods.what = function(response, convo) { convo.ask('What would you like to know?', (response, convo) => { convo.say(`Okay searching for...${response.text}`); methods.search(response, convo); convo.next(); }) }; return methods; }()); exports.command = (bot, message) => bot.startConversation(message, questions.what);;
Add awp as an additional shell command
#!/usr/bin/env python # coding=utf-8 from setuptools import setup setup( name='alfred-workflow-packager', version='0.11.0', description='A CLI utility for packaging and exporting Alfred workflows', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'biplist >= 1, < 2', 'jsonschema >= 2, < 3' ], entry_points={ 'console_scripts': [ 'alfred-workflow-packager=awp.main:main', 'workflow-packager=awp.main:main', 'awp=awp.main:main' ] } )
#!/usr/bin/env python # coding=utf-8 from setuptools import setup setup( name='alfred-workflow-packager', version='0.11.0', description='A CLI utility for packaging and exporting Alfred workflows', url='https://github.com/caleb531/alfred-workflow-packager', author='Caleb Evans', author_email='caleb@calebevans.me', license='MIT', keywords='alfred workflow package export', packages=['awp'], package_data={ 'awp': ['data/config-schema.json'] }, install_requires=[ 'biplist >= 1, < 2', 'jsonschema >= 2, < 3' ], entry_points={ 'console_scripts': [ 'alfred-workflow-packager=awp.main:main', 'workflow-packager=awp.main:main' ] } )
Fix embroider build in CI
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const { maybeEmbroider } = require('@embroider/test-setup'); process.env.buildTarget = EmberAddon.env(); module.exports = function (defaults) { const app = new EmberAddon(defaults, { minifyCSS: { enabled: false } }); // This build file specifies the options for the dummy test app of this // addon, located in `/tests/dummy` // This build file does *not* influence how the addon or the app using it // behave. You most likely want to be modifying `./index.js` or app's build file return maybeEmbroider(app, { // Needed for IE11 https://github.com/embroider-build/embroider/issues/731 skipBabel: [ { package: 'qunit', }, ], packageRules: [ { package: 'dummy', components: { '{{foo-select-box}}': { safeToIgnore: true } } } ] }); };
'use strict'; const EmberAddon = require('ember-cli/lib/broccoli/ember-addon'); const { maybeEmbroider } = require('@embroider/test-setup'); process.env.buildTarget = EmberAddon.env(); module.exports = function (defaults) { const app = new EmberAddon(defaults, { minifyCSS: { enabled: false } }); // This build file specifies the options for the dummy test app of this // addon, located in `/tests/dummy` // This build file does *not* influence how the addon or the app using it // behave. You most likely want to be modifying `./index.js` or app's build file return maybeEmbroider(app, { packageRules: [ { package: 'dummy', components: { '{{foo-select-box}}': { safeToIgnore: true } } } ] }); };
Update requests requirement from <2.26,>=2.4.2 to >=2.4.2,<2.27 Updates the requirements on [requests](https://github.com/psf/requests) to permit the latest version. - [Release notes](https://github.com/psf/requests/releases) - [Changelog](https://github.com/psf/requests/blob/master/HISTORY.md) - [Commits](https://github.com/psf/requests/compare/v2.4.2...v2.26.0) --- updated-dependencies: - dependency-name: requests dependency-type: direct:production ... Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@github.com>
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.4.0', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.27', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
from setuptools import setup, find_packages setup( name='panoptes_client', url='https://github.com/zooniverse/panoptes-python-client', author='Adam McMaster', author_email='adam@zooniverse.org', version='1.4.0', packages=find_packages(), include_package_data=True, install_requires=[ 'requests>=2.4.2,<2.26', 'future>=0.16,<0.19', 'python-magic>=0.4,<0.5', 'redo>=1.7', 'six>=1.9', ], extras_require={ 'testing': [ 'mock>=2.0,<4.1', ], 'docs': [ 'sphinx', ], ':python_version == "2.7"': ['futures'], } )
Include missing columns in output
from collections import namedtuple class Termite: def __init__(self, label, color): self.label = label self.color = color self.trail = [] self.tracker = None def to_csv(self): with open('data/{}-trail.csv'.format(self.label), mode='w') as trail_out: trail_out.write('label,frame,time,x,y,xoffset,yoffset\n') for record in self.trail: trail_out.write('{},{},{},{},{},{},{}\n'.format(self.label, record.frame, record.time, record.x, record.y, record.xoffset, record.yoffset))
from collections import namedtuple class Termite: def __init__(self, label, color): self.label = label self.color = color self.trail = [] self.tracker = None def to_csv(self): with open('data/{}-trail.csv'.format(self.label), mode='w') as trail_out: trail_out.write('label,frame,time,x,y\n') for record in self.trail: trail_out.write('{},{},{},{},{},{},{}\n'.format(self.label, record.frame, record.time, record.x, record.y, record.xoffset, record.yoffset))
Add text selection inside 'li' element
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1").extract() dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']/text()").extract() return dataset
from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from dataset import DatasetItem class DatasetSpider(CrawlSpider): name = 'dataset' allowed_domains = ['data.gc.ca/data/en'] start_urls = ['http://data.gc.ca/data/en/dataset?page=1'] rules = [Rule(SgmlLinkExtractor(allow=['/dataset/[0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12}']), 'parse_dataset')] def parse_dataset(self, response): sel = Selector(response) dataset = DatasetItem() dataset['url'] = response.url dataset['name'] = sel.xpath("//div[@class='span-6']/article/div[@class='module'][1]/section[@class='module-content indent-large'][1]/h1").extract() dataset['frequency'] = sel.xpath("//div[@class='span-2']/aside[@class='secondary']/div[@class='module-related'][2]/ul[1]/li[@class='margin-bottom-medium']").extract() return dataset
linkedql: Change name of variable in BuildIdentifier
package linkedql import "github.com/cayleygraph/quad" import "github.com/cayleygraph/quad/voc" // EntityIdentifier is an interface to be used where a single entity identifier is expected. type EntityIdentifier interface { BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) } // EntityIRI is an entity IRI. type EntityIRI quad.IRI // BuildIdentifier implements EntityIdentifier func (iri EntityIRI) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { return quad.IRI(iri).FullWith(ns), nil } // EntityBNode is an entity BNode. type EntityBNode quad.BNode // BuildIdentifier implements EntityIdentifier func (i EntityBNode) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { return quad.BNode(i), nil } // EntityIdentifierString is an entity IRI or BNode strings. type EntityIdentifierString string // BuildIdentifier implements EntityIdentifier func (i EntityIdentifierString) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { identifier, err := parseIdentifier(string(i)) if err != nil { return nil, err } return AbsoluteValue(identifier, ns), nil }
package linkedql import "github.com/cayleygraph/quad" import "github.com/cayleygraph/quad/voc" // EntityIdentifier is an interface to be used where a single entity identifier is expected. type EntityIdentifier interface { BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) } // EntityIRI is an entity IRI. type EntityIRI quad.IRI // BuildIdentifier implements EntityIdentifier func (i EntityIRI) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { return quad.IRI(i).FullWith(ns), nil } // EntityBNode is an entity BNode. type EntityBNode quad.BNode // BuildIdentifier implements EntityIdentifier func (i EntityBNode) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { return quad.BNode(i), nil } // EntityIdentifierString is an entity IRI or BNode strings. type EntityIdentifierString string // BuildIdentifier implements EntityIdentifier func (i EntityIdentifierString) BuildIdentifier(ns *voc.Namespaces) (quad.Value, error) { identifier, err := parseIdentifier(string(i)) if err != nil { return nil, err } return AbsoluteValue(identifier, ns), nil }
Put license at top of file
/* * 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 tech.tablesaw.io.saw; import com.google.common.annotations.Beta; /** * Utilities and constants for reading and writing data in Tablesaw's own compressed, * column-oriented file format aka "saw" */ @Beta class SawUtils { private SawUtils() {} static final String FLOAT = "FLOAT"; static final String DOUBLE = "DOUBLE"; static final String INTEGER = "INTEGER"; static final String LONG = "LONG"; static final String SHORT = "SHORT"; static final String STRING = "STRING"; static final String TEXT = "TEXT"; static final String INSTANT = "INSTANT"; static final String LOCAL_DATE = "LOCAL_DATE"; static final String LOCAL_TIME = "LOCAL_TIME"; static final String LOCAL_DATE_TIME = "LOCAL_DATE_TIME"; static final String BOOLEAN = "BOOLEAN"; }
package tech.tablesaw.io.saw; /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.common.annotations.Beta; /** * Utilities and constants for reading and writing data in Tablesaw's own compressed, * column-oriented file format aka "saw" */ @Beta class SawUtils { private SawUtils() {} static final String FLOAT = "FLOAT"; static final String DOUBLE = "DOUBLE"; static final String INTEGER = "INTEGER"; static final String LONG = "LONG"; static final String SHORT = "SHORT"; static final String STRING = "STRING"; static final String TEXT = "TEXT"; static final String INSTANT = "INSTANT"; static final String LOCAL_DATE = "LOCAL_DATE"; static final String LOCAL_TIME = "LOCAL_TIME"; static final String LOCAL_DATE_TIME = "LOCAL_DATE_TIME"; static final String BOOLEAN = "BOOLEAN"; }
Change development label to dev to match NODE_ENV
const config = { dev: { client: 'sqlite3', connection: { filename: './db/dev.sqlite3' } }, staging: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password' }, pool: { min: 2, max: 10 }, migrations: { tableName: 'knex_migrations' } }, production: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password' }, pool: { min: 2, max: 10 }, migrations: { tableName: 'knex_migrations' } } }; module.exports = config;
const config = { development: { client: 'sqlite3', connection: { filename: './db/dev.sqlite3' } }, staging: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password' }, pool: { min: 2, max: 10 }, migrations: { tableName: 'knex_migrations' } }, production: { client: 'postgresql', connection: { database: 'my_db', user: 'username', password: 'password' }, pool: { min: 2, max: 10 }, migrations: { tableName: 'knex_migrations' } } }; module.exports = config;
controller/examples: Add file/line to log messages Signed-off-by: Jonathan Rudenberg <3692bfa45759a67d83aedf0045f6cb635a966abf@titanous.com>
package main import ( "fmt" "io" "log" "os" ) type config struct { controllerKey string ourPort string logOut io.Writer } func init() { log.SetFlags(log.Lshortfile | log.Lmicroseconds) } func loadConfigFromEnv() (*config, error) { c := &config{} c.controllerKey = os.Getenv("CONTROLLER_KEY") if c.controllerKey == "" { return nil, fmt.Errorf("CONTROLLER_KEY is required") } port := os.Getenv("PORT") if port == "" { port = "4456" } c.ourPort = port if logPath := os.Getenv("LOGFILE"); logPath != "" { if f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err == nil { c.logOut = f } } if c.logOut == nil { c.logOut = os.Stderr } return c, nil }
package main import ( "fmt" "io" "os" ) type config struct { controllerKey string ourPort string logOut io.Writer } func loadConfigFromEnv() (*config, error) { c := &config{} c.controllerKey = os.Getenv("CONTROLLER_KEY") if c.controllerKey == "" { return nil, fmt.Errorf("CONTROLLER_KEY is required") } port := os.Getenv("PORT") if port == "" { port = "4456" } c.ourPort = port if logPath := os.Getenv("LOGFILE"); logPath != "" { if f, err := os.OpenFile(logPath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666); err == nil { c.logOut = f } } if c.logOut == nil { c.logOut = os.Stderr } return c, nil }
Reset world chunks metric to fix accumulating unloaded worlds Signed-off-by: Byron Marohn <72c48d57fac8949117d5a1dd58341ee30497c114@live.com>
package de.sldk.mc.metrics; import io.prometheus.client.Gauge; import org.bukkit.World; import org.bukkit.plugin.Plugin; public class LoadedChunks extends WorldMetric { private static final Gauge LOADED_CHUNKS = Gauge.build() .name(prefix("loaded_chunks_total")) .help("Chunks loaded per world") .labelNames("world") .create(); public LoadedChunks(Plugin plugin) { super(plugin, LOADED_CHUNKS); } @Override protected void clear() { LOADED_CHUNKS.clear(); } @Override public void collect(World world) { LOADED_CHUNKS.labels(world.getName()).set(world.getLoadedChunks().length); } }
package de.sldk.mc.metrics; import io.prometheus.client.Gauge; import org.bukkit.World; import org.bukkit.plugin.Plugin; public class LoadedChunks extends WorldMetric { private static final Gauge LOADED_CHUNKS = Gauge.build() .name(prefix("loaded_chunks_total")) .help("Chunks loaded per world") .labelNames("world") .create(); public LoadedChunks(Plugin plugin) { super(plugin, LOADED_CHUNKS); } @Override protected void clear() { } @Override public void collect(World world) { LOADED_CHUNKS.labels(world.getName()).set(world.getLoadedChunks().length); } }
Fix pass of arguments issue
'use strict'; var assign = require('es5-ext/object/assign') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , captureStackTrace = Error.captureStackTrace , AbstractError; AbstractError = function AbstractError(message/*, code, ext*/) { var ext, code; if (!(this instanceof AbstractError)) { return new AbstractError(message, arguments[1], arguments[2]); } code = arguments[1]; ext = arguments[2]; if (ext == null) { if (code && (typeof code === 'object')) { ext = code; code = null; } } if (ext != null) assign(this, ext); this.message = String(message); if (code != null) this.code = String(code); this.name = this.constructor.name; if (captureStackTrace) captureStackTrace(this, this.constructor); }; if (setPrototypeOf) setPrototypeOf(AbstractError, Error); AbstractError.prototype = Object.create(Error.prototype, { constructor: d(AbstractError) }); module.exports = AbstractError;
'use strict'; var assign = require('es5-ext/object/assign') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , captureStackTrace = Error.captureStackTrace , AbstractError; AbstractError = function AbstractError(message/*, code, ext*/) { var ext, code; if (!(this instanceof AbstractError)) { return new AbstractError(message, code, arguments[2]); } code = arguments[1]; ext = arguments[2]; if (ext == null) { if (code && (typeof code === 'object')) { ext = code; code = null; } } if (ext != null) assign(this, ext); this.message = String(message); if (code != null) this.code = String(code); this.name = this.constructor.name; if (captureStackTrace) captureStackTrace(this, this.constructor); }; if (setPrototypeOf) setPrototypeOf(AbstractError, Error); AbstractError.prototype = Object.create(Error.prototype, { constructor: d(AbstractError) }); module.exports = AbstractError;
Handle array of values for the MAC.
<?php namespace MCordingley\LaravelSapient\Middleware; use Closure; use Illuminate\Http\Request; use MCordingley\LaravelSapient\Contracts\KeyResolver; use ParagonIE\ConstantTime\Base64UrlSafe; use ParagonIE\Sapient\CryptographyKeys\SigningPublicKey; use Symfony\Component\HttpFoundation\Response; final class VerifyRequest { /** @var KeyResolver */ private $resolver; /** * @param KeyResolver $resolver */ public function __construct(KeyResolver $resolver) { $this->resolver = $resolver; } /** * @param Request $request * @param Closure $next * @return Response */ public function handle(Request $request, Closure $next): Response { $key = new SigningPublicKey(Base64UrlSafe::decode($this->resolver->resolveKey())); foreach ($request->headers->get('Body-Signature-Ed25519', null, false) as $signature) { if (sodium_crypto_sign_verify_detached(Base64UrlSafe::decode($signature), $request->getContent(), $key->getString(true))) { return $next($request); } } abort(403, 'Invalid Sapient signature detected.'); } }
<?php namespace MCordingley\LaravelSapient\Middleware; use Closure; use Illuminate\Http\Request; use MCordingley\LaravelSapient\Contracts\KeyResolver; use ParagonIE\ConstantTime\Base64UrlSafe; use ParagonIE\Sapient\CryptographyKeys\SigningPublicKey; use Symfony\Component\HttpFoundation\Response; final class VerifyRequest { /** @var KeyResolver */ private $resolver; /** * @param KeyResolver $resolver */ public function __construct(KeyResolver $resolver) { $this->resolver = $resolver; } /** * @param Request $request * @param Closure $next * @return Response */ public function handle(Request $request, Closure $next): Response { $signature = $request->headers->get('Body-Signature-Ed25519'); $key = new SigningPublicKey(Base64UrlSafe::decode($this->resolver->resolveKey())); if (!sodium_crypto_sign_verify_detached($this->decode($signature), $request->getContent(), $key->getString(true))) { abort(403, 'Invalid Sapient signature detected.'); } return $next($request); } }
Reword package info a bit
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Common data types and utilities for the Spine Event Engine. */ @CheckReturnValue @ParametersAreNonnullByDefault package io.spine; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
/* * Copyright 2018, TeamDev. All rights reserved. * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Common data types and utilities of the Spine Event Engine. */ @CheckReturnValue @ParametersAreNonnullByDefault package io.spine; import com.google.errorprone.annotations.CheckReturnValue; import javax.annotation.ParametersAreNonnullByDefault;
Use let and const instead of var
module.exports = { getRequest: (url, callback) => { let request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = () => { if (request.status >= 200 && request.status < 400) { const data = JSON.parse(request.responseText); callback(data); } else { console.error(url, request.responseText); } }; request.onerror = () => { console.error(url); }; request.send(); }, postJSONRequest: (url, data, callback) => { let request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); request.onload = () => { if (request.status >= 200 && request.status < 400) { const data = JSON.parse(request.responseText); callback(data); } else { console.error(url, request.responseText); } }; request.onerror = () => { console.error(url); }; request.send(JSON.stringify(data)); } };
module.exports = { getRequest: (url, callback) => { var request = new XMLHttpRequest(); request.open('GET', url, true); request.onload = () => { if (request.status >= 200 && request.status < 400) { var data = JSON.parse(request.responseText); callback(data); } else { console.error(url, request.responseText); } }; request.onerror = () => { console.error(url); }; request.send(); }, postJSONRequest: (url, data, callback) => { var request = new XMLHttpRequest(); request.open('POST', url, true); request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); request.onload = () => { if (request.status >= 200 && request.status < 400) { var data = JSON.parse(request.responseText); callback(data); } else { console.error(url, request.responseText); } }; request.onerror = () => { console.error(url); }; request.send(JSON.stringify(data)); } };
Disable ckeditor resizing to get rid of bottom bar
/* globals CKEDITOR */ import Ember from 'ember'; import layout from '../templates/components/ck-editor'; export default Ember.Component.extend({ layout: layout, _editor: null, didInsertElement () { let textarea = this.element.querySelector('.editor'); let editor = this._editor = CKEDITOR.replace(textarea, { language: 'no', // Remove elements path in footer removePlugins: 'elementspath', // Whether to use HTML entities in the output. entities: false, // Disable resizing to get rid of bottom bar resize_enabled: false, toolbar: [ {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat']}, {name: 'styles', items: ['Format']}, {name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Blockquote']}, {name: 'links', items: ['Link', 'Unlink', 'Anchor']}, {name: 'insert', items: ['Table']} ], format_tags: 'p;h2;h3' }); editor.on('change', (e) => { this.set('value', e.editor.getData()); }); }, willDestroyElement () { this._editor.destroy(); this._editor = null; } });
/* globals CKEDITOR */ import Ember from 'ember'; import layout from '../templates/components/ck-editor'; export default Ember.Component.extend({ layout: layout, _editor: null, didInsertElement() { let textarea = this.element.querySelector('.editor'); let editor = this._editor = CKEDITOR.replace(textarea, { language: 'no', // Remove elements path in footer removePlugins: 'elementspath', // Whether to use HTML entities in the output. entities: false, toolbar: [ {name: 'basicstyles', items: ['Bold', 'Italic', 'Underline', 'Strike', '-', 'RemoveFormat']}, {name: 'styles', items: ['Format']}, {name: 'paragraph', items: ['NumberedList', 'BulletedList', '-', 'Blockquote']}, {name: 'links', items: ['Link', 'Unlink', 'Anchor']}, {name: 'insert', items: ['Table']} ], format_tags: 'p;h2;h3' }); editor.on('change', (e) => { this.set('value', e.editor.getData()); }); }, willDestroyElement() { this._editor.destroy(); this._editor = null; } });
Enforce unique user names in the database model Set unique=TRUE and deleted TODO comment line
from django.db import models from common.util.generator import get_random_id class Student(models.Model): username = models.CharField(max_length=7,unique=True) magic_id = models.CharField(max_length=8) child = models.BooleanField() def __str__(self): return self.username def save(self, *args, **kwargs): if len(self.magic_id) == 0: self.magic_id = get_random_id() super(Student, self).save(*args, **kwargs) def get_new_student_popup(self): message = "Email has been sent to %s@ic.ac.uk. Go activate your account." % self.username return {'message': message, 'state': 'success'} def get_existing_student_popup(self): message = "Account already exists. Activation email re-sent to %s@ic.ac.uk." % self.username return {'message': message, 'state': 'warning'}
from django.db import models from common.util.generator import get_random_id class Student(models.Model): # ToDo: Make username unique username = models.CharField(max_length=7) magic_id = models.CharField(max_length=8) child = models.BooleanField() def __str__(self): return self.username def save(self, *args, **kwargs): if len(self.magic_id) == 0: self.magic_id = get_random_id() super(Student, self).save(*args, **kwargs) def get_new_student_popup(self): message = "Email has been sent to %s@ic.ac.uk. Go activate your account." % self.username return {'message': message, 'state': 'success'} def get_existing_student_popup(self): message = "Account already exists. Activation email re-sent to %s@ic.ac.uk." % self.username return {'message': message, 'state': 'warning'}
Set is-ie class on grid root.
import { appendIfMissing } from '@zambezi/d3-utils' import { defaultTemplate } from './basic-grid-template' import { isIE } from './is-ie' import { select } from 'd3-selection' export function createSetupGridTemplate() { const appendStirrup = appendIfMissing('div.zambezi-grid-stirrup') let template = defaultTemplate function setupTemplate(s) { s.each(setupTemplateEach) } setupTemplate.template = function(value) { if (!arguments.length) return template template = value return setupTemplate } return setupTemplate function setupTemplateEach(d, i) { const target = select(this) , stirrup = target.select('.zambezi-grid-stirrup') if (stirrup.empty()) { target.classed('zambezi-grid', true) .classed('is-ie', isIE) .select(appendStirrup) .html(template) } } }
import { defaultTemplate } from './basic-grid-template' import { appendIfMissing } from '@zambezi/d3-utils' import { select } from 'd3-selection' export function createSetupGridTemplate() { const appendStirrup = appendIfMissing('div.zambezi-grid-stirrup') let template = defaultTemplate function setupTemplate(s) { s.each(setupTemplateEach) } setupTemplate.template = function(value) { if (!arguments.length) return template template = value return setupTemplate } return setupTemplate function setupTemplateEach(d, i) { const target = select(this) , stirrup = target.select('.zambezi-grid-stirrup') if (stirrup.empty()) { target.classed('zambezi-grid', true) .select(appendStirrup) .html(template) } } }
Use length instead of property iteration
/* global exports */ "use strict"; // module Data.Foreign // jshint maxparams: 3 exports.parseJSONImpl = function (left, right, str) { try { return right(JSON.parse(str)); } catch (e) { return left(e.toString()); } }; // jshint maxparams: 1 exports.toForeign = function (value) { return value; }; exports.unsafeFromForeign = function (value) { return value; }; exports.typeOf = function (value) { return typeof value; }; exports.tagOf = function (value) { return Object.prototype.toString.call(value).slice(8, -1); }; exports.isNull = function (value) { return value === null; }; exports.isUndefined = function (value) { return value === undefined; }; exports.isArray = Array.isArray || function (value) { return Object.prototype.toString.call(value) === "[object Array]"; }; exports.writeObject = function (fields) { var record = {}; for (var i = 0; i < fields.length; i++) { record[fields[i].key] = fields[i].value; } return record; };
/* global exports */ "use strict"; // module Data.Foreign // jshint maxparams: 3 exports.parseJSONImpl = function (left, right, str) { try { return right(JSON.parse(str)); } catch (e) { return left(e.toString()); } }; // jshint maxparams: 1 exports.toForeign = function (value) { return value; }; exports.unsafeFromForeign = function (value) { return value; }; exports.typeOf = function (value) { return typeof value; }; exports.tagOf = function (value) { return Object.prototype.toString.call(value).slice(8, -1); }; exports.isNull = function (value) { return value === null; }; exports.isUndefined = function (value) { return value === undefined; }; exports.isArray = Array.isArray || function (value) { return Object.prototype.toString.call(value) === "[object Array]"; }; exports.writeObject = function (fields) { var record = {}; for (var i in fields) { record[fields[i].key] = fields[i].value; } return record; };
Add version constraints for all dependencies of accounts-password. This is necessary to allow publishing accounts-password independently of a Meteor release. Note that the npm-bcrypt version has been bumped to 0.8.7_1.
Package.describe({ summary: "Password support for accounts", version: "1.2.13" }); Package.onUse(function(api) { api.use('npm-bcrypt@=0.8.7_1'); api.use([ 'accounts-base@1.2.9', 'srp@1.0.9', 'sha@1.0.8', 'ejson@1.0.12', 'ddp@1.2.5' ], ['client', 'server']); // Export Accounts (etc) to packages using this one. api.imply('accounts-base@1.2.9', ['client', 'server']); api.use('email@1.1.16', ['server']); api.use('random@1.0.10', ['server']); api.use('check@1.2.3'); api.use('underscore@1.0.9'); api.use('ecmascript@0.5.7'); api.addFiles('email_templates.js', 'server'); api.addFiles('password_server.js', 'server'); api.addFiles('password_client.js', 'client'); }); Package.onTest(function(api) { api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker', 'accounts-base', 'random', 'email', 'underscore', 'check', 'ddp', 'ecmascript']); api.addFiles('password_tests_setup.js', 'server'); api.addFiles('password_tests.js', ['client', 'server']); api.addFiles('email_tests_setup.js', 'server'); api.addFiles('email_tests.js', 'client'); });
Package.describe({ summary: "Password support for accounts", version: "1.2.12" }); Package.onUse(function(api) { api.use('npm-bcrypt@=0.8.7'); api.use([ 'accounts-base', 'srp', 'sha', 'ejson', 'ddp' ], ['client', 'server']); // Export Accounts (etc) to packages using this one. api.imply('accounts-base', ['client', 'server']); api.use('email', ['server']); api.use('random', ['server']); api.use('check'); api.use('underscore'); api.use('ecmascript'); api.addFiles('email_templates.js', 'server'); api.addFiles('password_server.js', 'server'); api.addFiles('password_client.js', 'client'); }); Package.onTest(function(api) { api.use(['accounts-password', 'tinytest', 'test-helpers', 'tracker', 'accounts-base', 'random', 'email', 'underscore', 'check', 'ddp', 'ecmascript']); api.addFiles('password_tests_setup.js', 'server'); api.addFiles('password_tests.js', ['client', 'server']); api.addFiles('email_tests_setup.js', 'server'); api.addFiles('email_tests.js', 'client'); });
Use the proper Email validation message
<?php namespace Frontend\Modules\Mailmotor\Domain\Subscription\Command; use Frontend\Core\Language\Locale; use Symfony\Component\Validator\Constraints as Assert; use Frontend\Modules\Mailmotor\Domain\Subscription\Validator\Constraints as MailingListAssert; final class Unsubscription { /** * @var string * * @Assert\NotBlank(message="err.FieldIsRequired") * @Assert\Email(message="err.EmailIsInvalid") * @MailingListAssert\EmailUnsubscription */ public $email; /** * @var Locale */ public $locale; /** * @param Locale $locale * @param null|string $email */ public function __construct(Locale $locale, string $email = null) { $this->locale = $locale; $this->email = $email; } }
<?php namespace Frontend\Modules\Mailmotor\Domain\Subscription\Command; use Frontend\Core\Language\Locale; use Symfony\Component\Validator\Constraints as Assert; use Frontend\Modules\Mailmotor\Domain\Subscription\Validator\Constraints as MailingListAssert; final class Unsubscription { /** * @var string * * @Assert\NotBlank(message="err.FieldIsRequired") * @Assert\Email(message="err.FieldIsRequired") * @MailingListAssert\EmailUnsubscription */ public $email; /** * @var Locale */ public $locale; /** * @param Locale $locale * @param null|string $email */ public function __construct(Locale $locale, string $email = null) { $this->locale = $locale; $this->email = $email; } }
Move from junit to testng for integration tests
package net.kencochrane.raven.log4j; import net.kencochrane.raven.stub.SentryStub; import org.apache.log4j.Logger; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class SentryAppenderIT { private static final Logger logger = Logger.getLogger(SentryAppenderIT.class); private SentryStub sentryStub = new SentryStub(); @AfterMethod public void tearDown() { sentryStub.removeEvents(); } @Test public void testInfoLog() { assertThat(sentryStub.getEventCount(), is(0)); logger.info("This is a test"); assertThat(sentryStub.getEventCount(), is(1)); } @Test public void testChainedExceptions() { assertThat(sentryStub.getEventCount(), is(0)); logger.error("This is an exception", new UnsupportedOperationException("Test", new UnsupportedOperationException())); assertThat(sentryStub.getEventCount(), is(1)); } }
package net.kencochrane.raven.log4j; import net.kencochrane.raven.stub.SentryStub; import org.apache.log4j.Logger; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; public class SentryAppenderIT { private static final Logger logger = Logger.getLogger(SentryAppenderIT.class); private SentryStub sentryStub; @Before public void setUp() { sentryStub = new SentryStub(); sentryStub.removeEvents(); } @After public void tearDown() { sentryStub.removeEvents(); } @Test public void testInfoLog() { assertThat(sentryStub.getEventCount(), is(0)); logger.info("This is a test"); assertThat(sentryStub.getEventCount(), is(1)); } @Test public void testChainedExceptions() { assertThat(sentryStub.getEventCount(), is(0)); logger.error("This is an exception", new UnsupportedOperationException("Test", new UnsupportedOperationException())); assertThat(sentryStub.getEventCount(), is(1)); } }