text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Check if icon template is available before rendering
|
var $ = require('jquery');
var CoreView = require('backbone/core-view');
var iconTemplates = {};
var importAllIconTemplates = function () {
var templates = require.context('./templates', false, /\.tpl$/);
templates.keys().forEach(function (template) {
iconTemplates[template] = templates(template);
});
};
importAllIconTemplates();
module.exports = CoreView.extend({
initialize: function (opts) {
if (!opts || !opts.icon) throw new Error('An icon is required to render IconView');
this.icon = opts.icon;
this.iconTemplate = this._getIconTemplate(this.icon);
if (!this.iconTemplate) {
throw new Error('The selected icon does not have any available template');
}
this.placeholder = opts && opts.placeholder;
},
render: function () {
this.$el.html(this.iconTemplate);
if (this.placeholder) {
var placeholder = $(this.placeholder);
this.$el.removeClass().addClass(placeholder.attr('class'));
placeholder.replaceWith(this.$el);
}
return this;
},
_getIconTemplate: function (icon) {
var iconTemplate = './' + this.icon + '.tpl';
return iconTemplates[iconTemplate];
}
});
|
var $ = require('jquery');
var CoreView = require('backbone/core-view');
var iconTemplates = {};
var importAllIconTemplates = function () {
var templates = require.context('./templates', false, /\.tpl$/);
templates.keys().forEach(function (template) {
iconTemplates[template] = templates(template);
});
};
importAllIconTemplates();
module.exports = CoreView.extend({
initialize: function (opts) {
if (!opts || !opts.icon) throw new Error('An icon is required to render IconView');
this.icon = opts && opts.icon;
this.placeholder = opts && opts.placeholder;
},
render: function () {
var currentIconTemplate = './' + this.icon + '.tpl';
this.$el.html(iconTemplates[currentIconTemplate]());
if (this.placeholder) {
var placeholder = $(this.placeholder);
this.$el.removeClass().addClass(placeholder.attr('class'));
placeholder.replaceWith(this.$el);
}
return this;
}
});
|
Make the compilation return an object instead of a function
Ticket #13
|
#!/usr/bin/env node
/*
* Compiles Hogan templates and prints result to stdout
*/
var hogan = require('../lib/hogan'),
path = require('path'),
fs = require('fs');
// we assume that argv[2] is a list of files, or a directory
// that contains mustache templates
var argv = process.argv.slice(2);
var output = [];
argv.map(function(filePath) {
var fullPath = path.resolve(__dirname, filePath),
openedFile = fs.readFileSync(fullPath, 'utf-8'),
name = path.basename(filePath, '.mustache');
if (openedFile) {
output.push("'" + name + "': new Hogan.Template(" + hogan.compile(openedFile, {asString:true}) + ")");
}
});
process.stdout.write('var HoganTemplates = {' + output.join(',\n') + '};\n');
process.exit(0);
|
#!/usr/bin/env node
/*
* Compiles Hogan templates and prints result to stdout
*/
var hogan = require('../lib/hogan'),
path = require('path'),
fs = require('fs');
// we assume that argv[2] is a list of files, or a directory
// that contains mustache templates
var argv = process.argv.slice(2);
var output = [];
argv.map(function(filePath) {
var fullPath = path.resolve(__dirname, filePath),
openedFile = fs.readFileSync(fullPath, 'utf-8'),
name = path.basename(filePath, '.mustache');
if (openedFile) {
output.push("'" + name + "': " + hogan.compile(openedFile, {asString:true}));
}
});
process.stdout.write('var HoganTemplates = {' + output.join(',\n') + '};\n');
process.exit(0);
|
Make sure the random gif dashboard block is the first one
|
YUI.add('dp-dashboardblockrandomgifplugin', function (Y) {
Y.namespace('DP');
Y.DP.DashboardBlockRandomGifPlugin = Y.Base.create('dpDashboardBlockRandomGifPlugin', Y.Plugin.Base, [], {
initializer: function () {
this.get('host').addBlock(
new Y.DP.DashboardBlockRandomGifView({
priority: 2000
})
);
},
}, {
NS: 'dpDashboardBlockRandomGifPlugin',
});
Y.eZ.PluginRegistry.registerPlugin(
Y.DP.DashboardBlockRandomGifPlugin, ['dashboardBlocksView']
);
});
|
YUI.add('dp-dashboardblockrandomgifplugin', function (Y) {
Y.namespace('DP');
Y.DP.DashboardBlockRandomGifPlugin = Y.Base.create('dpDashboardBlockRandomGifPlugin', Y.Plugin.Base, [], {
initializer: function () {
this.get('host').addBlock(
new Y.DP.DashboardBlockRandomGifView({
priority: 100
})
);
},
}, {
NS: 'dpDashboardBlockRandomGifPlugin',
});
Y.eZ.PluginRegistry.registerPlugin(
Y.DP.DashboardBlockRandomGifPlugin, ['dashboardBlocksView']
);
});
|
Test edit - to check svn email hook
|
import os, glob, string, shutil
from distutils.core import setup
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
|
from distutils.core import setup
import os, glob, string, shutil
# Packages
packages = ['neuroimaging', 'neuroimaging.statistics', 'neuroimaging.image', 'neuroimaging.reference', 'neuroimaging.data', 'neuroimaging.image.formats', 'neuroimaging.image.formats.analyze', 'neuroimaging.fmri', 'neuroimaging.fmri.fmristat', 'neuroimaging.visualization', 'neuroimaging.visualization.cmap']
def main():
setup (name = 'neuroimaging',
version = '0.01a',
description = 'This is a neuroimaging python package',
author = 'Various, one of whom is Jonathan Taylor',
author_email = 'jonathan.taylor@stanford.edu',
ext_package = 'neuroimaging',
packages=packages,
package_dir = {'neuroimaging': 'lib'},
url = 'http://neuroimaging.scipy.org',
long_description =
'''
''')
if __name__ == "__main__":
main()
|
Set array type for PHPStan
|
<?php
declare(strict_types=1);
namespace Budgegeria\Bundle\IntlFormatBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class BudgegeriaIntlFormatExtension extends Extension
{
/**
* @param mixed[] $configs
* @param ContainerBuilder $container
*
* @return void
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
$loader->load('services.xml');
$configuration = new Configuration();
/** @phpstan-var array{locale: string, currency: string} $config */
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('budgegeria_intl_format.locale', $config['locale']);
$container->setParameter('budgegeria_intl_format.currency', $config['currency']);
}
}
|
<?php
declare(strict_types=1);
namespace Budgegeria\Bundle\IntlFormatBundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
class BudgegeriaIntlFormatExtension extends Extension
{
/**
* @param mixed[] $configs
* @param ContainerBuilder $container
*
* @return void
*/
public function load(array $configs, ContainerBuilder $container)
{
$loader = new XmlFileLoader($container, new FileLocator(dirname(__DIR__).'/Resources/config'));
$loader->load('services.xml');
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('budgegeria_intl_format.locale', $config['locale']);
$container->setParameter('budgegeria_intl_format.currency', $config['currency']);
}
}
|
Use a map to calculate the question counts for concepts all in once go and store them on the concept object
This allows us to sort the table by question count and saves us calculating the question count when trying to render each row of the table.
|
'use strict';
module.exports =
/*@ngInject*/
function ConceptsCmsCtrl (
$scope, ConceptsFBService, _
) {
$scope.sortType = 'concept_level_2.name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchConcept = ''; // set the default search/filter term
ConceptsFBService.get().then(function (c) {
$scope.concepts = addQuestionCountToConcepts(c);
});
$scope.getQuestionLength = function (questions) {
return _.keys(questions).length;
};
$scope.getTotalConcepts = function (concepts) {
return _.keys(concepts).length;
};
$scope.getTotalQuestions = function (concepts) {
return _.reduce(concepts, function (sum, c) {
if (_.isNaN(sum)) {
sum = 0;
}
return Number(sum) + Number(_.keys(c.questions).length);
});
};
function addQuestionCountToConcepts (concepts) {
return _.map(concepts, function (c) {
c.questionCount = _.keys(c.questions).length;
return c;
});
};
};
|
'use strict';
module.exports =
/*@ngInject*/
function ConceptsCmsCtrl (
$scope, ConceptsFBService, _
) {
$scope.sortType = 'concept_level_2.name'; // set the default sort type
$scope.sortReverse = false; // set the default sort order
$scope.searchConcept = ''; // set the default search/filter term
ConceptsFBService.get().then(function (c) {
$scope.concepts = c;
});
$scope.getQuestionLength = function (questions) {
return _.keys(questions).length;
};
$scope.getTotalConcepts = function (concepts) {
return _.keys(concepts).length;
};
$scope.getTotalQuestions = function (concepts) {
return _.reduce(concepts, function (sum, c) {
if (_.isNaN(sum)) {
sum = 0;
}
return Number(sum) + Number(_.keys(c.questions).length);
});
};
};
|
Fix processing of empty lines.
|
from __future__ import division, absolute_import, print_function
__all__ = ['Cartfile']
import re
from pathlib2 import Path
from .basic_types import *
from .errors import *
class Cartfile(object):
def __init__(self, specifications=None, overrides=None):
self.specifications = specifications if specifications else []
self.overrides = overrides
def read(self, source):
# type: (Path)
if isinstance(source, Path):
if not source.exists():
raise CartfileNotFound(path=source)
source = source.open().read()
# TODO: This is of course super feeble parsing. URLs with #s in them can break for example
lines = [line.rstrip() for line in source.splitlines()]
lines = [re.sub(r'\#.+', '', line) for line in lines]
lines = [line.strip() for line in lines]
lines = [line for line in lines if line]
self.specifications = [Specification.cartfile_string(line, self.overrides) for line in lines]
def write(self, destination):
# type: (File)
strings = [str(specification) for specification in self.specifications]
string = u'\n'.join(sorted(strings)) + '\n'
destination.write(string)
|
from __future__ import division, absolute_import, print_function
__all__ = ['Cartfile']
import re
from pathlib2 import Path
from .basic_types import *
from .errors import *
class Cartfile(object):
def __init__(self, specifications=None, overrides=None):
self.specifications = specifications if specifications else []
self.overrides = overrides
def read(self, source):
# type: (Path)
if isinstance(source, Path):
if not source.exists():
raise CartfileNotFound(path=source)
source = source.open().read()
# TODO: This is of course super feeble parsing. URLs with #s in them can break for example
lines = [line.rstrip() for line in source.splitlines()]
lines = [re.sub(r'\#.+', '', line) for line in lines]
self.specifications = [Specification.cartfile_string(line, self.overrides) for line in lines]
def write(self, destination):
# type: (File)
strings = [str(specification) for specification in self.specifications]
string = u'\n'.join(sorted(strings)) + '\n'
destination.write(string)
|
Install irccat as pydle-irccat instead.
|
from setuptools import setup, find_packages
import pydle
setup(
name=pydle.__name__,
version=pydle.__version__,
packages=[
'pydle',
'pydle.features',
'pydle.features.rfc1459',
'pydle.features.ircv3_1',
'pydle.features.ircv3_2',
'pydle.utils'
],
requires=['tornado'],
extras_require={
'SASL': 'pure-sasl >=0.1.6' # for pydle.features.sasl
},
entry_points={
'console_scripts': [
'pydle = pydle.utils.run:main',
'ipydle = pydle.utils.console:main',
'pydle-irccat = pydle.utils.irccat:main'
]
},
author='Shiz',
author_email='hi@shiz.me',
url='https://github.com/Shizmob/pydle',
keywords='irc library python3 compact flexible',
description='A compact, flexible and standards-abiding IRC library for Python 3.',
license=pydle.__license__,
zip_safe=True,
test_suite='tests'
)
|
from setuptools import setup, find_packages
import pydle
setup(
name=pydle.__name__,
version=pydle.__version__,
packages=[
'pydle',
'pydle.features',
'pydle.features.rfc1459',
'pydle.features.ircv3_1',
'pydle.features.ircv3_2',
'pydle.utils'
],
requires=['tornado'],
extras_require={
'SASL': 'pure-sasl >=0.1.6' # for pydle.features.sasl
},
entry_points={
'console_scripts': [
'irccat = pydle.utils.irccat:main',
'pydle = pydle.utils.run:main',
'ipydle = pydle.utils.console:main'
]
},
author='Shiz',
author_email='hi@shiz.me',
url='https://github.com/Shizmob/pydle',
keywords='irc library python3 compact flexible',
description='A compact, flexible and standards-abiding IRC library for Python 3.',
license=pydle.__license__,
zip_safe=True,
test_suite='tests'
)
|
Fix other devices not moving to loading page
|
class LobbyController {
constructor($scope, $state, $stateParams, SocketService) {
'ngInject';
this.$state = $state;
this.SocketService = SocketService;
this.roomName = $stateParams.roomName;
$scope.$on('owner_disconnect', function(event, args) {
alert('Computer disconnected from the game. Game ended.');
$state.go('main');
})
this.SocketService.extendedHandler = (message) => {
if(message.type === 'players_ready') {
this.handlePlayersReady();
}
}
}
startGame() {
this.SocketService.send({
type:'players_ready',
role:'player'
});
}
handlePlayersReady() {
this.$state.go('loading');
}
}
export default LobbyController;
|
class LobbyController {
constructor($scope, $state, $stateParams, SocketService) {
'ngInject';
this.$state = $state;
this.SocketService = SocketService;
this.roomName = $stateParams.roomName;
$scope.$on('owner_disconnect', function(event, args) {
alert('Computer disconnected from the game. Game ended.');
$state.go('main');
})
}
startGame() {
this.SocketService.send({
type:'players_ready',
role:'player'
});
this.SocketService.extendedHandler = (message) => {
if(message.type === 'players_ready') {
this.handlePlayersReady();
}
}
}
handlePlayersReady() {
this.$state.go('loading');
}
}
export default LobbyController;
|
Fix for API changes in Jedis
Use `long` primitive instead of boxed type.
|
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key"));
assertEquals(1, redisPerTest.getJedis().incr("key"));
assertEquals(1, myRedis.getJedis().incr("key"));
}
}
|
package org.testcontainers.junit.jupiter.inheritance;
import org.junit.jupiter.api.Test;
import org.testcontainers.junit.jupiter.Container;
import static org.junit.jupiter.api.Assertions.assertEquals;
class InheritedTests extends AbstractTestBase {
@Container
private RedisContainer myRedis = new RedisContainer();
@Test
void step1() {
assertEquals(1, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
@Test
void step2() {
assertEquals(2, redisPerClass.getJedis().incr("key").longValue());
assertEquals(1, redisPerTest.getJedis().incr("key").longValue());
assertEquals(1, myRedis.getJedis().incr("key").longValue());
}
}
|
Set default contact if present
|
/* eslint camelcase: 0 */
const { get, merge, pickBy } = require('lodash')
const { transformInteractionResponseToForm } = require('../transformers')
const { transformDateStringToDateObject } = require('../../transformers')
const { interactionEditFormConfig } = require('../macros')
const { buildFormWithStateAndErrors } = require('../../builders')
function renderEditPage (req, res) {
const interactionData = transformInteractionResponseToForm(res.locals.interaction)
const interactionDefaults = {
dit_adviser: req.session.user,
date: transformDateStringToDateObject(new Date()),
contact: get(res.locals, 'contact.id'),
}
const mergedInteractionData = pickBy(merge({}, interactionDefaults, interactionData, res.locals.requestBody))
const interactionForm =
buildFormWithStateAndErrors(
interactionEditFormConfig(
{
returnLink: res.locals.returnLink,
advisers: get(res.locals, 'advisers.results'),
contacts: res.locals.contacts,
services: res.locals.services,
}),
mergedInteractionData,
get(res.locals, 'form.errors.messages'),
)
res
.breadcrumb(`${interactionData ? 'Edit' : 'Add'} interaction`)
.title(`${interactionData ? 'Edit' : 'Add'} interaction for ${res.locals.entityName}`)
.render('interactions/views/edit', {
interactionForm,
})
}
module.exports = {
renderEditPage,
}
|
/* eslint camelcase: 0 */
const { get, merge, pickBy } = require('lodash')
const { transformInteractionResponseToForm } = require('../transformers')
const { transformDateStringToDateObject } = require('../../transformers')
const { interactionEditFormConfig } = require('../macros')
const { buildFormWithStateAndErrors } = require('../../builders')
function renderEditPage (req, res) {
const interactionData = transformInteractionResponseToForm(res.locals.interaction)
const interactionDefaults = {
dit_adviser: req.session.user,
date: transformDateStringToDateObject(new Date()),
}
const mergedInteractionData = pickBy(merge({}, interactionDefaults, interactionData, res.locals.requestBody))
const interactionForm =
buildFormWithStateAndErrors(
interactionEditFormConfig(
{
returnLink: res.locals.returnLink,
advisers: get(res.locals, 'advisers.results'),
contacts: res.locals.contacts,
services: res.locals.services,
}),
mergedInteractionData,
get(res.locals, 'form.errors.messages'),
)
res
.breadcrumb(`${interactionData ? 'Edit' : 'Add'} interaction`)
.title(`${interactionData ? 'Edit' : 'Add'} interaction for ${res.locals.entityName}`)
.render('interactions/views/edit', {
interactionForm,
})
}
module.exports = {
renderEditPage,
}
|
Update dict and set examples.
|
# Copyright (c) 2013 Jordan Halterman <jordan.halterman@gmail.com>
# See LICENSE for details.
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from active_redis import ActiveRedis
redis = ActiveRedis()
# Create an unnamed list.
mylist = redis.list()
# Append items to the list.
mylist.append('foo')
mylist.append('bar')
# Note that when appending a complex data structure the structure
# will be serialized to JSON when written to Redis. However, the
# structure will still be monitored for changes, so even once a
# list is serialized it can still be mutated, and Active Redis
# will capture changes and re-serialize the list.
mylist.append(['foo', 'bar'])
mylist[2].append('baz')
mylist.delete()
# We can also create a named list by passing a key to the constructor.
mylist = redis.list('mylist')
mylist.append('foo')
del mylist
mylist = redis.list('mylist')
print mylist # [u'foo']
mylist.delete()
print mylist # []
|
# Copyright (c) 2013 Jordan Halterman <jordan.halterman@gmail.com>
# See LICENSE for details.
import sys, os
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from active_redis import ActiveRedis
redis = ActiveRedis()
# Create an unnamed list.
mylist = redis.list()
# Append items to the list.
mylist.append('foo')
mylist.append('bar')
# Note that when appending a complex data structure the structure
# will be serialized to JSON when written to Redis. However, the
# structure will still be monitored for changes, so even once a
# list is serialized it can still be mutated, and Active Redis
# will capture changes and re-serialize the list.
mylist.append(['foo', 'bar'])
mylist[2].append('baz')
# We can also create a named list by passing a key to the constructor.
mylist = redis.list('mylist')
mylist.append('foo')
del mylist
mylist = redis.list('mylist')
print mylist # [u'foo']
mylist.delete()
print mylist # []
|
Use path.public to set 'public' folder location
|
<?php namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class ServeCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';
/**
* The console command description.
*
* @var string
*/
protected $description = "Serve the application on the PHP development server";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
chdir($this->laravel['path.base']);
$host = $this->input->getOption('host');
$port = $this->input->getOption('port');
$public = $this->laravel['path.public'];
$this->info("Laravel development server started on {$host}:{$port}...");
passthru("php -S {$host}:{$port} -t {$public} server.php");
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'),
array('port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000),
);
}
}
|
<?php namespace Illuminate\Foundation\Console;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
class ServeCommand extends Command {
/**
* The console command name.
*
* @var string
*/
protected $name = 'serve';
/**
* The console command description.
*
* @var string
*/
protected $description = "Serve the application on the PHP development server";
/**
* Execute the console command.
*
* @return void
*/
public function fire()
{
chdir($this->laravel['path.base']);
$host = $this->input->getOption('host');
$port = $this->input->getOption('port');
$this->info("Laravel development server started on {$host}:{$port}...");
passthru("php -S {$host}:{$port} -t public server.php");
}
/**
* Get the console command options.
*
* @return array
*/
protected function getOptions()
{
return array(
array('host', null, InputOption::VALUE_OPTIONAL, 'The host address to serve the application on.', 'localhost'),
array('port', null, InputOption::VALUE_OPTIONAL, 'The port to serve the application on.', 8000),
);
}
}
|
Set default token to empty string insted of null
|
import 'babel-polyfill';
import { existsSync } from 'fs';
import { resolve } from 'path';
import merge from 'lodash.merge';
import TipsBot from './Tipsbot';
const tokenPath = resolve(__dirname, '..', '..', 'token.js');
const defaultToken = existsSync(tokenPath) ? require(tokenPath) : '';
const defaultName = 'Tipsbot';
const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json');
const defaultChannel = 'general';
const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday
const defaultStartIndex = 0;
const defaultIconURL = '';
export const create = (options = {}) => {
let defaults = {
token: process.env.BOT_API_KEY || defaultToken,
name: process.env.BOT_NAME || defaultName,
filePath: process.env.BOT_FILE_PATH || defaultTips,
channel: process.env.BOT_CHANNEL || defaultChannel,
schedule: process.env.BOT_SCHEDULE || defaultSchedule,
startIndex: process.env.BOT_START_INDEX || defaultStartIndex,
iconURL: process.env.BOT_ICON_URL || defaultIconURL,
};
return new TipsBot(merge(defaults, options));
}
|
import 'babel-polyfill';
import { existsSync } from 'fs';
import { resolve } from 'path';
import merge from 'lodash.merge';
import TipsBot from './Tipsbot';
const tokenPath = resolve(__dirname, '..', '..', 'token.js');
const defaultToken = existsSync(tokenPath) ? require(tokenPath) : null;
const defaultName = 'Tipsbot';
const defaultTips = resolve(__dirname, '..', '..', 'data', 'pragmatic-programmer.json');
const defaultChannel = 'general';
const defaultSchedule = '0 9 * * 1,2,3,4,5'; // 09:00 on monday-friday
const defaultStartIndex = 0;
const defaultIconURL = '';
export const create = (options = {}) => {
let defaults = {
token: process.env.BOT_API_KEY || defaultToken,
name: process.env.BOT_NAME || defaultName,
filePath: process.env.BOT_FILE_PATH || defaultTips,
channel: process.env.BOT_CHANNEL || defaultChannel,
schedule: process.env.BOT_SCHEDULE || defaultSchedule,
startIndex: process.env.BOT_START_INDEX || defaultStartIndex,
iconURL: process.env.BOT_ICON_URL || defaultIconURL,
};
return new TipsBot(merge(defaults, options));
}
|
Update to WADO Image Loader 2.1.4 because 2.1.3 was broken
|
Package.describe({
name: 'ohif:cornerstone',
summary: 'Cornerstone Web-based Medical Imaging libraries',
version: '0.0.1'
});
Npm.depends({
hammerjs: '2.0.8',
'cornerstone-core': '2.2.4',
'cornerstone-tools': '2.3.3',
'cornerstone-math': '0.1.6',
'dicom-parser': '1.8.0',
'cornerstone-wado-image-loader': '2.1.4'
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.use('ecmascript');
api.addAssets('public/js/cornerstoneWADOImageLoaderCodecs.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.min.js.map', 'client');
api.mainModule('main.js', 'client');
api.export('cornerstone', 'client');
api.export('cornerstoneMath', 'client');
api.export('cornerstoneTools', 'client');
api.export('cornerstoneWADOImageLoader', 'client');
api.export('dicomParser', 'client');
});
|
Package.describe({
name: 'ohif:cornerstone',
summary: 'Cornerstone Web-based Medical Imaging libraries',
version: '0.0.1'
});
Npm.depends({
hammerjs: '2.0.8',
'cornerstone-core': '2.2.4',
'cornerstone-tools': '2.3.3',
'cornerstone-math': '0.1.6',
'dicom-parser': '1.8.0',
'cornerstone-wado-image-loader': '2.1.3'
});
Package.onUse(function(api) {
api.versionsFrom('1.5');
api.use('ecmascript');
api.addAssets('public/js/cornerstoneWADOImageLoaderCodecs.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.es5.js', 'client');
api.addAssets('public/js/cornerstoneWADOImageLoaderWebWorker.min.js.map', 'client');
api.mainModule('main.js', 'client');
api.export('cornerstone', 'client');
api.export('cornerstoneMath', 'client');
api.export('cornerstoneTools', 'client');
api.export('cornerstoneWADOImageLoader', 'client');
api.export('dicomParser', 'client');
});
|
Fix to the GI CDF test, so now all tests from SVN pass
git-svn-id: b371d604c7577be4609d70acd88b8a3995ce0a58@2259 3a8262b2-faa5-11dc-8610-ff947880b6b2
|
package jsx3.xml;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit test for simple App.
*/
public class CdfDocumentTest
{
/**
* Rigorous Test :-)
*/
@Test
public void testApp()
{
CdfDocument document = new CdfDocument("root");
Record record = new Record("US").setAttribute("index", "1");
document.appendRecord(record);
String xml = document.toXml();
assertTrue(xml.startsWith("<data jsxid=\"jsxroot\">"));
assertTrue(xml.contains("<record jsxid=\"US\" index=\"1\"/>"));
assertTrue(xml.contains("</data>"));
}
}
|
package jsx3.xml;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit test for simple App.
*/
public class CdfDocumentTest
{
/**
* Rigorous Test :-)
*/
@Test
public void testApp()
{
CdfDocument document = new CdfDocument("root");
Record record = new Record("US").setAttribute("index", "1");
document.appendRecord(record);
String xml = document.toXml();
assertEquals(xml, "");
}
}
/*
<data jsxid="jsxroot">
<record index="1" jsxid="US" jsxtext="United States"/>
<record index="2" jsxid="UK" jsxtext="United Kingdom"/>
<record index="3" jsxid="AG" jsxtext="Afghanistan"/>
<record index="4" jsxid="AL" jsxtext="Albania"/>
<record index="5" jsxid="AR" jsxtext="Algeria"/>
<record index="6" jsxid="AS" jsxtext="American Samoa"/>
<record index="7" jsxid="AD" jsxtext="Andorra"/>
<record index="8" jsxid="AO" jsxtext="Angola"/>
<record index="9" jsxid="AU" jsxtext="Anguilla"/>
</data>
*/
|
Fix skip to program button markup
|
const About = () => {
return (
<header id="about" className="component">
<a href="/" id="about-mainPageButton">Gå til hovedsiden</a>
<img className="about-header-logo" src="assets/images/online_logo.svg" alt="" />
<h1>Velkommen til Online, linjeforeningen for informatikkstudenter ved <a href="http://ntnu.no/">NTNU</a>.</h1>
<p className="about-description">Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.</p>
<a href="#calendar" className="skipToCalendar">Hopp til program</a>
</header>
);
};
export default About;
|
const About = () => {
return (
<header id="about" className="component">
<a href="/" id="about-mainPageButton">Gå til hovedsiden</a>
<img className="about-header-logo" src="assets/images/online_logo.svg" alt="" />
<h1>Velkommen til Online, linjeforeningen for informatikkstudenter ved <a href="http://ntnu.no/">NTNU</a>.</h1>
<p className="about-description">Det er vi som sørger for at studietiden blir den beste tiden i ditt liv! Vi i Online arrangerer utflukter, turer, fester, holder kurs og bedriftspresentasjoner gjennom hele året.</p>
<a href="#calendar"><button className="skipToCalendar">Hopp til program</button></a>
</header>
);
};
export default About;
|
Refactor - Simplify the call to api
|
# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui.back import http, api_query
from swh.core.json import SWHJSONDecoder
import json
def search(base_url, hashes):
"""Search a content with given hashes.
Args:
hashes, dictionary of hash indexed by key, sha1, sha256, etc...
Returns:
None if no content is found.
An enriched content if the content is found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
def unserialize_result(res):
if res.ok:
output = res.content.decode('utf-8')
return json.loads(output, cls=SWHJSONDecoder) if output else False
return False
q = api_query.api_storage_content_present({'content': hashes})
return http.execute(base_url, q, result_fn=unserialize_result)
|
# Copyright (C) 2015 The Software Heritage developers
# See the AUTHORS file at the top-level directory of this distribution
# License: GNU General Public License version 3, or any later version
# See top-level LICENSE file for more information
from swh.web.ui.back import http, api_query
from swh.core.json import SWHJSONDecoder
import json
def search(base_url, hashes):
"""Search a content with given hashes.
Args:
hashes, dictionary of hash indexed by key, sha1, sha256, etc...
Returns:
None if no content is found.
An enriched content if the content is found.
Raises:
OSError (no route to host), etc... Network issues in general
"""
def unserialize_result(res):
if res.ok:
output = res.content.decode('utf-8')
if output:
h_res = json.loads(output, cls=SWHJSONDecoder)
if h_res:
return h_res['found']
return None
return False
return False
q = api_query.api_storage_content_present({'content': hashes})
return http.execute(base_url, q, result_fn=unserialize_result)
|
Send owner and repo info to enclosing activity when done
|
package com.example.octoissues;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditOwnerRepoDialog extends DialogFragment implements OnEditorActionListener{
public interface EditRepoDialogListener {
void onFinishEditDialog(String owner, String repo);
}
private EditText editOwner;
private EditText editRepo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_owner_repo, container);
editOwner = (EditText) view.findViewById(R.id.owner_name);
editRepo = (EditText) view.findViewById(R.id.repo_name);
getDialog().setTitle("Enter Owner and Repo");
return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (EditorInfo.IME_ACTION_DONE == actionId) {
//Send input owner name and repo name to activity
EditRepoDialogListener activity = (EditRepoDialogListener) getActivity();
activity.onFinishEditDialog(editOwner.getText().toString(), editRepo.getText().toString());
this.dismiss();
return true;
}
return false;
}
}
|
package com.example.octoissues;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
public class EditOwnerRepoDialog extends DialogFragment implements OnEditorActionListener{
public interface EditRepoDialogListener {
void onFinishEditDialog(String inputText);
}
private EditText editOwner;
private EditText editRepo;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_owner_repo, container);
editOwner = (EditText) view.findViewById(R.id.owner_name);
editRepo = (EditText) view.findViewById(R.id.repo_name);
getDialog().setTitle("Enter Owner and Repo");
return view;
}
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
return false;
}
}
|
Add i18n route and route filter
|
<?php
Route::group(['prefix' => LaravelLocalization::setLocale(), 'before' => 'LaravelLocalizationRedirectFilter'], function()
{
Route::group(['prefix' => Config::get('core::core.admin-prefix'), 'namespace' => 'Modules\Workshop\Http\Controllers'],
function () {
Route::get('modules', ['as' => 'dashboard.modules.index', 'uses' => 'ModulesController@index']);
Route::post('modules', ['as' => 'dashboard.modules.store', 'uses' => 'ModulesController@store']);
# Workbench
Route::get('workbench', ['as' => 'dashboard.workbench.index', 'uses' => 'WorkbenchController@index']);
Route::post('generate', ['as' => 'dashboard.workbench.generate.index', 'uses' => 'WorkbenchController@generate']);
Route::post('migrate', ['as' => 'dashboard.workbench.migrate.index', 'uses' => 'WorkbenchController@migrate']);
Route::post('install', ['as' => 'dashboard.workbench.install.index', 'uses' => 'WorkbenchController@install']);
Route::post('seed', ['as' => 'dashboard.workbench.seed.index', 'uses' => 'WorkbenchController@seed']);
}
);
});
|
<?php
Route::group(['prefix' => Config::get('core::core.admin-prefix'), 'namespace' => 'Modules\Workshop\Http\Controllers'],
function () {
Route::get('modules', ['as' => 'dashboard.modules.index', 'uses' => 'ModulesController@index']);
Route::post('modules', ['as' => 'dashboard.modules.store', 'uses' => 'ModulesController@store']);
# Workbench
Route::get('workbench', ['as' => 'dashboard.workbench.index', 'uses' => 'WorkbenchController@index']);
Route::post('generate', ['as' => 'dashboard.workbench.generate.index', 'uses' => 'WorkbenchController@generate']);
Route::post('migrate', ['as' => 'dashboard.workbench.migrate.index', 'uses' => 'WorkbenchController@migrate']);
Route::post('install', ['as' => 'dashboard.workbench.install.index', 'uses' => 'WorkbenchController@install']);
Route::post('seed', ['as' => 'dashboard.workbench.seed.index', 'uses' => 'WorkbenchController@seed']);
}
);
|
Fix critical error - forgot ‘.php’ at the end of the testimonials-cpt.php file call
|
<?php
$includes = array(
'checks.php', // Set up options
'styles.php', // Enqueue our styles
'scripts.php', // Enqueue our scripts
'sidebars.php', // Set up our sidebar
'agi-excerpt.php', // Special excerpt so that includes a read more button
'agi-options-page.php', // Create our options page - Settings => AGI Options
'do-shortcode-widget.php', // Create a widget to do a single shortcode
'menus.php', // Set up our menus
'paging-nav.php', // Set up our paging nav
'theme-features.php', // Set up our theme features
'testimonials-cpt.php', // Set up our Testimonials Custom Post Type
'wp_bootstrap_navwalker.php', // Set up our Custom Walker for Bootstrap 3.x for wp_nav_menu()
'prevent-image-size-attr.php' // Prevent WP from adding Height and Width to images
);
$prefix = 'inc/';
foreach($includes as $include) {
require_once($prefix . $include);
}
|
<?php
$includes = array(
'checks.php', // Set up options
'styles.php', // Enqueue our styles
'scripts.php', // Enqueue our scripts
'sidebars.php', // Set up our sidebar
'agi-excerpt.php', // Special excerpt so that includes a read more button
'agi-options-page.php', // Create our options page - Settings => AGI Options
'do-shortcode-widget.php', // Create a widget to do a single shortcode
'menus.php', // Set up our menus
'paging-nav.php', // Set up our paging nav
'theme-features.php', // Set up our theme features
'testimonials-cpt', // Set up our Testimonials Custom Post Type
'wp_bootstrap_navwalker.php', // Set up our Custom Walker for Bootstrap 3.x for wp_nav_menu()
'prevent-image-size-attr.php' // Prevent WP from adding Height and Width to images
);
$prefix = 'inc/';
foreach($includes as $include) {
require_once($prefix . $include);
}
|
Add another greeting to the initial data.
|
package hello.config.data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import hello.dao.GreetingService;
import hello.entities.Greeting;
@Component
@Profile({ "default", "test" })
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {
private final static Logger log = LoggerFactory.getLogger(InitialDataLoader.class);
private final static String[] TEMPLATES = { "Hello, %s!", "Howdy, %s!" };
@Autowired
private GreetingService greetingService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (greetingService.count() > 0) {
log.info("Database already populated. Skipping data initialization.");
return;
}
for (String template : TEMPLATES) {
Greeting greeting = new Greeting();
greeting.setTemplate(template);
greetingService.save(greeting);
log.info("Added greeting (" + greeting.getId() + "): " + greeting.getTemplate());
}
}
}
|
package hello.config.data;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import hello.dao.GreetingService;
import hello.entities.Greeting;
@Component
@Profile({ "default", "test" })
public class InitialDataLoader implements ApplicationListener<ContextRefreshedEvent> {
private final static Logger log = LoggerFactory.getLogger(InitialDataLoader.class);
private final static String GREETING = "Hello, %s!";
@Autowired
private GreetingService greetingService;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (greetingService.count() > 0) {
log.info("Database already populated. Skipping data initialization.");
return;
}
Greeting greeting = new Greeting();
greeting.setTemplate(GREETING);
greetingService.save(greeting);
log.info("Added greeting (" + greeting.getId() + "): " + greeting.getTemplate());
}
}
|
Add css class for mobile modal canvas.
|
import { Component, $$, domHelpers } from '../dom'
export default class ModalCanvas extends Component {
getActionHandlers () {
return {
cancel: this._cancel,
confirm: this._confirm
}
}
render () {
const { renderModal } = this.state
const { isMobile } = this.props
const el = $$('div', { class: 'sc-modal-canvas' })
if (isMobile) el.addClass('sm-modal-mobile')
if (renderModal) {
el.append(
renderModal().ref('renderedModal')
)
}
// do not let the global context menu handler handle this
el.on('contextmenu', domHelpers.stopAndPrevent)
return el
}
openModal (renderModal) {
// if (this._resolve) throw new Error('Previous modal has not been closed.')
this.setState({ renderModal })
return new Promise((resolve, reject) => {
this._resolve = resolve
})
}
close () {
this._cancel()
}
_cancel () {
this._resolve(null)
this._resolve = null
this.setState({})
this.send('closePopover')
}
_confirm () {
this._resolve(this.refs.renderedModal)
this._resolve = null
this.setState({})
this.send('closePopover')
}
}
|
import { Component, $$, domHelpers } from '../dom'
export default class ModalCanvas extends Component {
getActionHandlers () {
return {
cancel: this._cancel,
confirm: this._confirm
}
}
render () {
const { renderModal } = this.state
const el = $$('div', { class: 'sc-modal-canvas' })
if (renderModal) {
el.append(
renderModal().ref('renderedModal')
)
}
// do not let the global context menu handler handle this
el.on('contextmenu', domHelpers.stopAndPrevent)
return el
}
openModal (renderModal) {
// if (this._resolve) throw new Error('Previous modal has not been closed.')
this.setState({ renderModal })
return new Promise((resolve, reject) => {
this._resolve = resolve
})
}
close () {
this._cancel()
}
_cancel () {
this._resolve(null)
this._resolve = null
this.setState({})
this.send('closePopover')
}
_confirm () {
this._resolve(this.refs.renderedModal)
this._resolve = null
this.setState({})
this.send('closePopover')
}
}
|
Move login page checkbox below buttons
|
@extends('layouts.master')
@section('title', 'Login')
@section('content')
<div class="container-sm jumbotron">
<form method="POST" action="{{ route('login') }}">
<div class="form-group">
<input title="Email" type="email" name="email" class="form-control" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input title="Password" type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="text-center">
<button type="submit" class="btn btn-primary">Login</button>
<a href="{{ route('account.password.email') }}" class="btn btn-default">Forgot Password</a>
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
</div>
{!! csrf_field() !!}
</form>
</div>
@stop
|
@extends('layouts.master')
@section('title', 'Login')
@section('content')
<div class="container-sm jumbotron">
<form method="POST" action="{{ route('login') }}">
<div class="form-group">
<input title="Email" type="email" name="email" class="form-control" placeholder="Email" value="{{ old('email') }}">
</div>
<div class="form-group">
<input title="Password" type="password" name="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="text-center">
<div class="checkbox">
<label>
<input type="checkbox" name="remember"> Remember Me
</label>
</div>
<button type="submit" class="btn btn-primary">Login</button>
<a href="{{ route('account.password.email') }}" class="btn btn-default">Forgot Password</a>
</div>
{!! csrf_field() !!}
</form>
</div>
@stop
|
Apply prettier, eslint to settings files
|
import { AsyncStorage } from 'react-native';
export { MobileAppSettings } from './MobileAppSettings';
export const SETTINGS_KEYS = {
APP_VERSION: 'AppVersion',
CURRENT_LANGUAGE: 'CurrentLanguage',
MOST_RECENT_USERNAME: 'MostRecentUsername',
SUPPLYING_STORE_ID: 'SupplyingStoreId',
SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
SYNC_IS_INITIALISED: 'SyncIsInitialised',
SYNC_PRIOR_FAILED: 'SyncPriorFailed',
SYNC_URL: 'SyncURL',
SYNC_SITE_ID: 'SyncSiteId',
SYNC_SERVER_ID: 'SyncServerId',
SYNC_SITE_NAME: 'SyncSiteName',
SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
THIS_STORE_ID: 'ThisStoreId',
THIS_STORE_NAME_ID: 'ThisStoreNameId',
HARDWARE_UUID: 'Hardware_UUID',
};
export const getAppVersion = async () => {
const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
return appVersion;
};
|
import { AsyncStorage } from 'react-native';
export { MobileAppSettings } from './MobileAppSettings';
export const SETTINGS_KEYS = {
APP_VERSION: 'AppVersion',
CURRENT_LANGUAGE: 'CurrentLanguage',
MOST_RECENT_USERNAME: 'MostRecentUsername',
SUPPLYING_STORE_ID: 'SupplyingStoreId',
SUPPLYING_STORE_NAME_ID: 'SupplyingStoreNameId',
LAST_POST_PROCESSING_FAILED: 'LastPostProcessingFailed',
SYNC_IS_INITIALISED: 'SyncIsInitialised',
SYNC_PRIOR_FAILED: 'SyncPriorFailed',
SYNC_URL: 'SyncURL',
SYNC_SITE_ID: 'SyncSiteId',
SYNC_SERVER_ID: 'SyncServerId',
SYNC_SITE_NAME: 'SyncSiteName',
SYNC_SITE_PASSWORD_HASH: 'SyncSitePasswordHash',
THIS_STORE_ID: 'ThisStoreId',
THIS_STORE_NAME_ID: 'ThisStoreNameId',
HARDWARE_UUID: 'Hardware_UUID',
};
export async function getAppVersion() {
const appVersion = await AsyncStorage.getItem(SETTINGS_KEYS.APP_VERSION);
return appVersion;
}
|
Transform Q and A variables to an Object
|
//On load, .contentBox should contain question #1
// When user enters Answer and hits submit, ask if
//answer matches stored Answer
// An array containing questions and answers
//
var questionAndAnswers ={
questionBank: ["Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"],
answerBank: ["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"]
};
$(document).ready()
var submitButton = $("#submitInput");
var displayQuestion = $("#card");
var nextButton = $("#nextButton");
// var currentQuestion = questionBank[0]
var currentIndex = -1;
nextButton.on("click", function(){
displayQuestion.html(questionAndAnswers.questionBank[currentIndex + 1]);
currentIndex++;
if(currentIndex === 9) {
currentIndex = -1;
}
});
submitButton.on("click", function(){
var userInput = $("#answerInput").val()
if (userInput === answerBank[0]) {
displayQuestion.html(questionBank())
}
});
//
// questionBank.forEach(function(currentQuestion) {
// console.log(currentQuestion)
// });
// //flipping card
// $("#card").flip({
// axis: 'x',
// trigger: 'hover'
// });
|
//On load, .contentBox should contain question #1
// When user enters Answer and hits submit, ask if
//answer matches stored Answer
// An array containing questions and answers
//
var questionBank = ["Q1","Q2","Q3","Q4","Q5","Q6","Q7","Q8","Q9","Q10"];
var answerBank = ["A1","A2","A3","A4","A5","A6","A7","A8","A9","A10"];
$(document).ready()
var submitButton = $("#submitInput");
var displayQuestion = $("#card");
var nextButton = $("#nextButton");
// var currentQuestion = questionBank[0]
var currentIndex = -1;
nextButton.on("click", function(){
displayQuestion.html(questionBank[currentIndex + 1]);
currentIndex++;
if(currentIndex === 9) {
currentIndex = -1;
}
});
submitButton.on("click", function(){
var userInput = $("#answerInput").val()
if (userInput === answerBank[0]) {
displayQuestion.html(questionBank())
}
});
//
// questionBank.forEach(function(currentQuestion) {
// console.log(currentQuestion)
// });
// //flipping card
// $("#card").flip({
// axis: 'x',
// trigger: 'hover'
// });
|
Read Dependencies and inject them
- Create a default route
- Create a flag to customize the route of conf file
- Build the port string
|
package main
import (
"bytes"
"flag"
"fmt"
"github.com/codegangsta/negroni"
"github.com/digital-ocean-service/infraestructure"
"github.com/digital-ocean-service/interfaces"
"github.com/digital-ocean-service/usecases"
"github.com/gorilla/mux"
)
const defaultPath = "/etc/digital-ocean-service.conf"
var confFilePath = flag.String("conf", defaultPath, "Custom path for configuration file")
func main() {
flag.Parse()
config, err := infraestructure.GetConfiguration(*confFilePath)
if err != nil {
fmt.Println(err.Error())
panic("Cannot parse configuration")
}
doInteractor := usecases.DOInteractor{}
handler := interfaces.WebServiceHandler{
Interactor: doInteractor,
ID: config.ClientID,
Secret: config.ClientSecret,
Scopes: config.Scopes,
RedirectURI: config.RedirectURI,
}
r := mux.NewRouter()
r.HandleFunc("/", handler.Login)
r.HandleFunc("/do_callback", handler.DOCallback).Methods("GET")
r.HandleFunc("/keys", handler.ShowKeys).Methods("GET")
r.HandleFunc("/keys", handler.CreateKey).Methods("POST")
r.HandleFunc("/droplets", handler.CreateDroplet).Methods("POST")
r.HandleFunc("/droplets", handler.ListDroplets).Methods("GET")
n := negroni.Classic()
n.UseHandler(r)
port := bytes.Buffer{}
port.WriteString(":")
port.WriteString(config.Port)
n.Run(port.String())
}
|
package main
import (
"github.com/codegangsta/negroni"
"github.com/digital-ocean-service/interfaces"
"github.com/digital-ocean-service/usecases"
"github.com/gorilla/mux"
)
func main() {
doInteractor := usecases.DOInteractor{}
handler := interfaces.WebServiceHandler{
Interactor: doInteractor,
ID: "",
Secret: "",
RedirectURI: "http://localhost:7000/do_callback",
}
r := mux.NewRouter()
r.HandleFunc("/", handler.Login)
r.HandleFunc("/do_callback", handler.DOCallback).Methods("GET")
r.HandleFunc("/keys", handler.ShowKeys).Methods("GET")
r.HandleFunc("/keys", handler.CreateKey).Methods("POST")
r.HandleFunc("/droplets", handler.CreateDroplet).Methods("POST")
r.HandleFunc("/droplets", handler.ListDroplets).Methods("GET")
n := negroni.Classic()
n.UseHandler(r)
n.Run(":7000")
}
|
Use hyphenated appname in webpack
|
var path = require("path");
module.exports = {
context: path.join(process.cwd(), "<%= srcFolder %>"),
progress: true,
entry: {
"<%= hAppName %>": "./<%= hAppName %>.ts"
},
devtool: "source-map",
output: {
filename: "[name].js"
},
resolve: {
extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"]
},
module: {
loaders: [
{
test: /\.ts?$/,
loader: "ts-loader"
}
]
}
}
|
var path = require("path");
module.exports = {
context: path.join(process.cwd(), "<%= srcFolder %>"),
progress: true,
entry: {
"<%= appName %>": "./<%= hAppName %>.ts"
},
devtool: "source-map",
output: {
filename: "[name].js"
},
resolve: {
extensions: ["", ".webpack.js", ".web.js", ".ts", ".js"]
},
module: {
loaders: [
{
test: /\.ts?$/,
loader: "ts-loader"
}
]
}
}
|
Comment out 'static' and 'deform' methods; disagreements on long-term API.
|
"""
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
## Commented because I'm unsure of the long-term API.
## If you want to use this, or a more particular one for your
## static package(s), define it in a subclass.
##
# A future version might make 'path' optional, defaulting to
# a value passed to the constructor ("myapp:static/").
#
#def static(self, path, **kw):
# return url.static_url(path, self.request, **kw)
## If you're using the Deform package you may find this useful.
#
#@reify
#def deform(self):
# return url.static_url("deform:static/", self.request)
|
"""
Contributed by Michael Mericikel.
"""
from pyramid.decorator import reify
import pyramid.url as url
class URLGenerator(object):
def __init__(self, context, request):
self.context = context
self.request = request
@reify
def context(self):
return url.resource_url(self.context, self.request)
@reify
def app(self):
return self.request.application_url
def route(self, route_name, *elements, **kw):
return url.route_url(route_name, self.request, *elements, **kw)
# sugar for calling url('home')
__call__ = route
def current(self, *elements, **kw):
return url.current_route_url(self.request, *elements, **kw)
@reify
def static(self):
return url.static_url('baseline:static/', self.request)
@reify
def deform(self):
return url.static_url('deform:static/', self.request)
|
Add git src at top.
|
// https://github.com/odanielson/vector_2d.js
// Copyright 2013, odanielson@github.com
// MIT-license
var Norm = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
}
var Normalize = function(v) {
var norm = Norm(v);
return [v[0] / norm, v[1] / norm];
}
var Subtract = function(a, b) {
return [a[0] - b[0], a[1] - b[1]];
}
var Add = function(a, b) {
return [a[0] + b[0], a[1] + b[1]];
}
var Multiply = function(v, k) {
return [v[0] * k, v[1] * k];
}
var ComplexMultiply = function(v1, v2) {
return [ (v1[0] * v2[0]) - (v1[1] * v2[1]), (v1[0] * v2[1]) + (v2[0] * v1[1]) ];
}
var RotateLeft = function(v) {
return ComplexMultiply(v, [0,-1]);
}
|
// Copyright 2013, odanielson@github.com
// MIT-license
var Norm = function(v) {
return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
}
var Normalize = function(v) {
var norm = Norm(v);
return [v[0] / norm, v[1] / norm];
}
var Subtract = function(a, b) {
return [a[0] - b[0], a[1] - b[1]];
}
var Add = function(a, b) {
return [a[0] + b[0], a[1] + b[1]];
}
var Multiply = function(v, k) {
return [v[0] * k, v[1] * k];
}
var ComplexMultiply = function(v1, v2) {
return [ (v1[0] * v2[0]) - (v1[1] * v2[1]), (v1[0] * v2[1]) + (v2[0] * v1[1]) ];
}
var RotateLeft = function(v) {
return ComplexMultiply(v, [0,-1]);
}
|
Fix malformed data bugs in lookup_term()
|
from merriam_webster.api import CollegiateDictionary, WordNotFoundException
from translate.translate import translate_word
DICTIONARY = CollegiateDictionary('d59bdd56-d417-42d7-906e-6804b3069c90')
def lookup_term(language, term):
# If the language is English, use the Merriam-Webster API.
# Otherwise, use WordReference.
if language == 'en':
try:
response = DICTIONARY.lookup(term)
except WordNotFoundException as e:
# If the word can't be found, use the suggestions as the
# definition.
return e.message
definitions = [
u'({function}) {d}'.format(function=entry.function, d=d)
for entry in response
for d, _ in entry.senses
]
else:
results = translate_word('{}en'.format(language), term)
definitions = []
if results != -1:
for row in results:
# Replace linebreaks with semicolons.
definitions.append(row[1].replace(' \n', '; ').strip())
return ' / '.join(definitions)
|
from merriam_webster.api import CollegiateDictionary, WordNotFoundException
from translate.translate import translate_word
DICTIONARY = CollegiateDictionary('d59bdd56-d417-42d7-906e-6804b3069c90')
def lookup_term(language, term):
# If the language is English, use the Merriam-Webster API.
# Otherwise, use WordReference.
if language == 'en':
try:
response = DICTIONARY.lookup(term)
except WordNotFoundException as e:
# If the word can't be found, use the suggestions as the
# definition.
return e.message
definitions = [
'({function}) {d}'.format(function=entry.function, d=d)
for entry in response
for d, _ in entry.senses
]
else:
results = translate_word('{}en'.format(language), term)
definitions = []
for row in results:
# Replace linebreaks with semicolons.
definitions.append(row[1].replace(' \n', '; ').strip())
return ' / '.join(definitions)
|
Use plain password help text instead of html
|
from django.contrib.auth.password_validation import password_validators_help_texts
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
password = serializers.CharField(label=_("Password"), write_only=True)
class PasswordChangeSerializer(serializers.Serializer):
old_password = serializers.CharField(label=_("Old password"), write_only=True)
new_password1 = serializers.CharField(
label=_("New password"),
help_text=password_validators_help_texts(),
write_only=True,
)
new_password2 = serializers.CharField(
label=_("New password confirmation"), write_only=True
)
|
from django.contrib.auth import password_validation
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
password = serializers.CharField(label=_("Password"), write_only=True)
class PasswordChangeSerializer(serializers.Serializer):
old_password = serializers.CharField(label=_("Old password"), write_only=True)
new_password1 = serializers.CharField(
label=_("New password"),
help_text=password_validation.password_validators_help_text_html(),
write_only=True,
)
new_password2 = serializers.CharField(
label=_("New password confirmation"), write_only=True
)
|
Add question mark to query path.
|
var assert = require('assert');
var fs = require('fs');
var should = require('should');
var ResultsPage = require('./../../lib/results-page');
var Plugin = require('./../../lib/plugin');
var allResultsPages = [],
allPlugins = [];
before(function readPluginFile() {
fs.readFile(__dirname + '/../data/results-page.html', 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
var resultsPage = new ResultsPage(data);
allResultsPages = resultsPage.getAllResultsPages();
allPlugins = resultsPage.getAllPlugins();
});
});
describe('ResultsPage', function() {
describe('#getAllResultsPages()', function() {
it('should return an array of ResultsPage\'s', function() {
for (var i = 1; i <= 614; i++) {
allResultsPages.should.containEql('https://wordpress.org/plugins/search/forms/page/' + i.toString() + '?');
}
});
});
describe('#getAllPlugins()', function() {
it('should return an array of Plugins', function() {
allPlugins.forEach(function(plugin) {
plugin.should.be.an.instanceOf(Plugin);
});
});
});
});
|
var assert = require('assert');
var fs = require('fs');
var should = require('should');
var ResultsPage = require('./../../lib/results-page');
var Plugin = require('./../../lib/plugin');
var allResultsPages = [],
allPlugins = [];
before(function readPluginFile() {
fs.readFile(__dirname + '/../data/results-page.html', 'utf8', function (err, data) {
if (err) {
return console.log(err);
}
var resultsPage = new ResultsPage(data);
allResultsPages = resultsPage.getAllResultsPages();
allPlugins = resultsPage.getAllPlugins();
});
});
describe('ResultsPage', function() {
describe('#getAllResultsPages()', function() {
it('should return an array of ResultsPage\'s', function() {
for (var i = 1; i <= 614; i++) {
allResultsPages.should.containEql('https://wordpress.org/plugins/search/forms/page/' + i.toString());
}
});
});
describe('#getAllPlugins()', function() {
it('should return an array of Plugins', function() {
allPlugins.forEach(function(plugin) {
plugin.should.be.an.instanceOf(Plugin);
});
});
});
});
|
Add shadow to header on all pages.
|
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]-->
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<div class="shadow"></div>
<div class="wrap container" role="document">
<div class="content row">
<div class="main <?php echo roots_main_class(); ?>" role="main">
<?php include roots_template_path(); ?>
</div><!-- /.main -->
<?php if (roots_display_sidebar()) : ?>
<aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary">
<?php include roots_sidebar_path(); ?>
</aside><!-- /.sidebar -->
<?php endif; ?>
</div><!-- /.content -->
</div><!-- /.wrap -->
<?php get_template_part('templates/footer'); ?>
</body>
</html>
|
<?php get_template_part('templates/head'); ?>
<body <?php body_class(); ?>>
<!--[if lt IE 7]><div class="alert">Your browser is <em>ancient!</em> <a href="http://browsehappy.com/">Upgrade to a different browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">install Google Chrome Frame</a> to experience this site.</div><![endif]-->
<?php
do_action('get_header');
get_template_part('templates/header');
?>
<div class="wrap container" role="document">
<div class="content row">
<div class="main <?php echo roots_main_class(); ?>" role="main">
<?php include roots_template_path(); ?>
</div><!-- /.main -->
<?php if (roots_display_sidebar()) : ?>
<aside class="sidebar <?php echo roots_sidebar_class(); ?>" role="complementary">
<?php include roots_sidebar_path(); ?>
</aside><!-- /.sidebar -->
<?php endif; ?>
</div><!-- /.content -->
</div><!-- /.wrap -->
<?php get_template_part('templates/footer'); ?>
</body>
</html>
|
Add ReturnTypeWillChange to JsonSerializable implementation
Signed-off-by: Alexander M. Turek <b1c1d8736f20db3fb6c1c66bb1455ed43909f0d8@derrabus.de>
|
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Marks a content as safe.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Markup implements \Countable, \JsonSerializable
{
private $content;
private $charset;
public function __construct($content, $charset)
{
$this->content = (string) $content;
$this->charset = $charset;
}
public function __toString()
{
return $this->content;
}
/**
* @return int
*/
public function count()
{
return mb_strlen($this->content, $this->charset);
}
#[\ReturnTypeWillChange]
public function jsonSerialize()
{
return $this->content;
}
}
class_alias('Twig\Markup', 'Twig_Markup');
|
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig;
/**
* Marks a content as safe.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Markup implements \Countable, \JsonSerializable
{
private $content;
private $charset;
public function __construct($content, $charset)
{
$this->content = (string) $content;
$this->charset = $charset;
}
public function __toString()
{
return $this->content;
}
/**
* @return int
*/
public function count()
{
return mb_strlen($this->content, $this->charset);
}
public function jsonSerialize()
{
return $this->content;
}
}
class_alias('Twig\Markup', 'Twig_Markup');
|
Clean up repositories with symbols correctly
Summary: We currently try to delete symbols by ID, but the table has a multipart primary key and no `id` column.
Test Plan: Ran query locally; had @JThramer verify fix in his environment.
Reviewers: btrahan
Reviewed By: btrahan
CC: JThramer, aran
Differential Revision: https://secure.phabricator.com/D4626
|
<?php
final class PhabricatorRepositoryArcanistProject
extends PhabricatorRepositoryDAO {
protected $name;
protected $phid;
protected $repositoryID;
protected $symbolIndexLanguages = array();
protected $symbolIndexProjects = array();
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_SERIALIZATION => array(
'symbolIndexLanguages' => self::SERIALIZATION_JSON,
'symbolIndexProjects' => self::SERIALIZATION_JSON,
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID('APRJ');
}
public function loadRepository() {
if (!$this->getRepositoryID()) {
return null;
}
return id(new PhabricatorRepository())->load($this->getRepositoryID());
}
public function delete() {
$this->openTransaction();
queryfx(
$this->establishConnection('w'),
'DELETE FROM %T WHERE arcanistProjectID = %d',
id(new PhabricatorRepositorySymbol())->getTableName(),
$this->getID());
$result = parent::delete();
$this->saveTransaction();
return $result;
}
}
|
<?php
final class PhabricatorRepositoryArcanistProject
extends PhabricatorRepositoryDAO {
protected $name;
protected $phid;
protected $repositoryID;
protected $symbolIndexLanguages = array();
protected $symbolIndexProjects = array();
public function getConfiguration() {
return array(
self::CONFIG_AUX_PHID => true,
self::CONFIG_TIMESTAMPS => false,
self::CONFIG_SERIALIZATION => array(
'symbolIndexLanguages' => self::SERIALIZATION_JSON,
'symbolIndexProjects' => self::SERIALIZATION_JSON,
),
) + parent::getConfiguration();
}
public function generatePHID() {
return PhabricatorPHID::generateNewPHID('APRJ');
}
public function loadRepository() {
if (!$this->getRepositoryID()) {
return null;
}
return id(new PhabricatorRepository())->load($this->getRepositoryID());
}
public function delete() {
$this->openTransaction();
$conn_w = $this->establishConnection('w');
$symbols = id(new PhabricatorRepositorySymbol())->loadAllWhere(
'arcanistProjectID = %d',
$this->getID()
);
foreach ($symbols as $symbol) {
$symbol->delete();
}
$result = parent::delete();
$this->saveTransaction();
return $result;
}
}
|
Add axios request to breweryDB through our API endpoint
|
'use strict';
const axios = require('axios');
// const Post = require('./postModel')
const _API_KEY = require('../config/apiKeys.js').breweryDBKey;
const _API_BASEURL = 'http://api.brewerydb.com/v2/';
exports.get = (req, res, next) => {
// breweryDB endpoint
var endPoint = 'locations/';
// endpoint query options
var queryOptions = {
//locality: 'San Francisco'
locality: req.params.location,
p: '1'
};
// axios RESTful API call
axios.get(createUrl(endPoint, queryOptions))
.then(function (response) {
res.end(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
}
exports.post = (req, res, next) => {
// console.log('brewery post controller');
}
// Helper formatting function for connecting to breweryDB
var createUrl = function(endPoint, queryOptions) {
var key = '?key=' + _API_KEY;
var queryStrings = [];
// Create query string from all query options
for (let query in queryOptions) {
if (typeof queryOptions[query] === 'string') {
// encode spaces for url if query option is string
queryStrings.push(query + '=' + queryOptions[query].replace(' ', '+'));
} else {
queryStrings.push(query + '=' + queryOptions[query]);
}
}
return _API_BASEURL + endPoint + key + '&' + queryStrings.join('&');
}
|
'use strict';
const axios = require('axios');
// const Post = require('./postModel')
const _API_KEY = require('../config/apiKeys.js').breweryDBKey;
const _API_ENDPOINT = 'http://api.brewerydb.com/v2/';
exports.get = (req, res, next) => {
console.log('brewery get controller');
// Post.find({})
// .then((post) => {
// if (post) {
// res.json(post)
// } else {
// console.log('No posts in database')
// }
// })
}
exports.post = (req, res, next) => {
console.log('brewery post controller');
// let newPost = new Post({
// title: req.body.title,
// text: req.body.text,
// author: req.body.author
// })
//
// newPost.save()
// .then((post) => {
// if (post) {
// res.json(post)
// } else {
// console.log('Could not save post')
// }
// })
}
|
Support for listener in component constructor
|
/**
* A component
* @constructor
* @param {Object} options
* @param {Element} options.element
* @param {String} options.name
* @param {Object} options.listen A listener
*/
hui.ui.Component = function(options) {
this.name = options.name;
if (!this.name) {
hui.ui.latestObjectIndex++;
this.name = 'unnamed'+hui.ui.latestObjectIndex;
}
this.element = hui.get(options.element);
this.delegates = [];
if (this.nodes) {
this.nodes = hui.collect(this.nodes,this.element);
}
if (options.listen) {
this.listen(options.listen);
}
hui.ui.registerComponent(this);
}
hui.ui.Component.prototype = {
/**
* Add event listener
* @param {Object} listener An object with methods for different events
*/
listen : function(listener) {
this.delegates.push(listener);
},
fire : function(name,value,event) {
return hui.ui.callDelegates(this,name,value,event);
},
/**
* Get the components root element
* @returns Element
*/
getElement : function() {
return this.element;
},
destroy : function() {
if (this.element) {
hui.dom.remove(this.element);
}
}
}
|
/**
* A component
* @constructor
* @param {Object} options
* @param {Element} options.element
* @param {String} options.name
*/
hui.ui.Component = function(options) {
this.name = options.name;
if (!this.name) {
hui.ui.latestObjectIndex++;
this.name = 'unnamed'+hui.ui.latestObjectIndex;
}
this.element = hui.get(options.element);
this.listeners = [];
if (this.nodes) {
this.nodes = hui.collect(this.nodes,this.element);
}
hui.ui.registerComponent(this);
}
hui.ui.Component.prototype = {
/**
* Add event listener
* @param {Object} listener An object with methods for different events
*/
listen : function(listener) {
this.listeners.push(listener);
},
fire : function(name,value,event) {
return hui.ui.callDelegates(this,name,value,event);
},
/**
* Get the components root element
* @returns Element
*/
getElement : function() {
return this.element;
},
destroy : function() {
if (this.element) {
hui.dom.remove(this.element);
}
}
}
|
Make config file reader more defensive
|
<?php
namespace Whm\Opm\Client\Config;
use Symfony\Component\Yaml\Yaml;
class Config
{
private $config = array();
public function __construct(array $configArray)
{
$this->config = $configArray;
}
/**
* @param string $filename the yaml file name.
* @return \Whm\Opm\Client\Config\Config
*/
public static function createFromFile($filename)
{
$yamlString = file_get_contents($filename);
$yaml = new Yaml();
return new self($yaml->parse($yamlString));
}
public function getPhantomExecutable()
{
return $this->config['phantom']['executable'];
}
public function getOpmServer()
{
return $this->config['opm-server']['host'];
}
public function getClientId()
{
return $this->config['opm-client']['clientid'];
}
public function getMaxParallelRequests()
{
return $this->config['opm-client']['max-parallel-requests'];
}
}
|
<?php
namespace Whm\Opm\Client\Config;
use Symfony\Component\Yaml\Yaml;
class Config
{
private $config = array();
public function __construct (array $configArray)
{
$this->config = $configArray;
}
/**
* @param string $filename the yaml file name.
* @return \Whm\Opm\Client\Config\Config
*/
static public function createFromFile( $filename )
{
$yamlString = file_get_contents($filename);
$yaml = new Yaml();
return new self($yaml->parse($yamlString));
}
public function getPhantomExecutable ()
{
return $this->config['phantom']['executable'];
}
public function getOpmServer( )
{
return $this->config['opm-server']['host'];
}
public function getClientId( )
{
return $this->config['opm-client']['clientid'];
}
public function getMaxParallelRequests()
{
return $this->config['opm-client']['max-parallel-requests'];
}
}
|
Add in shim nullable FK for initial scriptparameter update
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
]
operations = [
migrations.CreateModel(
name='ScriptParser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=255, default='')),
('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')),
],
bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model),
),
migrations.AddField(
model_name='scriptparameter',
name='parser',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'),
preserve_default=False,
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2017-04-25 09:25
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import wooey.models.mixins
class Migration(migrations.Migration):
dependencies = [
('wooey', '0027_parameter_order'),
]
operations = [
migrations.CreateModel(
name='ScriptParser',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(blank=True, max_length=255, default='')),
('script_version', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptVersion')),
],
bases=(wooey.models.mixins.WooeyPy2Mixin, models.Model),
),
migrations.AddField(
model_name='scriptparameter',
name='parser',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='wooey.ScriptParser'),
preserve_default=False,
),
]
|
Read bin from command line arg
|
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Initializing Octave CPU...")
file, err := os.Open(os.Args[1])
if err != nil {
return
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return
}
bs := make([]byte, stat.Size())
_, err = file.Read(bs)
if err != nil {
return
}
for _, instruction := range bs {
decode(instruction)
}
}
func decode(instruction byte) {
switch instruction >> 5 {
case 1:
fmt.Println("MEM")
case 2:
fmt.Println("LOADI")
case 3:
fmt.Println("STACK")
case 4:
fmt.Println("JMP")
case 5:
fmt.Println("MATH")
case 6:
fmt.Println("LOGIC")
case 7:
fmt.Println("IN")
case 8:
fmt.Println("OUT")
}
}
|
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Initializing Octave CPU...")
file, err := os.Open("hello.bin")
if err != nil {
return
}
defer file.Close()
stat, err := file.Stat()
if err != nil {
return
}
bs := make([]byte, stat.Size())
_, err = file.Read(bs)
if err != nil {
return
}
for _, instruction := range bs {
decode(instruction)
}
}
func decode(instruction byte) {
switch instruction >> 5 {
case 1:
fmt.Println("MEM")
case 2:
fmt.Println("LOADI")
case 3:
fmt.Println("STACK")
case 4:
fmt.Println("JMP")
case 5:
fmt.Println("MATH")
case 6:
fmt.Println("LOGIC")
case 7:
fmt.Println("IN")
case 8:
fmt.Println("OUT")
}
}
|
feat: Add updated_at to Job schema
|
from marshmallow import Schema, fields
from .failurereason import FailureReasonSchema
from .fields import ResultField, StatusField
from .stats import StatsSchema
class JobSchema(Schema):
id = fields.UUID(dump_only=True)
number = fields.Integer(dump_only=True)
created_at = fields.DateTime(attribute='date_created', dump_only=True)
started_at = fields.DateTime(attribute='date_started', allow_none=True)
finished_at = fields.DateTime(attribute='date_finished', allow_none=True)
updated_at = fields.DateTime(attribute='date_updated', dump_only=True)
label = fields.Str()
status = StatusField()
result = ResultField()
stats = fields.Nested(StatsSchema(), dump_only=True)
# XXX(dcramer): these should be dump_only in normal cases, but not via hooks
provider = fields.Str()
external_id = fields.Str()
url = fields.Str(allow_none=True)
failures = fields.List(fields.Nested(FailureReasonSchema), dump_only=True)
allow_failure = fields.Bool(default=False)
|
from marshmallow import Schema, fields
from .failurereason import FailureReasonSchema
from .fields import ResultField, StatusField
from .stats import StatsSchema
class JobSchema(Schema):
id = fields.UUID(dump_only=True)
number = fields.Integer(dump_only=True)
created_at = fields.DateTime(attribute="date_created", dump_only=True)
started_at = fields.DateTime(attribute="date_started", allow_none=True)
finished_at = fields.DateTime(attribute="date_finished", allow_none=True)
label = fields.Str()
status = StatusField()
result = ResultField()
stats = fields.Nested(StatsSchema(), dump_only=True)
# XXX(dcramer): these should be dump_only in normal cases, but not via hooks
provider = fields.Str()
external_id = fields.Str()
url = fields.Str(allow_none=True)
failures = fields.List(fields.Nested(FailureReasonSchema), dump_only=True)
allow_failure = fields.Bool(default=False)
|
Make assigned-password migration script more robust
|
<?php
$skipped = false;
// skip if people table not generated yet
if (!static::tableExists('people')) {
print("Skipping migration because table `people` doesn't exist yet\n");
return static::STATUS_SKIPPED;
}
// skip if people table already has AssignedPassword column
if (static::columnExists('people', 'AssignedPassword')) {
print("Skipping migration because table `people` already has column `AssignedPassword`\n");
return static::STATUS_SKIPPED;
}
// skip if people table does not have a legacy PasswordClear column to rename
if (!static::columnExists('people', 'PasswordClear')) {
print("Skipping migration because table `people` does not have legacy column `PasswordClear`\n");
return static::STATUS_SKIPPED;
}
print("Upgrading people table\n");
DB::nonQuery('ALTER TABLE `people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');
print("Upgrading history_people table\n");
DB::nonQuery('ALTER TABLE `history_people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');
return static::STATUS_EXECUTED;
|
<?php
// skip if people table not generated yet
if (!DB::oneRecord('SELECT 1 FROM information_schema.TABLES WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = "people"')) {
print("Skipping migration because table doesn't exist yet\n");
return static::STATUS_SKIPPED;
}
// skip if people table already has AssignedPassword column
if (DB::oneRecord('SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = SCHEMA() AND TABLE_NAME = "people" AND COLUMN_NAME = "AssignedPassword"')) {
print("Skipping migration because table already has AssignedPassword column\n");
return static::STATUS_SKIPPED;
}
print("Upgrading people table\n");
DB::nonQuery('ALTER TABLE `people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');
print("Upgrading history_people table\n");
DB::nonQuery('ALTER TABLE `history_people` CHANGE `PasswordClear` `AssignedPassword` VARCHAR(255) NULL DEFAULT NULL');
return static::STATUS_EXECUTED;
|
Remove not needed comment line
|
from django.db import models
class Data_Ingredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
Ingredient = models.CharField(max_length=1000)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_length=500, default='Ingredientes')
def __str__(self):
return self.Ingredient
class Data_Way_Cooking(models.Model):
"""Class used to Store steps of the recipes found in the crawling process"""
Description = models.CharField(max_length=500)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_length=500, default='Modo de Fazer')
def __str__(self):
return self.Description
class Ingredient_Spec(models.Model):
"""Class used to manipulate Ingredients found and change data to data mining and found patterns of ingredients"""
Word = models.CharField(max_length=500)
Count = models.IntegerField()
Type = models.CharField(max_length=1)
class Ignore_Words(models.Model):
"""Model to store words to ignore from Ingredient Spec"""
Word = models.CharField(max_length=500)
|
from django.db import models
# Create your models here.
class Data_Ingredient(models.Model):
""""Class used to Store Ingredients of the recipes found in the crawling process"""
Ingredient = models.CharField(max_length=1000)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_length=500, default='Ingredientes')
def __str__(self):
return self.Ingredient
class Data_Way_Cooking(models.Model):
"""Class used to Store steps of the recipes found in the crawling process"""
Description = models.CharField(max_length=500)
Recipe = models.CharField(max_length=500)
Group = models.CharField(max_length=500, default='Modo de Fazer')
def __str__(self):
return self.Description
class Ingredient_Spec(models.Model):
"""Class used to manipulate Ingredients found and change data to data mining and found patterns of ingredients"""
Word = models.CharField(max_length=500)
Count = models.IntegerField()
Type = models.CharField(max_length=1)
class Ignore_Words(models.Model):
"""Model to store words to ignore from Ingredient Spec"""
Word = models.CharField(max_length=500)
|
Update Javadoc in class placeholder test
|
package org.tinylog.impl.format;
import org.junit.jupiter.api.Test;
import org.tinylog.impl.LogEntry;
import org.tinylog.impl.test.LogEntryBuilder;
import org.tinylog.impl.test.PlaceholderRenderer;
import static org.assertj.core.api.Assertions.assertThat;
class ClassPlaceholderTest {
/**
* Verifies that the source class name of a log entry will be output, if set.
*/
@Test
void renderWithClassName() {
PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create();
assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass");
}
/**
* Verifies that {@code <unknown>} will be output, if the class name is not set.
*/
@Test
void renderWithoutClassName() {
PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
LogEntry logEntry = new LogEntryBuilder().create();
assertThat(renderer.render(logEntry)).isEqualTo("<unknown>");
}
}
|
package org.tinylog.impl.format;
import org.junit.jupiter.api.Test;
import org.tinylog.impl.LogEntry;
import org.tinylog.impl.test.LogEntryBuilder;
import org.tinylog.impl.test.PlaceholderRenderer;
import static org.assertj.core.api.Assertions.assertThat;
class ClassPlaceholderTest {
/**
* Verifies that the source class name of a log entry will be output, if set.
*/
@Test
void renderWithClassName() {
PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
LogEntry logEntry = new LogEntryBuilder().className("foo.MyClass").create();
assertThat(renderer.render(logEntry)).isEqualTo("foo.MyClass");
}
/**
* Verifies that "<unknown>" will be output, if the class name is not set.
*/
@Test
void renderWithoutClassName() {
PlaceholderRenderer renderer = new PlaceholderRenderer(new ClassPlaceholder());
LogEntry logEntry = new LogEntryBuilder().create();
assertThat(renderer.render(logEntry)).isEqualTo("<unknown>");
}
}
|
Switch to proper context pacakge
|
package logouthandler
import (
"context"
"net/url"
"github.com/flimzy/jqeventrouter"
"github.com/flimzy/log"
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/jquery"
"github.com/FlashbackSRS/flashback/model"
)
var jQuery = jquery.NewJQuery
// BeforeTransition prepares the logout page before display.
func BeforeTransition(repo *model.Repo) jqeventrouter.HandlerFunc {
return func(_ *jquery.Event, _ *js.Object, _ url.Values) bool {
log.Debugf("logout BEFORE\n")
button := jQuery("#logout")
button.On("click", func() {
log.Debugf("Trying to log out now\n")
if err := repo.Logout(context.TODO()); err != nil {
log.Printf("Logout failure: %s\n", err)
}
jQuery(":mobile-pagecontainer").Call("pagecontainer", "change", "/")
})
return true
}
}
|
package logouthandler
import (
"net/url"
"golang.org/x/net/context"
"github.com/flimzy/jqeventrouter"
"github.com/flimzy/log"
"github.com/gopherjs/gopherjs/js"
"github.com/gopherjs/jquery"
"github.com/FlashbackSRS/flashback/model"
)
var jQuery = jquery.NewJQuery
// BeforeTransition prepares the logout page before display.
func BeforeTransition(repo *model.Repo) jqeventrouter.HandlerFunc {
return func(_ *jquery.Event, _ *js.Object, _ url.Values) bool {
log.Debugf("logout BEFORE\n")
button := jQuery("#logout")
button.On("click", func() {
log.Debugf("Trying to log out now\n")
if err := repo.Logout(context.TODO()); err != nil {
log.Printf("Logout failure: %s\n", err)
}
jQuery(":mobile-pagecontainer").Call("pagecontainer", "change", "/")
})
return true
}
}
|
Correct the timer element issue
|
const Timer = React.createClass({
getInitialState: function () {
return { secondsToWait: this.props.secondsToWait };
},
runTimer: function () {
this.setState({
timer: setInterval(() => {
if (this.state.secondsToWait === 0) clearInterval(timer);
this.setState({ secondsToWait: this.state.secondsToWait - 1 });
}, 1000)
});
},
stopTimer: function () {
clearInterval(this.state.timer);
},
componentDidMount: function () {
this.runTimer();
},
componentWillUnmount: function () {
this.stopTimer();
},
render: function () {
if (this.state.secondsToWait > 0) {
let unit = (this.state.secondsToWait > 1)? 'seconds': 'second';
return <p><i className="fa fa-spinner"></i> Waiting {this.state.secondsToWait} {unit}...</p>;
}
return <p>Done!</p>;
}
});
|
const Timer = React.createClass({
getInitialState: function () {
return { secondsToWait: this.props.secondsToWait };
},
runTimer: function () {
let timer = setInterval(() => {
if (this.state.secondsToWait === 0) clearInterval(timer);
this.setState({ secondsToWait: this.state.secondsToWait - 1 });
}, 1000);
},
componentDidMount: function () {
this.runTimer();
},
render: function () {
if (this.state.secondsToWait > 0) {
let unit = (this.state.secondsToWait > 1)? 'seconds': 'second';
return <p><i className="fa fa-spinner"></i> Waiting {this.state.secondsToWait} {unit}...</p>;
}
return <p>Done!</p>;
}
});
|
Change keyboard shortcut defaults to shift+
|
export const TOOLTIP_DEFAULT_OPTION = true
export const POSITION_DEFAULT_OPTION = 'mouse'
export const HIGHLIGHTS_DEFAULT_OPTION = true
export const HIGHLIGHTS_STORAGE_NAME = 'memex_link_highlights'
export const TOOLTIP_STORAGE_NAME = 'memex_link_tooltip'
export const POSITION_STORAGE_NAME = 'memex_link_position'
export const INFO_URL =
'https://worldbrain.helprace.com/i62-feature-memex-links-highlight-any-text-and-create-a-link-to-it'
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts'
export const KEYBOARDSHORTCUTS_DEFAULT_STATE = {
shortcutsEnabled: false,
linkShortcut: 'alt+l',
toggleSidebarShortcut: 'alt+r',
toggleHighlightsShortcut: 'alt+h',
createAnnotationShortcut: 'alt+a',
createHighlightShortcut: 'alt+n',
createBookmarkShortcut: 'alt+b',
addTagShortcut: 'alt+t',
addToCollectionShortcut: 'alt+u',
addCommentShortcut: 'alt+c',
linkShortcutEnabled: true,
toggleSidebarShortcutEnabled: true,
toggleHighlightsShortcutEnabled: true,
createAnnotationShortcutEnabled: true,
createBookmarkShortcutEnabled: true,
createHighlightShortcutEnabled: true,
addTagShortcutEnabled: true,
addToCollectionShortcutEnabled: true,
addCommentShortcutEnabled: true,
}
|
export const TOOLTIP_DEFAULT_OPTION = true
export const POSITION_DEFAULT_OPTION = 'mouse'
export const HIGHLIGHTS_DEFAULT_OPTION = true
export const HIGHLIGHTS_STORAGE_NAME = 'memex_link_highlights'
export const TOOLTIP_STORAGE_NAME = 'memex_link_tooltip'
export const POSITION_STORAGE_NAME = 'memex_link_position'
export const INFO_URL =
'https://worldbrain.helprace.com/i62-feature-memex-links-highlight-any-text-and-create-a-link-to-it'
export const KEYBOARDSHORTCUTS_STORAGE_NAME = 'memex-keyboardshortcuts'
export const KEYBOARDSHORTCUTS_DEFAULT_STATE = {
shortcutsEnabled: false,
linkShortcut: 'shift+l',
toggleSidebarShortcut: 'shift+r',
toggleHighlightsShortcut: 'shift+h',
createAnnotationShortcut: 'shift+a',
createHighlightShortcut: 'shift+n',
createBookmarkShortcut: 'shift+b',
addTagShortcut: 'shift+t',
addToCollectionShortcut: 'shift+u',
addCommentShortcut: 'shift+c',
linkShortcutEnabled: true,
toggleSidebarShortcutEnabled: true,
toggleHighlightsShortcutEnabled: true,
createAnnotationShortcutEnabled: true,
createBookmarkShortcutEnabled: true,
createHighlightShortcutEnabled: true,
addTagShortcutEnabled: true,
addToCollectionShortcutEnabled: true,
addCommentShortcutEnabled: true,
}
|
Fix for overseas first - to skip the issued question
|
module.exports = {
'/':{
fields: ['age-day', 'age-year', 'age-month'],
backLink: '../filter-common/what-do-you-want-to-do-overseas',
next: '/country-born'
},
'/issued':{
fields: ['issuing-authority', 'expiry-year', 'expiry-month'],
backLink: './',
next: '/country-born'
},
'/country-born': {
controller: require('../../../controllers/application-country'),
controller: require('../../../controllers/go-overseas'),
fields: ['application-country'],
backLink: './',
next: 'france-first',
nextAlt: 'france-first',
nextAltAltAlt: 'spain-first' /* if they are from Spain - first hidden as renewal */
},
'/france-first': {
backLink: './country-born',
},
'/spain-first': {
backLink: './country-born',
}
};
|
module.exports = {
'/':{
fields: ['age-day', 'age-year', 'age-month'],
backLink: '../filter-common/what-do-you-want-to-do-overseas',
next: '/issued'
},
'/issued':{
fields: ['issuing-authority', 'expiry-year', 'expiry-month'],
backLink: './',
next: '/country-born'
},
'/country-born': {
controller: require('../../../controllers/application-country'),
controller: require('../../../controllers/go-overseas'),
fields: ['application-country'],
backLink: './issued',
next: 'france-first',
nextAlt: 'france-first',
nextAltAltAlt: 'spain-first' /* if they are from Spain - first hidden as renewal */
},
'/france-first': {
backLink: './country-born',
},
'/spain-first': {
backLink: './country-born',
}
};
|
Add updating of jobs if their state is now unknown
|
from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
jobids = []
for job in cluster["jobs"]:
status = job[-1]
job_id = job[0]
jobids.append(job_id)
if status in jobs:
jobs[status].append(job_id)
else:
jobs[status] = [job_id]
running = Job.get_running_jobs(credential=cred)
unknown = running.exclude(jobid__in=set(jobids)).values_list('jobid', flat=True)
if unknown:
jobs[Job.UNKNOWN] = list(unknown)
Job.update_states(cred, jobs)
if __name__ == "__main__":
run_all()
|
from django.contrib.auth.models import User
from models import Job
from interface import get_all_jobs
def run_all():
for user in User.objects.all():
creds = user.credentials.all()
for i, cluster in enumerate(get_all_jobs(user)):
cred = creds[i]
jobs = {}
for job in cluster["jobs"]:
status = job[-1]
job_id = job[0]
if status in jobs:
jobs[status].append(job_id)
else:
jobs[status] = [job_id]
Job.update_states(cred, jobs)
if __name__ == "__main__":
run_all()
|
Add the webpack NoErrors plugin
This plugin keeps webpack from emitting its build products if there are
any errors. That way, the hot-reloading in the browser won’t get
broken and require a page refresh.
|
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: [path.resolve(__dirname, '../client/index.js')],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel']
}, {
test: /\.css/,
loader: ExtractTextPlugin.extract('css')
}, {
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}
],
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}]
},
output: {
path: path.resolve(__dirname, '../public'),
filename: 'client.js'
},
plugins: [
new ExtractTextPlugin('style.css', {
allChunks: true
}),
new webpack.NoErrorsPlugin(),
new webpack.ProvidePlugin({
fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
],
resolve: {
root: path.resolve(__dirname, '../client'),
extensions: ['', '.js']
}
}
|
const path = require('path')
const webpack = require('webpack')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
module.exports = {
entry: [path.resolve(__dirname, '../client/index.js')],
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel']
}, {
test: /\.css/,
loader: ExtractTextPlugin.extract('css')
}, {
test: /\.(eot|woff|woff2|ttf|svg|png|jpg)$/,
loader: 'url-loader?limit=30000&name=[name]-[hash].[ext]'
}
],
preLoaders: [{
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}]
},
output: {
path: path.resolve(__dirname, '../public'),
filename: 'client.js'
},
plugins: [
new ExtractTextPlugin('style.css', {
allChunks: true
}),
new webpack.ProvidePlugin({
fetch: 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
],
resolve: {
root: path.resolve(__dirname, '../client'),
extensions: ['', '.js']
}
}
|
Adjust the other pains on sidebar toggle
|
/* global document */
import { Map } from 'immutable';
import { handleActions } from 'redux-actions';
import { SIDEBAR_TOGGLE, PANE_TOGGLE, PANE_RESIZE, SIDEBAR_RESIZE } from '../actions/ui';
import { FOLDER_OPEN } from '../actions/files';
const initialState = Map({
sidebarVisible: false,
paneVisible: true,
paneSize: (document.documentElement.clientWidth / 2),
sidebarSize: 250
});
const uiReducer = handleActions({
[SIDEBAR_TOGGLE]: (state) => {
const sidebarVisible = !state.get('sidebarVisible');
const sidebarSize = state.get('sidebarSize');
let paneSize = state.get('paneSize');
if (sidebarVisible) {
paneSize -= (sidebarSize / 2);
} else {
paneSize += (sidebarSize / 2);
}
return state.merge({ sidebarVisible, paneSize });
},
[FOLDER_OPEN]: state => (state.set('sidebarVisible', true)),
[PANE_TOGGLE]: state => (state.set('paneVisible', !state.get('paneVisible'))),
[PANE_RESIZE]: (state, { payload }) => (state.set('paneSize', payload)),
[SIDEBAR_RESIZE]: (state, { payload }) => (state.set('sidebarSize', payload))
}, initialState);
export default uiReducer;
|
/* global document */
import { Map } from 'immutable';
import { handleActions } from 'redux-actions';
import { SIDEBAR_TOGGLE, PANE_TOGGLE, PANE_RESIZE, SIDEBAR_RESIZE } from '../actions/ui';
import { FOLDER_OPEN } from '../actions/files';
const initialState = Map({
sidebarVisible: false,
paneVisible: true,
paneSize: ((document.documentElement.clientWidth - 250) / 2),
sidebarSize: 250
});
const uiReducer = handleActions({
[SIDEBAR_TOGGLE]: state => (state.set('sidebarVisible', !state.get('sidebarVisible'))),
[FOLDER_OPEN]: state => (state.set('sidebarVisible', true)),
[PANE_TOGGLE]: state => (state.set('paneVisible', !state.get('paneVisible'))),
[PANE_RESIZE]: (state, { payload }) => (state.set('paneSize', payload)),
[SIDEBAR_RESIZE]: (state, { payload }) => (state.set('sidebarSize', payload))
}, initialState);
export default uiReducer;
|
Add default govuk link and logo title
|
module.exports = {
htmlLang: '{{htmlLang}}',
assetPath: '{{govukAssetPath}}',
afterHeader: '{{$afterHeader}}{{/afterHeader}}',
bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}',
bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}',
content: '{{$main}}{{/main}}',
cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}',
footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}',
footerTop: '{{$footerTop}}{{/footerTop}}',
head: '{{$head}}{{/head}}',
headerClass: '{{$headerClass}}{{/headerClass}}',
homepageUrl: '{{$homepageUrl}}https://www.gov.uk{{/homepageUrl}}',
logoLinkTitle: '{{$logoLinkTitle}}Go to the GOV.UK homepage{{/logoLinkTitle}}',
insideHeader: '{{$insideHeader}}{{/insideHeader}}',
pageTitle: '{{$pageTitle}}{{/pageTitle}}',
propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}',
skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}',
globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}',
licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}',
crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}'
};
|
module.exports = {
htmlLang: '{{htmlLang}}',
assetPath: '{{govukAssetPath}}',
afterHeader: '{{$afterHeader}}{{/afterHeader}}',
bodyClasses: '{{$bodyClasses}}{{/bodyClasses}}',
bodyEnd: '{{$bodyEnd}}{{/bodyEnd}}',
content: '{{$main}}{{/main}}',
cookieMessage: '{{$cookieMessage}}{{/cookieMessage}}',
footerSupportLinks: '{{$footerSupportLinks}}{{/footerSupportLinks}}',
footerTop: '{{$footerTop}}{{/footerTop}}',
head: '{{$head}}{{/head}}',
headerClass: '{{$headerClass}}{{/headerClass}}',
insideHeader: '{{$insideHeader}}{{/insideHeader}}',
pageTitle: '{{$pageTitle}}{{/pageTitle}}',
propositionHeader: '{{$propositionHeader}}{{/propositionHeader}}',
skipLinkMessage: '{{$skipLinkMessage}}Skip to main content{{/skipLinkMessage}}',
globalHeaderText: '{{$globalHeaderText}}GOV.UK{{/globalHeaderText}}',
licenceMessage: '{{$licenceMessage}}<p>All content is available under the <a href="https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/" rel="license">Open Government Licence v3.0</a>, except where otherwise stated</p>{{/licenceMessage}}',
crownCopyrightMessage: '{{$crownCopyrightMessage}}© Crown copyright{{/crownCopyrightMessage}}'
};
|
Remove deprecated applications adapter code
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .. import backend
from .. import layers
from .. import models
from .. import utils
import keras_applications
if not hasattr(keras_applications, 'get_submodules_from_kwargs'):
keras_applications.set_keras_submodules(
backend=backend,
layers=layers,
models=models,
utils=utils)
def keras_modules_injection(base_fun):
def wrapper(*args, **kwargs):
if hasattr(keras_applications, 'get_submodules_from_kwargs'):
kwargs['backend'] = backend
kwargs['layers'] = layers
kwargs['models'] = models
kwargs['utils'] = utils
return base_fun(*args, **kwargs)
return wrapper
from .vgg16 import VGG16
from .vgg19 import VGG19
from .resnet50 import ResNet50
from .inception_v3 import InceptionV3
from .inception_resnet_v2 import InceptionResNetV2
from .xception import Xception
from .mobilenet import MobileNet
from .mobilenet_v2 import MobileNetV2
from .densenet import DenseNet121, DenseNet169, DenseNet201
from .nasnet import NASNetMobile, NASNetLarge
from .resnet import ResNet101, ResNet152
from .resnet_v2 import ResNet50V2, ResNet101V2, ResNet152V2
from .resnext import ResNeXt50, ResNeXt101
|
Fix class name of Facebook command
|
<?php
namespace Laravel\Passport\Console;
use DateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\ClientRepository;
class FacebookCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'passport:facebook {client_id : ID of the client}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Grant a client access to the Facebook grant';
/**
* Execute the console command.
*
* @param \Laravel\Passport\ClientRepository $clients
* @return void
*/
public function handle(ClientRepository $clients)
{
$client = Client::find($this->argument("client_id"));
if (!$client) {
throw new Exception("Could not find client with ID " . $this->argument("client_id"));
}
$client->facebook_client = true;
$client->save();
$this->info("Client " . $this->argument("client_id") . " has been granted access to the Facebook grant.");
}
}
|
<?php
namespace Laravel\Passport\Console;
use DateTime;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Laravel\Passport\ClientRepository;
class ClientCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'passport:facebook {client_id : ID of the client}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Grant a client access to the Facebook grant';
/**
* Execute the console command.
*
* @param \Laravel\Passport\ClientRepository $clients
* @return void
*/
public function handle(ClientRepository $clients)
{
$client = Client::find($this->argument("client_id"));
if (!$client) {
throw new Exception("Could not find client with ID " . $this->argument("client_id"));
}
$client->facebook_client = true;
$client->save();
$this->info("Client " . $this->argument("client_id") . " has been granted access to the Facebook grant.");
}
}
|
Fix RegExp to `$` for all targets rather than node
|
'use strict';
var commander = require('commander');
var path = require('path');
var Queue = require('gear').Queue;
var registry = require('./tasks');
var build, target;
commander
.usage('[options] [<languages ...>]')
.option('-n, --no-compress', 'Disable compression')
.option('-t, --target <name>', 'Build for target [browser, cdn, node]',
/^(browser|cdn|node)$/i, 'browser')
.parse(process.argv);
target = './' + commander.target.toLowerCase();
build = require(target);
global.dir = {};
global.dir.root = path.dirname(__dirname);
global.dir.build = path.join(dir.root, 'build');
new Queue({ registry: registry })
.clean(dir.build)
.log('Starting build.')
.tasks(build(commander))
.log('Finished build.')
.run();
|
'use strict';
var commander = require('commander');
var path = require('path');
var Queue = require('gear').Queue;
var registry = require('./tasks');
var build, target;
commander
.usage('[options] [<languages ...>]')
.option('-n, --no-compress', 'Disable compression')
.option('-t, --target <name>', 'Build for target [browser, cdn, node]',
/^(browser|cdn|node$)/i, 'browser')
.parse(process.argv);
target = './' + commander.target.toLowerCase();
build = require(target);
global.dir = {};
global.dir.root = path.dirname(__dirname);
global.dir.build = path.join(dir.root, 'build');
new Queue({ registry: registry })
.clean(dir.build)
.log('Starting build.')
.tasks(build(commander))
.log('Finished build.')
.run();
|
Use argparse instead of manually parsing [skip ci]
|
#!/usr/bin/env python3
# #############################################################################
# Copyright (c) 2018-present lzutao <taolzu(at)gmail.com>
# All rights reserved.
#
# This source code is licensed under both the BSD-style license (found in the
# LICENSE file in the root directory of this source tree) and the GPLv2 (found
# in the COPYING file in the root directory of this source tree).
# #############################################################################
import re
import sys
def find_version(filepath):
version_file_data = None
with open(filepath) as fd:
version_file_data = fd.read()
patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$
#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$
#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$
"""
regex = re.compile(patterns, re.MULTILINE)
version_match = regex.search(version_file_data)
if version_match:
return version_match.groups()
raise Exception("Unable to find version string.")
def main():
import argparse
parser = argparse.ArgumentParser(description='Print lz4 version from lib/lz4.h')
parser.add_argument('file', help='path to lib/lz4.h')
args = parser.parse_args()
filepath = args.file
version_tup = find_version(filepath)
print('.'.join(version_tup))
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
# #############################################################################
# Copyright (c) 2018-present lzutao <taolzu(at)gmail.com>
# All rights reserved.
#
# This source code is licensed under both the BSD-style license (found in the
# LICENSE file in the root directory of this source tree) and the GPLv2 (found
# in the COPYING file in the root directory of this source tree).
# #############################################################################
import re
import sys
def usage():
print('usage: python3 GetLz4LibraryVersion.py <path/to/lz4.h>')
sys.exit(1)
def find_version(filepath):
version_file_data = None
with open(filepath) as fd:
version_file_data = fd.read()
patterns = r"""#\s*define\s+LZ4_VERSION_MAJOR\s+([0-9]+).*$
#\s*define\s+LZ4_VERSION_MINOR\s+([0-9]+).*$
#\s*define\s+LZ4_VERSION_RELEASE\s+([0-9]+).*$
"""
regex = re.compile(patterns, re.MULTILINE)
version_match = regex.search(version_file_data)
if version_match:
return version_match.groups()
raise Exception("Unable to find version string.")
def main():
if len(sys.argv) < 2:
usage()
filepath = sys.argv[1]
version_tup = find_version(filepath)
print('.'.join(version_tup))
if __name__ == '__main__':
main()
|
Use own model class on github task
|
import datetime
from goodtablesio.models.user import User
from goodtablesio.services import database
from goodtablesio.celery_app import celery_app
from goodtablesio.integrations.github.models.repo import GithubRepo
from goodtablesio.integrations.github.utils.repos import iter_repos_by_token
@celery_app.task(name='goodtablesio.github.sync_user_repos')
def sync_user_repos(user_id, token):
"""Sync user repositories.
"""
user = database['session'].query(User).get(user_id)
for repo_data in iter_repos_by_token(token):
repo = database['session'].query(GithubRepo).filter(
GithubRepo.conf['github_id'].astext == repo_data['conf']['github_id']
).one_or_none()
if repo is None:
repo = GithubRepo(**repo_data)
database['session'].add(repo)
repo.active = repo_data['active']
repo.updated = datetime.datetime.utcnow(),
repo.users.append(user)
database['session'].commit()
|
import datetime
from goodtablesio.models.user import User
from goodtablesio.models.source import Source
from goodtablesio.services import database
from goodtablesio.celery_app import celery_app
from goodtablesio.integrations.github.utils.repos import iter_repos_by_token
@celery_app.task(name='goodtablesio.github.sync_user_repos')
def sync_user_repos(user_id, token):
"""Sync user repositories.
"""
user = database['session'].query(User).get(user_id)
for repo_data in iter_repos_by_token(token):
repo = database['session'].query(Source).filter(
Source.conf['github_id'].astext == repo_data['conf']['github_id']
).one_or_none()
if repo is None:
repo = Source(**repo_data)
database['session'].add(repo)
repo.active = repo_data['active']
repo.updated = datetime.datetime.utcnow(),
repo.users.append(user)
database['session'].commit()
|
Make fire take coordinates, add function for aiming
|
(function() {
'use strict';
function Weapon(game, x, y, coolDown, bulletSpeed, bullets, damage) {
this.game = game;
this.x = x;
this.y = y;
this.coolDown = coolDown;
this.nextFire = 0;
this.bullets = bullets;
this.bulletSpeed = bulletSpeed;
this.damage = damage;
}
Weapon.prototype = {
updateManually: function(x, y){
this.x = x;
this.y = y;
},
fire: function(x, y){
if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0){
this.nextFire = this.game.time.now + this.coolDown;
var bullet = this.bullets.getFirstDead();
bullet.reset(this.x, this.y);
bullet.rotation = this.takeAim(x, y);
}
},
takeAim: function(x, y) {
var perfAngle = this.game.physics.angleToXY(this.game.player, x, y);
// TODO: Make targeting depend on users intelligence.
return perfAngle;
}
};
window.Darwinator = window.Darwinator || {};
window.Darwinator.Weapon = Weapon;
}());
|
(function() {
'use strict';
function Weapon(game, x, y, coolDown, bulletSpeed, bullets, damage) {
this.game = game;
this.x = x;
this.y = y;
this.coolDown = coolDown;
this.nextFire = 0;
this.bullets = bullets;
this.bulletSpeed = bulletSpeed;
this.damage = damage;
}
Weapon.prototype = {
updateManually: function(x, y){
this.x = x;
this.y = y;
this.game.physics.angleToPointer(this);
if (this.game.input.activePointer.isDown){
this.fire();
}
},
fire: function(){
if (this.game.time.now > this.nextFire && this.bullets.countDead() > 0){
this.nextFire = this.game.time.now + this.coolDown;
var bullet = this.bullets.getFirstDead();
this.resetBullet(bullet);
}
},
resetBullet: function(bullet){
bullet.reset(this.x, this.y); // resets sprite and body
bullet.rotation = this.game.physics.moveToPointer(bullet, this.bulletSpeed);
}
};
window.Darwinator = window.Darwinator || {};
window.Darwinator.Weapon = Weapon;
}());
|
[DI] Make tagged abstract services throw earlier
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\DependencyInjection;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds tagged routing.loader services to routing.resolver service.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoutingResolverPass implements CompilerPassInterface
{
private $resolverServiceId;
private $loaderTag;
public function __construct($resolverServiceId = 'routing.resolver', $loaderTag = 'routing.loader')
{
$this->resolverServiceId = $resolverServiceId;
$this->loaderTag = $loaderTag;
}
public function process(ContainerBuilder $container)
{
if (false === $container->hasDefinition($this->resolverServiceId)) {
return;
}
$definition = $container->getDefinition($this->resolverServiceId);
foreach ($container->findTaggedServiceIds($this->loaderTag, true) as $id => $attributes) {
$definition->addMethodCall('addLoader', array(new Reference($id)));
}
}
}
|
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Routing\DependencyInjection;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
/**
* Adds tagged routing.loader services to routing.resolver service.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RoutingResolverPass implements CompilerPassInterface
{
private $resolverServiceId;
private $loaderTag;
public function __construct($resolverServiceId = 'routing.resolver', $loaderTag = 'routing.loader')
{
$this->resolverServiceId = $resolverServiceId;
$this->loaderTag = $loaderTag;
}
public function process(ContainerBuilder $container)
{
if (false === $container->hasDefinition($this->resolverServiceId)) {
return;
}
$definition = $container->getDefinition($this->resolverServiceId);
foreach ($container->findTaggedServiceIds($this->loaderTag) as $id => $attributes) {
$definition->addMethodCall('addLoader', array(new Reference($id)));
}
}
}
|
Allow "O42" to find packages by monogram in Owners typeaheads
Summary: When a user queries by package monogram explicitly, search by package ID.
Test Plan: {F2305075}
Reviewers: chad
Reviewed By: chad
Differential Revision: https://secure.phabricator.com/D17142
|
<?php
final class PhabricatorOwnersPackageDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Packages');
}
public function getPlaceholderText() {
return pht('Type a package name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorOwnersApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
$query = id(new PhabricatorOwnersPackageQuery())
->setOrder('name');
// If the user is querying by monogram explicitly, like "O123", do an ID
// search. Otherwise, do an ngram substring search.
if (preg_match('/^[oO]\d+\z/', $raw_query)) {
$id = trim($raw_query, 'oO');
$id = (int)$id;
$query->withIDs(array($id));
} else {
$query->withNameNgrams($raw_query);
}
$packages = $this->executeQuery($query);
foreach ($packages as $package) {
$name = $package->getName();
$monogram = $package->getMonogram();
$results[] = id(new PhabricatorTypeaheadResult())
->setName("{$monogram}: {$name}")
->setURI($package->getURI())
->setPHID($package->getPHID());
}
return $this->filterResultsAgainstTokens($results);
}
}
|
<?php
final class PhabricatorOwnersPackageDatasource
extends PhabricatorTypeaheadDatasource {
public function getBrowseTitle() {
return pht('Browse Packages');
}
public function getPlaceholderText() {
return pht('Type a package name...');
}
public function getDatasourceApplicationClass() {
return 'PhabricatorOwnersApplication';
}
public function loadResults() {
$viewer = $this->getViewer();
$raw_query = $this->getRawQuery();
$results = array();
$query = id(new PhabricatorOwnersPackageQuery())
->withNameNgrams($raw_query)
->setOrder('name');
$packages = $this->executeQuery($query);
foreach ($packages as $package) {
$name = $package->getName();
$monogram = $package->getMonogram();
$results[] = id(new PhabricatorTypeaheadResult())
->setName("{$monogram}: {$name}")
->setURI($package->getURI())
->setPHID($package->getPHID());
}
return $this->filterResultsAgainstTokens($results);
}
}
|
Read input from variable, not from buffer again
|
package main
import (
"bytes"
"flag"
"fmt"
"github.com/cadena-monde/slackbot"
"os"
"strings"
)
var (
channel, message string
stdin bool
slackURL = os.Getenv("SLACKBOT_URL")
token = os.Getenv("SLACKBOT_TOKEN")
)
func main() {
parseFlags()
if stdin {
readFromStdin()
}
postMessage()
}
func readFromStdin() {
input := bytes.NewBuffer([]byte{})
input.ReadFrom(os.Stdin)
inputString := input.String()
if inputString != "" {
message = fmt.Sprintf("%s\n```%s```", message, inputString)
message = strings.Replace(message, "\r", "", -1)
}
}
func parseFlags() {
flag.StringVar(&channel, "channel", "", "Channel. Ex: #random")
flag.StringVar(&message, "message", "", "Message to be sent to the channel")
flag.BoolVar(&stdin, "stdin", false, "Read message from stdin")
flag.Parse()
if channel == "" || (message == "" && !stdin) {
flag.Usage()
os.Exit(1)
}
}
func postMessage() {
b := slackbot.New(slackURL, token)
b.PostMessage(channel, message)
}
|
package main
import (
"bytes"
"flag"
"fmt"
"github.com/cadena-monde/slackbot"
"os"
"strings"
)
var (
channel, message string
stdin bool
slackURL = os.Getenv("SLACKBOT_URL")
token = os.Getenv("SLACKBOT_TOKEN")
)
func main() {
parseFlags()
if stdin {
readFromStdin()
}
postMessage()
}
func readFromStdin() {
input := bytes.NewBuffer([]byte{})
input.ReadFrom(os.Stdin)
inputString := input.String()
if inputString != "" {
message = fmt.Sprintf("%s\n```%s```", message, input.String())
message = strings.Replace(message, "\r", "", -1)
}
}
func parseFlags() {
flag.StringVar(&channel, "channel", "", "Channel. Ex: #random")
flag.StringVar(&message, "message", "", "Message to be sent to the channel")
flag.BoolVar(&stdin, "stdin", false, "Read message from stdin")
flag.Parse()
if channel == "" || (message == "" && !stdin) {
flag.Usage()
os.Exit(1)
}
}
func postMessage() {
b := slackbot.New(slackURL, token)
b.PostMessage(channel, message)
}
|
Add some missing translation phases
|
<?php
/**
* Created by PhpStorm.
* User: antiprovn
* Date: 12/31/14
* Time: 2:00 AM
*/
namespace Application\Helper;
class Common {
public function __construct()
{
setlocale(LC_ALL, 'en_US.UTF8');
}
/**
* Return name with Uppercase the first character of each word in a string
*
* @param string $route
* @return string
*/
public static function getNameFromRoute($route)
{
$route = str_replace('-', ' ', $route);
$route = str_replace('/', '', $route);
$route = str_replace(' s ', '\'s ', $route);
$route = ucwords($route);
$route = str_replace(' Of ', ' of ', $route);
return $route;
}
}
|
<?php
/**
* Created by PhpStorm.
* User: antiprovn
* Date: 12/31/14
* Time: 2:00 AM
*/
namespace Application\Helper;
class Common {
public function __construct()
{
setlocale(LC_ALL, 'en_US.UTF8');
}
/**
* Return name with Uppercase the first character of each word in a string
*
* @param string $route
* @return string
*/
public static function getNameFromRoute($route)
{
$route = str_replace('-', ' ', $route);
$route = str_replace('/', '', $route);
$route = str_replace(' s ', '\'s ', $route);
ucwords($route);
$route = str_replace(' Of ', ' of ', $route);
return $route;
}
}
|
Make Mako requirement only for tests
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
requires = [
'pyramid',
'WebHelpers',
'FormEncode',
]
tests_require = requires + [
'pyramid_mako',
]
setup(name='pyramid_simpleform',
version='0.7',
description='pyramid_simpleform',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Chris Lambacher',
author_email='chris@kateandchris.net',
url='https://github.com/Pylons/pyramid_simpleform',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
license="LICENSE.txt",
install_requires=requires,
tests_require=tests_require,
test_suite="pyramid_simpleform",
)
|
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
requires = [
'pyramid',
'pyramid_mako',
'WebHelpers',
'FormEncode',
]
setup(name='pyramid_simpleform',
version='0.7',
description='pyramid_simpleform',
long_description=README + '\n\n' + CHANGES,
classifiers=[
"Programming Language :: Python",
"Framework :: Pylons",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application",
],
author='Chris Lambacher',
author_email='chris@kateandchris.net',
url='https://github.com/Pylons/pyramid_simpleform',
keywords='web pyramid pylons',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
license="LICENSE.txt",
install_requires=requires,
tests_require=requires,
test_suite="pyramid_simpleform",
)
|
Test form submission in NewHoushold
|
import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from '../../../redux/store';
import NewHousehold from '../index';
afterEach(cleanup);
describe('<NewHousehold /> component', () => {
it('matches the snapshop', () => {
const { container } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(container.firstChild).toMatchSnapshot();
});
it('renders correctly', () => {
const { getByTestId } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(getByTestId('page-header').textContent).toBe('Create A New Family');
});
it('renders the new household form', () => {
const { getByTestId } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(getByTestId('household-form')).toBeTruthy();
});
it('submits the form correctly', () => {
const { getByText } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
fireEvent.click(getByText('Create Lead'));
});
});
|
import React from 'react';
import { render, cleanup, fireEvent } from '@testing-library/react';
import { Provider } from 'react-redux';
import store from '../../../redux/store';
import NewHousehold from '../index';
afterEach(cleanup);
describe('<NewHousehold /> component', () => {
it('matches the snapshop', () => {
const { container } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(container.firstChild).toMatchSnapshot();
});
it('renders correctly', () => {
const { getByTestId } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(getByTestId('page-header').textContent).toBe('Create A New Family');
});
it('renders the new household form', () => {
const { getByTestId } = render(
<Provider store={store}>
<NewHousehold />
</Provider>
);
expect(getByTestId('household-form')).toBeTruthy();
});
});
|
Make portal_config fetch config from a URL
|
#!/usr/bin/env python
import rospy
import urllib2
from portal_config.srv import *
# XXX TODO: return an error if the config file isn't valid JSON
class ConfigRequestHandler():
def __init__(self, url):
self.url = url
def get_config(self):
response = urllib2.urlopen(self.url)
return response.read()
def handle_request(self, request):
config = self.get_config()
return PortalConfigResponse(config)
def main():
rospy.init_node('portal_config')
url = rospy.get_param('~url', 'http://lg-head/portal/config.json')
handler = ConfigRequestHandler(url)
s = rospy.Service(
'/portal_config/query',
PortalConfig,
handler.handle_request
)
rospy.spin()
if __name__ == '__main__':
main()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 smartindent
|
#!/usr/bin/env python
import rospy
from portal_config.srv import *
class ConfigRequestHandler():
def __init__(self, url):
self.url = url
def get_config(self):
return '{"foo": "bar"}'
def handle_request(self, request):
config = self.get_config()
return PortalConfigResponse(config)
def main():
rospy.init_node('portal_config')
url = rospy.get_param('~url', 'http://lg-head/portal/config.json')
handler = ConfigRequestHandler(url)
s = rospy.Service(
'/portal_config/query',
PortalConfig,
handler.handle_request
)
rospy.spin()
if __name__ == '__main__':
main()
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
Declare the media argument in the previous track feature.
|
(function( window, $, cue, undefined ) {
'use strict';
$.extend( MediaElementPlayer.prototype, {
buildcueprevioustrack: function( player, controls, layers, media ) {
$( '<div class="mejs-button mejs-previous-button mejs-previous">' +
'<button type="button" aria-controls="' + player.id + '" title="' + cue.l10n.previousTrack + '"></button>' +
'</div>' )
.appendTo( controls )
.on( 'click.cue', function() {
var state,
track = player.cueGetCurrentTrack() || {};
state = $.extend({}, {
currentTime: media.currentTime,
duration: media.duration,
src: media.src
});
player.$node.trigger( 'skipBack.cue', [ state, track ] );
player.cuePlayPreviousTrack();
});
},
// @todo Go to previous playable track.
cuePlayPreviousTrack: function() {
var player = this,
index = player.cueCurrentTrack - 1 < 0 ? player.options.cuePlaylistTracks.length - 1 : player.cueCurrentTrack - 1;
player.$node.trigger( 'previousTrack.cue', player );
player.cueSetCurrentTrack( index );
}
});
})( this, jQuery, window.cue );
|
(function( window, $, cue, undefined ) {
'use strict';
$.extend( MediaElementPlayer.prototype, {
buildcueprevioustrack: function( player, controls ) {
$( '<div class="mejs-button mejs-previous-button mejs-previous">' +
'<button type="button" aria-controls="' + player.id + '" title="' + cue.l10n.previousTrack + '"></button>' +
'</div>' )
.appendTo( controls )
.on( 'click.cue', function() {
var state,
track = player.cueGetCurrentTrack() || {};
state = $.extend({}, {
currentTime: media.currentTime,
duration: media.duration,
src: media.src
});
player.$node.trigger( 'skipBack.cue', [ state, track ] );
player.cuePlayPreviousTrack();
});
},
// @todo Go to previous playable track.
cuePlayPreviousTrack: function() {
var player = this,
index = player.cueCurrentTrack - 1 < 0 ? player.options.cuePlaylistTracks.length - 1 : player.cueCurrentTrack - 1;
player.$node.trigger( 'previousTrack.cue', player );
player.cueSetCurrentTrack( index );
}
});
})( this, jQuery, window.cue );
|
Hide version in footer on mobile devices
|
import React from 'react'
import { List, Responsive } from 'semantic-ui-react'
import { version } from 'package.json'
export default function Footer() {
let versionStr
if (GIT_TAG && GIT_TAG !== 'unknown') versionStr = GIT_TAG
if (GIT_COMMIT && GIT_COMMIT !== 'unknown') versionStr = GIT_COMMIT
if (!versionStr) versionStr = version
return (
<React.Fragment>
<List horizontal inverted divided link>
<List.Item as='a' href='#'>© Server Name Here</List.Item>
<List.Item as='a' href='#'>Contact Us</List.Item>
<List.Item as='a' href='#'>Link Example</List.Item>
</List>
<Responsive
minWidth={Responsive.onlyTablet.minWidth}
as={List}
floated='right'
horizontal>
<List.Item as='a' href='https://github.com/BanManagement/BanManager-WebUI' floated='right'>v{versionStr}</List.Item>
</Responsive>
</React.Fragment>
)
}
|
import React from 'react'
import { List } from 'semantic-ui-react'
import { version } from 'package.json'
export default function Footer() {
let versionStr
if (GIT_TAG && GIT_TAG !== 'unknown') versionStr = GIT_TAG
if (GIT_COMMIT && GIT_COMMIT !== 'unknown') versionStr = GIT_COMMIT
if (!versionStr) versionStr = version
return (
<React.Fragment>
<List horizontal inverted divided link>
<List.Item as='a' href='#'>© Server Name Here</List.Item>
<List.Item as='a' href='#'>Contact Us</List.Item>
<List.Item as='a' href='#'>Link Example</List.Item>
</List>
<List floated='right' horizontal>
<List.Item as='a' href='https://github.com/BanManagement/BanManager-WebUI' floated='right'>v{versionStr}</List.Item>
</List>
</React.Fragment>
)
}
|
Fix test of Wild defaults.
|
package mytown.test.config.json;
import mytown.config.json.FlagsConfig;
import myessentials.json.JsonConfig;
import mytown.config.json.WildPermsConfig;
import mytown.entities.Wild;
import mytown.entities.flag.Flag;
import mytown.test.TestMain;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class JsonConfigTest {
private List<JsonConfig> jsonConfigs;
@Before
public void shouldInitConfigs() {
TestMain.main();
jsonConfigs = new ArrayList<JsonConfig>();
//jsonConfigs.add(new RanksConfig(path + "/DefaultRanks.json"));
jsonConfigs.add(new WildPermsConfig(TestMain.path + "/WildPerms.json"));
jsonConfigs.add(new FlagsConfig(TestMain.path + "/DefaultFlags.json"));
}
@Test
public void shouldLoadConfigs() {
for (JsonConfig jsonConfig : jsonConfigs) {
jsonConfig.init();
}
}
@Test
public void shouldWildHaveProperValues() {
for(Flag flag : Wild.instance.flagsContainer) {
Assert.assertEquals(flag.value, flag.flagType.defaultWildValue);
}
}
}
|
package mytown.test.config.json;
import mytown.config.json.FlagsConfig;
import myessentials.json.JsonConfig;
import mytown.config.json.WildPermsConfig;
import mytown.entities.Wild;
import mytown.entities.flag.Flag;
import mytown.test.TestMain;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
/**
*
*/
public class JsonConfigTest {
private List<JsonConfig> jsonConfigs;
@Before
public void shouldInitConfigs() {
TestMain.main();
jsonConfigs = new ArrayList<JsonConfig>();
//jsonConfigs.add(new RanksConfig(path + "/DefaultRanks.json"));
jsonConfigs.add(new WildPermsConfig(TestMain.path + "/WildPerms.json"));
jsonConfigs.add(new FlagsConfig(TestMain.path + "/DefaultFlags.json"));
}
@Test
public void shouldLoadConfigs() {
for (JsonConfig jsonConfig : jsonConfigs) {
jsonConfig.init();
}
}
@Test
public void shouldWildHaveProperValues() {
for(Flag flag : Wild.instance.flagsContainer) {
Assert.assertEquals(flag.value, flag.flagType.defaultValue);
}
}
}
|
Fix readOnly attribute not taken in account
|
import { transformAttributes } from "../../components/form/dynamic-attributes";
function serializeValue(fieldType, value) {
if(fieldType === 'autocomplete') {
return !!value ? value.id : value;
}
return value;
}
function serializeData(data, fields) {
return Object.entries(data).reduce((res, [fieldKey, value]) => {
const field = fields[fieldKey];
return {
...res,
[fieldKey]: serializeValue(field.type, value),
}
}, {});
}
export function transformFields(fields, data) {
const serializedData = serializeData(data, fields);
return Object.entries(fields).reduce((res, [fieldKey, field]) => {
const {
attributes,
resolvedEmptyAttributes,
} = transformAttributes(field, field.dynamicAttributes, serializedData);
const readOnly = attributes.readOnly || resolvedEmptyAttributes.length > 0;
return {
...res,
[fieldKey]: {
...attributes,
readOnly,
},
};
}, {});
}
|
import { transformAttributes } from "../../components/form/dynamic-attributes";
function serializeValue(fieldType, value) {
if(fieldType === 'autocomplete') {
return !!value ? value.id : value;
}
return value;
}
function serializeData(data, fields) {
return Object.entries(data).reduce((res, [fieldKey, value]) => {
const field = fields[fieldKey];
return {
...res,
[fieldKey]: serializeValue(field.type, value),
}
}, {});
}
export function transformFields(fields, data) {
const serializedData = serializeData(data, fields);
return Object.entries(fields).reduce((res, [fieldKey, field]) => {
const {
attributes,
resolvedEmptyAttributes,
} = transformAttributes(field, field.dynamicAttributes, serializedData);
const readOnly = resolvedEmptyAttributes.length > 0;
return {
...res,
[fieldKey]: {
...attributes,
readOnly,
},
};
}, {});
}
|
Add some comments and rename TextField instance
|
enchant();
window.onload = function () {
var core = new Core(320, 320);
core.onload = function () {
core.rootScene.backgroundColor = '#eee';
// Create an instance of enchant.TextField
var textField = new TextField(160, 24);
// Set position
textField.x = (core.width - textField.width) / 2;
textField.y = 64;
// Set placeholder
textField.placeholder = 'what is your name ?';
// Set styles
textField.style.border = '2px solid #f6c';
textField.style.borderRadius = '4px';
// Define events
textField.onfocus = function () {
label.text = 'onfocus called!!';
};
textField.onblur = function () {
label.text = 'onblur called!!';
};
textField.onreturn = function () {
label.text = 'onreturn called!!<br>' + this.value + '!!';
};
// Add to the scene
core.rootScene.addChild(textField);
var label = new Label();
label.font = '32px Arial';
label.width = 320;
label.height = 32;
label.x = 0;
label.y = core.height - label.height * 2;
label.textAlign = 'center';
core.rootScene.addChild(label);
};
core.start();
};
|
enchant();
window.onload = function () {
var core = new Core(320, 320);
core.onload = function () {
core.rootScene.backgroundColor = '#eee';
var field = new TextField(160, 24);
field.x = (core.width - field.width) / 2;
field.y = 64;
field.placeholder = 'what is your name ?';
field.style.border = '2px solid #f6c';
field.style.borderRadius = '4px';
field.onfocus = function () {
label.text = 'onfocus called!!';
};
field.onblur = function () {
label.text = 'onblur called!!';
};
field.onreturn = function () {
label.text = 'onreturn called!!<br>' + this.value + '!!';
};
core.rootScene.addChild(field);
var label = new Label();
label.font = '32px Arial';
label.width = 320;
label.height = 32;
label.x = 0;
label.y = core.height - label.height * 2;
label.textAlign = 'center';
core.rootScene.addChild(label);
};
core.start();
};
|
Add unit test for tagName
|
import {createContainer} from 'stardux'
import View from '../../../src/dragon/views/base'
describe('Unit: View', function() {
/*
TODO: what happens if:
- there is no container?
- there is no template?
*/
it.skip('should initialize', function(done) {
var view = new View({
})
expect(view).to.be.an('object')
done()
})
it('should create view from container (string reference)', function(done) {
var view = new View({
container: '#app',
template: 'Hello World'
})
expect(view).to.be.an('object')
done()
})
it.skip('should create view from container', function(done) {
var view = new View({
container: createContainer(document.querySelector('#app'))
})
expect(view).to.be.an('object')
done()
})
it('should manually attach to DOM', function(done) {
var view = new View({
attachOnInit: false,
container: '#app',
template: 'Hello World'
})
view.on('addedToDOM', function() {
done()
})
view.attach()
})
it('should have a tagName <nav>', function(done) {
var view = new View({
container: '#app',
tagName: 'nav',
template: 'Hello World'
})
expect(view.tagName).to.equal('nav')
done()
})
})
|
import {createContainer} from 'stardux'
import View from '../../../src/dragon/views/base'
describe('Unit: View', function() {
/*
TODO: what happens if:
- there is no container?
- there is no template?
*/
it.skip('should initialize', function(done) {
var view = new View({
})
expect(view).to.be.an('object')
done()
})
it('should create view from container (string reference)', function(done) {
var view = new View({
container: '#app',
template: 'Hello World'
})
expect(view).to.be.an('object')
done()
})
it.skip('should create view from container', function(done) {
var view = new View({
container: createContainer(document.querySelector('#app'))
})
expect(view).to.be.an('object')
done()
})
it('should manually attach to DOM', function(done) {
var view = new View({
attachOnInit: false,
container: '#app',
template: 'Hello World'
})
view.on('addedToDOM', function() {
done()
})
view.attach()
})
})
|
Split migration script of customform
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-04 10:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('workflow', '0007_auto_20171204_0203'),
('formlibrary', '0004_customform_created_by'),
]
operations = [
migrations.AddField(
model_name='customform',
name='form_uuid',
field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'),
),
migrations.AddField(
model_name='customform',
name='silo_id',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='customform',
name='workflowlevel1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'),
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-12-04 10:03
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import uuid
class Migration(migrations.Migration):
dependencies = [
('workflow', '0007_auto_20171204_0203'),
('formlibrary', '0004_customform_created_by'),
]
operations = [
migrations.AddField(
model_name='customform',
name='form_uuid',
field=models.CharField(default='', max_length=255, verbose_name='CustomForm UUID'),
),
migrations.AddField(
model_name='customform',
name='silo_id',
field=models.IntegerField(default=0),
),
migrations.AddField(
model_name='customform',
name='workflowlevel1',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='workflow.WorkflowLevel1'),
),
]
|
Read port number for target site from JSON config
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var fs = require('fs');
var app = express();
var json = fs.readFileSync(__dirname + '/../config.json', 'utf8');
var fakeminder_config = JSON.parse(json);
// all environments
app.set('port', fakeminder_config.target_site.port);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
|
Save reference to original server properly.
|
(function(Monarch) {
Monarch.Remote.FakeServer = new JS.Singleton('Monarch.Remote.FakeServer', {
initialize: function() {
this.reset();
},
create: function(record, wireRepresentation) {
return new Monarch.Remote.FakeCreateRequest(this, record, wireRepresentation);
},
update: function(record, wireRepresentation) {
return new Monarch.Remote.FakeUpdateRequest(this, record, wireRepresentation);
},
destroy: function(record) {
return new Monarch.Remote.FakeDestroyRequest(this, record);
},
fetch: function() {
return new Monarch.Remote.FakeFetchRequest(this, _.toArray(arguments));
},
lastCreate: function() {
return _.last(this.creates);
},
lastUpdate: function() {
return _.last(this.updates);
},
lastDestroy: function() {
return _.last(this.destroys);
},
lastFetch: function() {
return _.last(this.fetches);
},
reset: function() {
this.creates = [];
this.updates = [];
this.destroys = [];
this.fetches = [];
}
});
Monarch.Remote.OriginalServer = Monarch.Remote.Server;
Monarch.useFakeServer = function() {
Monarch.Remote.Server = Monarch.Remote.FakeServer;
Monarch.Remote.Server.reset();
};
Monarch.restoreOriginalServer = function() {
Monarch.Remote.Server = Monarch.Remote.OriginalServer;
};
})(Monarch);
|
(function(Monarch) {
Monarch.Remote.FakeServer = new JS.Singleton('Monarch.Remote.FakeServer', {
initialize: function() {
this.reset();
},
create: function(record, wireRepresentation) {
return new Monarch.Remote.FakeCreateRequest(this, record, wireRepresentation);
},
update: function(record, wireRepresentation) {
return new Monarch.Remote.FakeUpdateRequest(this, record, wireRepresentation);
},
destroy: function(record) {
return new Monarch.Remote.FakeDestroyRequest(this, record);
},
fetch: function() {
return new Monarch.Remote.FakeFetchRequest(this, _.toArray(arguments));
},
lastCreate: function() {
return _.last(this.creates);
},
lastUpdate: function() {
return _.last(this.updates);
},
lastDestroy: function() {
return _.last(this.destroys);
},
lastFetch: function() {
return _.last(this.fetches);
},
reset: function() {
this.creates = [];
this.updates = [];
this.destroys = [];
this.fetches = [];
}
});
Monarch.Remote.OriginalServer = Monarch.Remote.OriginalServer;
Monarch.useFakeServer = function() {
Monarch.Remote.Server = Monarch.Remote.FakeServer;
Monarch.Remote.Server.reset();
};
Monarch.restoreOriginalServer = function() {
Monarch.Remote.Server = Monarch.Remote.OriginalServer;
};
})(Monarch);
|
LUCENE-1769: Add also the opposite assert statement
git-svn-id: 4c5078813df38efa56971a28e09a55254294f104@891907 13f79535-47bb-0310-9956-ffa450edef68
|
package org.apache.lucene;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.util.LuceneTestCase;
public class TestAssertions extends LuceneTestCase {
public void test() {
try {
assert Boolean.FALSE.booleanValue();
fail("assertions are not enabled!");
} catch (AssertionError e) {
assert Boolean.TRUE.booleanValue();
}
}
}
|
package org.apache.lucene;
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.lucene.util.LuceneTestCase;
public class TestAssertions extends LuceneTestCase {
public void test() {
try {
assert Boolean.FALSE.booleanValue();
fail("assertions are not enabled!");
} catch (AssertionError e) {
}
}
}
|
Fix: Include the invalid glob in error message
|
'use strict';
var defaults = require('lodash.defaults');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var getContents = require('./getContents');
var getStats = require('./getStats');
function createFile (globFile, enc, cb) {
cb(null, new File(globFile));
}
function src(glob, opt) {
if (!isValidGlob(glob)) {
throw new Error('Invalid glob argument: ' + glob);
}
var options = defaults({}, opt, {
read: true,
buffer: true
});
var globStream = gs.create(glob, options);
// when people write to use just pass it through
var outputStream = globStream
.pipe(through.obj(createFile))
.pipe(getStats(options));
if (options.read !== false) {
outputStream = outputStream
.pipe(getContents(options));
}
return outputStream
.pipe(through.obj());
}
function isValidGlob(glob) {
if (typeof glob === 'string') {
return true;
}
if (Array.isArray(glob) && glob.length !== 0) {
return true;
}
return false;
}
module.exports = src;
|
'use strict';
var defaults = require('lodash.defaults');
var through = require('through2');
var gs = require('glob-stream');
var File = require('vinyl');
var getContents = require('./getContents');
var getStats = require('./getStats');
function createFile (globFile, enc, cb) {
cb(null, new File(globFile));
}
function src(glob, opt) {
if (!isValidGlob(glob)) {
throw new Error('Invalid glob argument');
}
var options = defaults({}, opt, {
read: true,
buffer: true
});
var globStream = gs.create(glob, options);
// when people write to use just pass it through
var outputStream = globStream
.pipe(through.obj(createFile))
.pipe(getStats(options));
if (options.read !== false) {
outputStream = outputStream
.pipe(getContents(options));
}
return outputStream
.pipe(through.obj());
}
function isValidGlob(glob) {
if (typeof glob === 'string') {
return true;
}
if (Array.isArray(glob) && glob.length !== 0) {
return true;
}
return false;
}
module.exports = src;
|
Put a blank line before section headings.
|
"""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('')
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
|
"""Formatters for creating documents.
A formatter is an object which accepts an output stream (usually a file or
standard output) and then provides a structured way for writing to that stream.
All formatters should provide 'title', 'section', 'subsection' and 'paragraph'
methods which write to the stream.
"""
class WikiFormatter(object):
"""Moin formatter."""
def __init__(self, stream):
self.stream = stream
def writeln(self, line):
self.stream.write('%s\n' % (line,))
def title(self, name):
self.writeln('= %s =\n' % (name,))
def section(self, name):
self.writeln('== %s ==\n' % (name,))
def subsection(self, name):
self.writeln('=== %s ===\n' % (name,))
def paragraph(self, text):
self.writeln('%s\n' % (text.strip(),))
|
TODO: Replace with something that handles more than just 'double' ...
|
package org.csstudio.platform.model;
/**
* Interface to a control system process variable with archive data source.
* <p>
*
* @see IProcessVariableName
* @see IArchiveDataSource
* @author Jan Hatje and Helge Rickens
*
* TODO It's actually ... process variable with actual data.
* TODO This is limited to double-type samples.
* Use either DAL, or the intermediate Value from org.csstudio.utility.pv,
* which supports more data types as well as their MetaData.
*/
public interface IProcessVariableWithSample extends IProcessVariable {
/**
* The global type id.
*/
String TYPE_ID = "css:processVariableWithSample"; //$NON-NLS-1$
/**
*
* @return
*/
double[] getSampleValue();
/**
*
* TODO Use the Timestamp (ITimestamp) found elsewhere in this plugin.
* @return
*/
double[] getTimeStamp();
/**
*
*
* @return
*/
String[] getStatus();
/**
*
*
* @return
*/
String[] getSeverity();
/**
*
*
* @return
*/
int getDBRTyp();
/**
*
*
* @return
*/
String getEGU();
/**
*
*
* @return
*/
int getPrecision();
/**
*
*
* @return
*/
double getLow();
/**
*
*
* @return
*/
double getHigh();
}
|
package org.csstudio.platform.model;
/**
* Interface to a control system process variable with archive data source.
* <p>
*
* @see IProcessVariableName
* @see IArchiveDataSource
* @author Jan Hatje and Helge Rickens
*
*/
public interface IProcessVariableWithSample extends IProcessVariable {
/**
* The global type id.
*/
String TYPE_ID = "css:processVariableWithSample"; //$NON-NLS-1$
/**
*
*
* @return
*/
double[] getSampleValue();
/**
*
*
* @return
*/
double[] getTimeStamp();
/**
*
*
* @return
*/
String[] getStatus();
/**
*
*
* @return
*/
String[] getSeverity();
/**
*
*
* @return
*/
int getDBRTyp();
/**
*
*
* @return
*/
String getEGU();
/**
*
*
* @return
*/
int getPrecision();
/**
*
*
* @return
*/
double getLow();
/**
*
*
* @return
*/
double getHigh();
}
|
Exclude tests from installed packages
|
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(exclude=["tests.*", "tests"]),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
|
from setuptools import setup, find_packages
setup(
name="IIS",
version="0.0",
long_description=__doc__,
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=[
"Flask>=0.11.1,<0.12.0",
"Flask-Bootstrap>=3.3.7.0,<4.0.0.0",
"Flask-Login>=0.3.2,<0.4.0",
"Flask-Mail>=0.9.1,<0.10.0",
"Flask-SQLAlchemy>=2.1,<3.0",
"Flask-User>=0.6.8,<0.7.0",
"Flask-WTF>=0.12,<0.13.0",
"Flask-Migrate>=2.0.0,<3.0.0",
"Flask-Testing>=0.6.1,<0.7.0"
],
extras_require={
'dev': [
'mypy-lang>=0.4.4,<0.5.0'
]
}
)
|
Replace deprecated custom function call
|
<?php
namespace Lmc\Steward\Component;
abstract class AbstractComponent
{
/** @var \Lmc\Steward\Test\AbstractTestCaseBase */
protected $tc;
/** @var string */
protected $componentName;
/**
* @param \Lmc\Steward\Test\AbstractTestCaseBase $tc TestCase instance
*/
public function __construct(\Lmc\Steward\Test\AbstractTestCaseBase $tc)
{
$this->tc = $tc;
$reflection = new \ReflectionClass($this);
$this->componentName = $reflection->getShortName();
}
public function __call($name, $arguments)
{
// Methods log() and warn() prepend componentName to message and call the same method on TestCase.
if ($name == 'log' || $name == 'warn') {
$arguments[0] = '[' . $this->componentName . '] ' . $arguments[0];
call_user_func_array([$this->tc, $name], $arguments);
}
}
}
|
<?php
namespace Lmc\Steward\Component;
abstract class AbstractComponent
{
/** @var \Lmc\Steward\Test\AbstractTestCaseBase */
protected $tc;
/** @var string */
protected $componentName;
/**
* @param \Lmc\Steward\Test\AbstractTestCaseBase $tc TestCase instance
*/
public function __construct(\Lmc\Steward\Test\AbstractTestCaseBase $tc)
{
$this->tc = $tc;
$reflection = new \ReflectionClass($this);
$this->componentName = $reflection->getShortName();
}
public function __call($name, $arguments)
{
// Methods log() and warn() prepend componentName to message and call the same method on TestCase.
if ($name == 'log' || $name == 'warn') {
$arguments[0] = '[' . $this->componentName . '] ' . $arguments[0];
call_user_method_array($name, $this->tc, $arguments);
}
}
}
|
Make this useful for py3 also
|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Run a simple trace function on a file of Python code."""
import os, sys
nest = 0
def trace(frame, event, arg):
global nest
if nest is None:
# This can happen when Python is shutting down.
return None
print("%s%s %s %d @%d" % (
" " * nest,
event,
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
frame.f_lasti,
))
if event == 'call':
nest += 1
if event == 'return':
nest -= 1
return trace
the_program = sys.argv[1]
code = open(the_program).read()
sys.settrace(trace)
exec(code)
|
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/nedbat/coveragepy/blob/master/NOTICE.txt
"""Run a simple trace function on a file of Python code."""
import os, sys
nest = 0
def trace(frame, event, arg):
global nest
if nest is None:
# This can happen when Python is shutting down.
return None
print("%s%s %s %d @%d" % (
" " * nest,
event,
os.path.basename(frame.f_code.co_filename),
frame.f_lineno,
frame.f_lasti,
))
if event == 'call':
nest += 1
if event == 'return':
nest -= 1
return trace
the_program = sys.argv[1]
sys.settrace(trace)
execfile(the_program)
|
Revert use of bintrees; it's not a great fit.
|
#!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://www.github.com/locationlabs/mockredis',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose==1.2.1'
],
install_requires=[
],
tests_require=[
'redis>=2.7.2'
],
test_suite='mockredis.tests',
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
# Match releases to redis-py versions
__version__ = '2.7.2'
# Jenkins will replace __build__ with a unique value.
__build__ = ''
setup(name='mockredis',
version=__version__ + __build__,
description='Mock for redis-py',
url='http://www.github.com/locationlabs/mockredis',
license='Apache2',
packages=find_packages(exclude=['*.tests']),
setup_requires=[
'nose==1.2.1'
],
install_requires=[
'bintrees==1.0.1'
],
tests_require=[
'redis>=2.7.2'
],
test_suite='mockredis.tests',
)
|
Reset internal DIV clock on resetting the counter.
|
package eu.rekawek.coffeegb.timer;
import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Counter {
private final int frequency;
private final SpeedMode speedMode;
private int clocks;
private int counter;
public Counter(int frequency, SpeedMode speedMode) {
this.frequency = frequency;
this.speedMode = speedMode;
}
public boolean tick() {
int divider = Gameboy.TICKS_PER_SEC / frequency;
if (speedMode != null) {
divider /= speedMode.getSpeedMode();
}
if (++clocks >= divider) {
clocks = 0;
counter = (counter + 1) & 0xff;
return true;
} else {
return false;
}
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
this.clocks = 0;
}
}
|
package eu.rekawek.coffeegb.timer;
import eu.rekawek.coffeegb.Gameboy;
import eu.rekawek.coffeegb.cpu.SpeedMode;
public class Counter {
private final int frequency;
private final SpeedMode speedMode;
private int clocks;
private int counter;
public Counter(int frequency, SpeedMode speedMode) {
this.frequency = frequency;
this.speedMode = speedMode;
}
public boolean tick() {
int divider = Gameboy.TICKS_PER_SEC / frequency;
if (speedMode != null) {
divider /= speedMode.getSpeedMode();
}
if (++clocks >= divider) {
clocks = 0;
counter = (counter + 1) & 0xff;
return true;
} else {
return false;
}
}
public int getCounter() {
return counter;
}
public void setCounter(int counter) {
this.counter = counter;
}
}
|
Create the BrowserWindow as unresizable instead of setting it later
|
const path = require('path');
const {ipcMain} = require('electron');
const menubar = require('menubar')({
index: `file://${__dirname}/dist/index.html`,
icon: path.join(__dirname, 'static', 'iconTemplate.png'),
width: 250,
height: 500,
preloadWindow: true,
transparent: true,
resizable: false
});
if (process.env.DEBUG_FOCUS) {
const electronExecutable = `${__dirname}/../node_modules/electron/dist/Electron.app/Contents/MacOS/Electron`;
require('electron-reload')(`${__dirname}/dist`, {electron: electronExecutable}); // eslint-disable-line import/newline-after-import
menubar.setOption('alwaysOnTop', true);
}
menubar.on('after-create-window', () => {
if (process.env.DEBUG_FOCUS) {
menubar.window.openDevTools({mode: 'detach'});
}
});
ipcMain.on('set-window-size', (event, args) => {
if (args.width && args.height && menubar.window) {
menubar.window.setSize(args.width, args.height, true); // true == animate
}
});
|
const path = require('path');
const {ipcMain} = require('electron');
const menubar = require('menubar')({
index: `file://${__dirname}/dist/index.html`,
icon: path.join(__dirname, 'static', 'iconTemplate.png'),
width: 250,
height: 500,
preloadWindow: true,
transparent: true
});
if (process.env.DEBUG_FOCUS) {
const electronExecutable = `${__dirname}/../node_modules/electron/dist/Electron.app/Contents/MacOS/Electron`;
require('electron-reload')(`${__dirname}/dist`, {electron: electronExecutable}); // eslint-disable-line import/newline-after-import
menubar.setOption('alwaysOnTop', true);
}
menubar.on('after-create-window', () => {
if (process.env.DEBUG_FOCUS) {
menubar.window.openDevTools({mode: 'detach'});
}
menubar.window.setResizable(false);
});
ipcMain.on('set-window-size', (event, args) => {
if (args.width && args.height && menubar.window) {
menubar.window.setSize(args.width, args.height, true); // true == animate
}
});
|
Clean up HTML Table visual callback
Fixes #79.
|
/**
* Generates a function that moves the cursor on a Google Chart
* @private
* @param {GoogleChart} chart - the in-memory GoogleChart object
* @returns {VisualCallback} the callback
*/
var googleVisualCallbackMaker = function(chart) {
return function(series, row) {
chart.setSelection([
{
'row': row,
'column': series + 1
}
])
}
}
/**
* Generate a function that can be used to highlight table cells
* @private
* @param {HTMLTableElement} table - The in-DOM table element
* @param {string} className - Name of the CSS highlight class
* @returns {VisualCallback} The highlighting function
*/
var htmlTableVisualCallbackMaker = function(table, className) {
return function(series, row) {
const tds = table.getElementsByTagName('td')
for (const cell of tds) {
cell.classList.remove(className)
}
tds[row].classList.add(className)
}
}
/**
* Generates a function that moves the cursor on a C3 Chart
* @private
* @param {Object} chart - the in-memory C3 chart object
* @returns {VisualCallback} the callback
* @todo define C3 chart type?
*/
var c3VisualCallbackMaker = function(chart) {
return function(series, row) {
chart.select(null, [row], true)
}
}
|
/**
* Generates a function that moves the cursor on a Google Chart
* @private
* @param {GoogleChart} chart - the in-memory GoogleChart object
* @returns {VisualCallback} the callback
*/
var googleVisualCallbackMaker = function(chart) {
return function(series, row) {
chart.setSelection([
{
'row': row,
'column': series + 1
}
])
}
}
/**
* Generate a function that can be used to highlight table cells
* @private
* @param {HTMLTableElement} table - The in-DOM table element
* @param {string} className - Name of the CSS highlight class
* @returns {VisualCallback} The highlighting function
*/
var htmlTableVisualCallbackMaker = function(table, className) {
return function(series, row) {
const tds = table.getElementsByTagName('td')
let cell // TODO remove
for (let i = 0; i < tds.length; i++) {
cell = tds[i]
cell.classList.remove(className)
}
cell = table.getElementsByTagName('td')[row]
cell.classList.add(className)
}
}
/**
* Generates a function that moves the cursor on a C3 Chart
* @private
* @param {Object} chart - the in-memory C3 chart object
* @returns {VisualCallback} the callback
* @todo define C3 chart type?
*/
var c3VisualCallbackMaker = function(chart) {
return function(series, row) {
chart.select(null, [row], true)
}
}
|
Fix wrong Redis DB setting
|
from __future__ import absolute_import
import dj_database_url
import urlparse
from os import environ
from .base import *
ENV = 'HEROKU'
# Store files on S3
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
redis_url = urlparse.urlparse(environ.get('REDISTOGO_URL'))
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port),
'OPTIONS': {
'PASSWORD': redis_url.password,
'DB': 0,
},
},
}
# Grab database info
DATABASES = {
'default': dj_database_url.config()
}
# Setup sentry / raven
SENTRY_DSN = environ.get('SENTRY_DSN')
INSTALLED_APPS += (
'raven.contrib.django',
)
|
from __future__ import absolute_import
import dj_database_url
import urlparse
from os import environ
from .base import *
ENV = 'HEROKU'
# Store files on S3
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
redis_url = urlparse.urlparse(environ.get('REDISTOGO_URL'))
CACHES = {
'default': {
'BACKEND': 'redis_cache.RedisCache',
'LOCATION': '%s:%s' % (redis_url.hostname, redis_url.port),
'OPTIONS': {
'PASSWORD': redis_url.password,
'DB': 1,
},
},
}
# Grab database info
DATABASES = {
'default': dj_database_url.config()
}
# Setup sentry / raven
SENTRY_DSN = environ.get('SENTRY_DSN')
INSTALLED_APPS += (
'raven.contrib.django',
)
|
[FIX] Create Code Toolbar Action repaired
|
package de.fu_berlin.imp.apiua.groundedtheory.handlers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
import com.bkahlert.nebula.utils.selection.retriever.SelectionRetrieverFactory;
import de.fu_berlin.imp.apiua.groundedtheory.model.ICode;
import de.fu_berlin.imp.apiua.groundedtheory.ui.Utils;
import de.fu_berlin.imp.apiua.groundedtheory.ui.wizards.WizardUtils;
public class CreateCodeHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger LOGGER = Logger
.getLogger(CreateCodeHandler.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Collection<?> menus = HandlerUtil.getActiveMenus(event);
List<ICode> codes = menus != null && menus.size() > 0 ? SelectionRetrieverFactory
.getSelectionRetriever(ICode.class).getSelection()
: new LinkedList<ICode>();
assert codes.size() < 2;
WizardUtils.openNewCodeWizard(codes.size() == 1 ? codes.get(0) : null,
Utils.getFancyCodeColor());
return null;
}
}
|
package de.fu_berlin.imp.apiua.groundedtheory.handlers;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.handlers.HandlerUtil;
import com.bkahlert.nebula.utils.selection.retriever.SelectionRetrieverFactory;
import de.fu_berlin.imp.apiua.groundedtheory.model.ICode;
import de.fu_berlin.imp.apiua.groundedtheory.ui.Utils;
import de.fu_berlin.imp.apiua.groundedtheory.ui.wizards.WizardUtils;
public class CreateCodeHandler extends AbstractHandler {
@SuppressWarnings("unused")
private static final Logger LOGGER = Logger
.getLogger(CreateCodeHandler.class);
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
Collection<?> menus = HandlerUtil.getActiveMenus(event);
List<ICode> codes = menus.size() > 0 ? SelectionRetrieverFactory
.getSelectionRetriever(ICode.class).getSelection()
: new LinkedList<ICode>();
assert codes.size() < 2;
WizardUtils.openNewCodeWizard(codes.size() == 1 ? codes.get(0) : null,
Utils.getFancyCodeColor());
return null;
}
}
|
Tidy up JS, add commentary
|
window.atthemovies = {
init: function() {
var body = document.querySelectorAll("body")[0];
var jsController = body.getAttribute("data-js-controller");
var jsAction = body.getAttribute("data-js-action");
this.pageJS("atthemovies." + jsController + ".init", window);
this.pageJS("atthemovies." + jsController + ".init" + jsAction, window);
},
// pass a string to call a namespaced function that may not exist
pageJS: function(functionString, context) {
var namespaces = functionString.split(".");
var functionName = namespaces.pop();
// recursively loop into existing namespaces, else return harmlessly
for (var i = 0; i < namespaces.length; i++) {
if(context[namespaces[i]]) {
context = context[namespaces[i]];
} else {
return null;
}
}
// call the function if it exists in this context, else return harmlessly
if(typeof context[functionName] === "function") {
return context[functionName].apply(context, null);
} else {
return null;
}
}
}
|
window.atthemovies = {
init: function() {
var body = document.querySelectorAll("body")[0];
var jsController = body.getAttribute("data-js-controller");
var jsAction = body.getAttribute("data-js-action");
this.pageJS("atthemovies." + jsController + ".init", window);
this.pageJS("atthemovies." + jsController + ".init" + jsAction, window);
},
pageJS: function(functionName, context) {
var namespaces = functionName.split(".");
var func = namespaces.pop();
for (var i = 0; i < namespaces.length; i++) {
if(context[namespaces[i]]) {
context = context[namespaces[i]];
} else {
return null;
}
}
if(typeof context[func] === "function") {
return context[func].apply(context, null);
} else {
return null;
}
}
}
|
Fix for memleak when user callback is not truly-async.
|
var csv = require('binary-csv');
var through2 = require('through2');
/**
* Parses an input stream.
*
* @param {object} stream
* @param {function} item_callback
* @param {function} done
* @return {void}
*/
module.exports.read = function(stream, item_callback, done) {
var parser = csv({
separator: '\t',
newline: '\n',
detectNewlines: true
});
var waiting = 0;
var transformer = through2(function(chunk, enc, callback) {
var cells, was_async;
cells = parser.line(chunk).map(function(cell) {
return cell.toString('utf8');
});
waiting++;
was_async = false;
item_callback(cells, function(err) {
waiting--;
cells = null;
if (!was_async) {
process.nextTick(function() {
callback(err);
});
} else {
callback(err);
}
});
was_async = true;
});
var finish = function(err) {
if (!waiting) {
return done(err);
}
setTimeout(finish, 10);
};
stream.on('end', finish);
stream.pipe(parser).pipe(transformer);
};
|
var csv = require('binary-csv');
var through2 = require('through2');
/**
* Parses an input stream.
*
* @param {object} stream
* @param {function} item_callback
* @param {function} done
* @return {void}
*/
module.exports.read = function(stream, item_callback, done) {
var parser = csv({
separator: '\t',
newline: '\n',
detectNewlines: true
});
var waiting = 0;
var transformer = through2(function(chunk, enc, callback) {
var cells = parser.line(chunk).map(function(cell) {
return cell.toString('utf8');
});
waiting++;
item_callback(cells, function(err) {
waiting--;
callback(err);
});
});
var finish = function(err) {
if (!waiting) {
return done(err);
}
setTimeout(finish, 10);
};
stream.on('end', finish);
stream.pipe(parser).pipe(transformer);
};
|
Fix an issue where the `_cards` attribute in StudySet was used.
|
import click
import os
from flashcards import storage
from flashcards.study import BaseStudySession
from flashcards.commands import sets as sets_commands
from flashcards.commands import cards as cards_commands
@click.group()
def cli():
""" Main entry point of the application """
# Verify that the storage directory is present.
storage.verify_storage_dir_integrity()
pass
@click.command('status')
def status():
"""
Show status of the application.
Displaying the currently selected studyset.
- studyset title
- studyset description
- number of cards
"""
studyset = storage.load_selected_studyset()
data = (studyset.title, len(studyset))
click.echo('Currently using studyset: %s (%s cards)\n' % data)
click.echo('Description: \n%s' % studyset.description)
@click.command('study')
@click.argument('studyset')
def study(studyset):
""" Start a study session on the supplied studyset. """
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
studyset = storage.load_studyset(studyset_path).load()
studysession = BaseStudySession()
studysession.start(studyset)
# Add the subcommands to this main entry point.
cli.add_command(status)
cli.add_command(study)
cli.add_command(sets_commands.sets_group)
cli.add_command(cards_commands.cards_group)
|
import click
import os
from flashcards import storage
from flashcards.study import BaseStudySession
from flashcards.commands import sets as sets_commands
from flashcards.commands import cards as cards_commands
@click.group()
def cli():
""" Main entry point of the application """
# Verify that the storage directory is present.
storage.verify_storage_dir_integrity()
pass
@click.command('status')
def status():
"""
Show status of the application.
Displaying the currently selected studyset.
- studyset title
- studyset description
- number of cards
"""
studyset = storage.load_selected_studyset()
data = (studyset.title, len(studyset._cards))
click.echo('Currently using studyset: %s (%s cards)\n' % data)
click.echo('Description: \n%s' % studyset.description)
@click.command('study')
@click.argument('studyset')
def study(studyset):
""" Start a study session on the supplied studyset. """
studyset_path = os.path.join(storage.studyset_storage_path(), studyset)
studyset = storage.load_studyset(studyset_path).load()
studysession = BaseStudySession()
studysession.start(studyset)
# Add the subcommands to this main entry point.
cli.add_command(status)
cli.add_command(study)
cli.add_command(sets_commands.sets_group)
cli.add_command(cards_commands.cards_group)
|
ADD usage informations on command line
If user supplied not files or arguments, the program ended like it was
normal and displayed no informations to the user on how he should have
used it.
Fix by adding information messages.
REF: #2
|
package main
import (
"flag"
"fmt"
"github.com/MaximeD/gost/conf"
"github.com/MaximeD/gost/gist"
"os"
)
var baseUrl string = "https://api.github.com/"
// get command line arguments
var gistDescriptionFlag = flag.String("description", "", "Description of the gist")
var gistPrivateFlag = flag.Bool("private", false, "Set gist to private")
var listGistsFlag = flag.String("list", "", "List gists for a user")
func init() {
flag.StringVar(gistDescriptionFlag, "d", "", "Description of the gist")
flag.BoolVar(gistPrivateFlag, "p", false, "Set gist to private")
flag.StringVar(listGistsFlag, "l", "", "List gists for a user")
}
func main() {
flag.Parse()
isPublic := !*gistPrivateFlag
// if nothing was given write message
if (flag.NFlag() == 0) && (len(flag.Args()) == 0) {
fmt.Println("No arguments or files given!")
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
os.Exit(2)
}
if *listGistsFlag != "" {
username := *listGistsFlag
url := baseUrl + "users/" + username + "/gists"
Gist.List(url)
} else {
filesName := flag.Args()
if len(filesName) == 0 {
fmt.Println("No files given!")
os.Exit(2)
}
token := Configuration.GetToken()
Gist.Post(baseUrl, token, isPublic, filesName, *gistDescriptionFlag)
}
}
|
package main
import (
"flag"
"github.com/MaximeD/gost/conf"
"github.com/MaximeD/gost/gist"
)
var baseUrl string = "https://api.github.com/"
// get command line arguments
var gistDescriptionFlag = flag.String("description", "", "Description of the gist")
var gistPrivateFlag = flag.Bool("private", false, "Tells if the gist is private")
var listGistsFlag = flag.String("list", "", "List gists for a user")
func init() {
flag.StringVar(gistDescriptionFlag, "d", "", "description")
flag.BoolVar(gistPrivateFlag, "p", false, "private")
flag.StringVar(listGistsFlag, "l", "", "list")
}
func main() {
flag.Parse()
isPublic := !*gistPrivateFlag
if *listGistsFlag != "" {
username := *listGistsFlag
url := baseUrl + "users/" + username + "/gists"
Gist.List(url)
} else {
token := Configuration.GetToken()
filesName := flag.Args()
Gist.Post(baseUrl, token, isPublic, filesName, *gistDescriptionFlag)
}
}
|
Move config.xml parsing into its own Config class
Now the parsing happens very early in the bootstrap process, before
loadUrl() is called. This enables a future change to put the start page
in config.xml instead of hardcoding it.
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 __ID__;
import android.os.Bundle;
import org.apache.cordova.*;
public class __ACTIVITY__ extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Config.init(this);
super.loadUrl("file:///android_asset/www/index.html");
}
}
|
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you 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 __ID__;
import android.app.Activity;
import android.os.Bundle;
import org.apache.cordova.*;
public class __ACTIVITY__ extends DroidGap
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
super.loadUrl("file:///android_asset/www/index.html");
}
}
|
Resolve to local react-router for UMD
|
import babel from 'rollup-plugin-babel'
import uglify from 'rollup-plugin-uglify'
import replace from 'rollup-plugin-replace'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
const config = {
input: 'modules/index.js',
name: 'ReactRouterDOM',
globals: {
react: 'React'
},
external: [
'react'
],
plugins: [
babel({
exclude: 'node_modules/**'
}),
resolve({
customResolveOptions: {
moduleDirectory: ['node_modules', '../']
}
}),
commonjs({
include: /node_modules/
}),
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
}
if (process.env.NODE_ENV === 'production') {
config.plugins.push(uglify())
}
export default config
|
import babel from 'rollup-plugin-babel'
import uglify from 'rollup-plugin-uglify'
import replace from 'rollup-plugin-replace'
import commonjs from 'rollup-plugin-commonjs'
import resolve from 'rollup-plugin-node-resolve'
const config = {
input: 'modules/index.js',
name: 'ReactRouterDOM',
globals: {
react: 'React'
},
external: [
'react'
],
plugins: [
babel({
exclude: 'node_modules/**'
}),
resolve(),
commonjs({
include: /node_modules/
}),
replace({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
}
if (process.env.NODE_ENV === 'production') {
config.plugins.push(uglify())
}
export default config
|
Update KeyValuePair model so delete and other operations which require "id"
attribute to be present still work.
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class KeyValuePair(core.Resource):
_alias = 'Key'
_display_name = 'Key Value Pair'
_plural = 'Keys'
_plural_display_name = 'Key Value Pairs'
_repr_attributes = ['name', 'value']
@property
def id(self):
# Note: This is a temporary hack until we refactor client and make it support non id PKs
return self.name
|
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from st2client.models import core
LOG = logging.getLogger(__name__)
class KeyValuePair(core.Resource):
_alias = 'Key'
_display_name = 'Key Value Pair'
_plural = 'Keys'
_plural_display_name = 'Key Value Pairs'
_repr_attributes = ['name', 'value']
|
Use ResponseError instead of NoScriptError to be compatible with earlier versions of the redis client
|
import hashlib
from redis.exceptions import ResponseError
class LuaScript(object):
def __init__(self, redis, template, cache):
self.redis = redis
self.template = template
self.cache = cache
self.script = self._render_template(template)
def _render_template(self, template):
if template.filename in self.cache:
script = self.cache[template.filename]
else:
script = template.render()
self.cache[template.filename] = script
return script
def _get_script_sha(self):
return hashlib.sha1(self.script).hexdigest()
def __call__(self, *args, **kwargs):
script_sha = self._get_script_sha()
keys = kwargs.get('keys', [])
arguments = kwargs.get('args', [])
num_keys = len(keys)
keys_and_args = keys + arguments
try:
response = self.redis.evalsha(script_sha, num_keys, *keys_and_args)
except ResponseError:
response = self.redis.eval(self.script, num_keys, *keys_and_args)
return response
|
import hashlib
from redis.exceptions import NoScriptError
class LuaScript(object):
def __init__(self, redis, template, cache):
self.redis = redis
self.template = template
self.cache = cache
self.script = self._render_template(template)
def _render_template(self, template):
if template.filename in self.cache:
script = self.cache[template.filename]
else:
script = template.render()
self.cache[template.filename] = script
return script
def _get_script_sha(self):
return hashlib.sha1(self.script).hexdigest()
def __call__(self, *args, **kwargs):
script_sha = self._get_script_sha()
keys = kwargs.get('keys', [])
arguments = kwargs.get('args', [])
num_keys = len(keys)
keys_and_args = keys + arguments
try:
response = self.redis.evalsha(script_sha, num_keys, *keys_and_args)
except NoScriptError:
response = self.redis.eval(self.script, num_keys, *keys_and_args)
return response
|
Add automatic launch with maven test phase
|
package com.socgen.finit.easymargin;
import com.socgen.finit.easymargin.converter.TradeFileHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import java.util.Arrays;
@Slf4j
@SpringBootApplication
@Import(DefaultConfig.class)
public class Application {
@Autowired
TradeFileHandler tradeFileHandler;
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
log.info("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
log.info(beanName);
}
log.info("Server started - URL : http//localhost:" +
ctx.getEnvironment().getProperty("server.port"));
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
|
package com.socgen.finit.easymargin;
import com.socgen.finit.easymargin.converter.TradeFileHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import java.util.Arrays;
@Slf4j
@SpringBootApplication
@Import(DefaultConfig.class)
public class Application {
@Autowired
TradeFileHandler tradeFileHandler;
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(Application.class, args);
log.info("Let's inspect the beans provided by Spring Boot:");
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
log.info(beanName);
}
}
@Bean
public HibernateExceptionTranslator hibernateExceptionTranslator() {
return new HibernateExceptionTranslator();
}
}
|
Implement Put for Project struct
|
package data
import (
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Project struct {
ID bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
OwnerID bson.ObjectId `bson:"owner_id"`
MemberIDs []bson.ObjectId `bson:"member_ids"`
CreatedAt time.Time `bson:"created_at"`
ModifiedAt time.Time `bson:"modified_at"`
}
func GetProject(id bson.ObjectId) (*Project, error) {
pro := Project{}
err := sess.DB("").C(projectC).FindId(id).One(&pro)
if err == mgo.ErrNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
return &pro, nil
}
func (p *Project) Put() error {
p.ModifiedAt = time.Now()
if p.ID == "" {
p.ID = bson.NewObjectId()
p.CreatedAt = p.ModifiedAt
}
_, err := sess.DB("").C(organizationC).UpsertId(p.ID, p)
return err
}
|
package data
import (
"time"
"gopkg.in/mgo.v2"
"gopkg.in/mgo.v2/bson"
)
type Project struct {
ID bson.ObjectId `bson:"_id"`
Name string `bson:"name"`
OwnerId bson.ObjectId `bson:"owner_id"`
MemberIds []bson.ObjectId `bson:"member_ids"`
CreatedAt time.Time `bson:"created_at"`
ModifiedAt time.Time `bson:"modified_at"`
}
func GetProject(id bson.ObjectId) (*Project, error) {
pro := Project{}
err := sess.DB("").C(projectC).FindId(id).One(&pro)
if err == mgo.ErrNotFound {
return nil, nil
}
if err != nil {
return nil, err
}
return &pro, nil
}
|
Fix Expired logic to catch Jobs never updated
|
UI.registerHelper("getPrettyDateAndTime", function(timestamp) {
if(timestamp)
return moment(timestamp).format('M/D/YY h:mm:ss A');
});
UI.registerHelper("getCurrentUserDisplayName", function() {
return getUserName(Meteor.user());
});
Template.expiredAlert.expired = function() {
if (this.userId == Meteor.userId()) {
if ((this.createdAt < daysUntilExpiration()) && (this.updatedAt < daysUntilExpiration())) {
return true
} else if ((this.createdAt < daysUntilExpiration()) && (this.updatedAt == undefined)) {
return true
} else {
return false;
}
} else {
return false;
}
}
|
UI.registerHelper("getPrettyDateAndTime", function(timestamp) {
if(timestamp)
return moment(timestamp).format('M/D/YY h:mm:ss A');
});
UI.registerHelper("getCurrentUserDisplayName", function() {
return getUserName(Meteor.user());
});
Template.expiredAlert.expired = function() {
if (this.userId == Meteor.userId()) {
if (this.createdAt < daysUntilExpiration() && this.updatedAt < daysUntilExpiration()) {
return true
} else if (this.createdAt < daysUntilExpiration()) {
return true
} else {
return false;
}
} else {
return false;
}
}
|
Enable Heroku wrapper to read config vars using '.'
|
<?php
/**
* Created by IntelliJ IDEA.
* User: luzifer
* Date: 26.04.14
* Time: 14:16
*/
class HerokuConfigStore implements IConfigReader {
/**
* @var IConfigReader
*/
private $origin_reader = null;
/**
* @param IConfigReader $config_reader Filesystem config reader
*/
public function __construct($config_reader) {
$this->origin_reader = $config_reader;
}
public function get($config_key, $default = null) {
$secure_key = str_replace('.', '_', $config_key);
if(array_key_exists($secure_key, $_ENV)) {
return $_ENV[$secure_key];
} else {
return $this->origin_reader->get($config_key, $default);
}
}
public function getSection($config_section_name) {
$this->origin_reader->getSection($config_section_name);
}
public function set($config_key, $config_value) {
if(array_key_exists($config_key, $_ENV)) {
throw new HerokuConfigStoreException($config_key . ' is a variable from the read-only-storage at Heroku');
} else {
$this->origin_reader->set($config_key, $config_value);
}
}
}
class HerokuConfigStoreException extends Exception {}
|
<?php
/**
* Created by IntelliJ IDEA.
* User: luzifer
* Date: 26.04.14
* Time: 14:16
*/
class HerokuConfigStore implements IConfigReader {
/**
* @var IConfigReader
*/
private $origin_reader = null;
/**
* @param IConfigReader $config_reader Filesystem config reader
*/
public function __construct($config_reader) {
$this->origin_reader = $config_reader;
}
public function get($config_key, $default = null) {
if(array_key_exists($config_key, $_ENV)) {
return $_ENV[$config_key];
} else {
return $this->origin_reader->get($config_key, $default);
}
}
public function getSection($config_section_name) {
$this->origin_reader->getSection($config_section_name);
}
public function set($config_key, $config_value) {
if(array_key_exists($config_key, $_ENV)) {
throw new HerokuConfigStoreException($config_key . ' is a variable from the read-only-storage at Heroku');
} else {
$this->origin_reader->set($config_key, $config_value);
}
}
}
class HerokuConfigStoreException extends Exception {}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.