text
stringlengths 16
4.96k
| positive
stringlengths 321
2.24k
| negative
stringlengths 310
2.21k
|
|---|---|---|
Use full path for eslint-config-airbnb
|
'use strict'
const _ = require('lodash')
const extendConfig = require('../lib/extendConfig')
const mainRules = require('./main')
const eslintConfigAirbnb = extendConfig({
extends: 'eslint-config-airbnb'
})
const migratedRules = {}
const migrateRuleNames = [
'array-bracket-spacing',
'arrow-parens',
'generator-star-spacing',
'new-cap',
'object-curly-spacing',
'object-shorthand'
]
for (const migrateRuleName of migrateRuleNames) {
migratedRules[migrateRuleName] = 'off'
let migratedRuleVal = mainRules.rules[migrateRuleName]
if (migratedRuleVal === undefined) {
migratedRuleVal = eslintConfigAirbnb.rules[migrateRuleName]
}
migratedRules[`babel/${migrateRuleName}`] = migratedRuleVal
}
module.exports = {
parser: 'babel-eslint',
plugins: [
'babel'
],
rules: _.merge(migratedRules, {
'babel/flow-object-type': 'off',
'babel/func-params-comma-dangle': ['error', 'never'],
'babel/no-await-in-loop': 'off'
})
}
|
'use strict'
const _ = require('lodash')
const extendConfig = require('../lib/extendConfig')
const mainRules = require('./main')
const eslintConfigAirbnb = extendConfig({
extends: 'airbnb'
})
const migratedRules = {}
const migrateRuleNames = [
'array-bracket-spacing',
'arrow-parens',
'generator-star-spacing',
'new-cap',
'object-curly-spacing',
'object-shorthand'
]
for (const migrateRuleName of migrateRuleNames) {
migratedRules[migrateRuleName] = 'off'
let migratedRuleVal = mainRules.rules[migrateRuleName]
if (migratedRuleVal === undefined) {
migratedRuleVal = eslintConfigAirbnb.rules[migrateRuleName]
}
migratedRules[`babel/${migrateRuleName}`] = migratedRuleVal
}
module.exports = {
parser: 'babel-eslint',
plugins: [
'babel'
],
rules: _.merge(migratedRules, {
'babel/flow-object-type': 'off',
'babel/func-params-comma-dangle': ['error', 'never'],
'babel/no-await-in-loop': 'off'
})
}
|
Fix NPE for mispelled/missing directories in type-ahead file lookup
|
package water.api;
import java.io.File;
import com.google.gson.*;
public class TypeaheadFileRequest extends TypeaheadRequest {
public TypeaheadFileRequest() {
super("Provides a simple JSON array of filtered local files.","");
}
@Override
protected JsonArray serve(String filter, int limit) {
File base = null;
String filterPrefix = "";
if( !filter.isEmpty() ) {
File file = new File(filter);
if( file.isDirectory() ) {
base = file;
} else {
base = file.getParentFile();
filterPrefix = file.getName().toLowerCase();
}
}
if( base == null ) base = new File(".");
JsonArray array = new JsonArray();
File[] files = base.listFiles();
if( files == null ) return array;
for( File file : files ) {
if( file.isHidden() ) continue;
if( file.getName().toLowerCase().startsWith(filterPrefix) )
array.add(new JsonPrimitive(file.getPath()));
if( array.size() == limit) break;
}
return array;
}
}
|
package water.api;
import java.io.File;
import com.google.gson.*;
public class TypeaheadFileRequest extends TypeaheadRequest {
public TypeaheadFileRequest() {
super("Provides a simple JSON array of filtered local files.","");
}
@Override
protected JsonArray serve(String filter, int limit) {
File base = null;
String filterPrefix = "";
if( !filter.isEmpty() ) {
File file = new File(filter);
if( file.isDirectory() ) {
base = file;
} else {
base = file.getParentFile();
filterPrefix = file.getName().toLowerCase();
}
}
if( base == null ) base = new File(".");
JsonArray array = new JsonArray();
for( File file : base.listFiles() ) {
if( file.isHidden() ) continue;
if( file.getName().toLowerCase().startsWith(filterPrefix) ) {
String s = file.getPath();
array.add(new JsonPrimitive(s));
}
if( array.size() == limit) break;
}
return array;
}
}
|
Fix Dir resolver test to succeed with multiple CPUs
Fixes this problem:
$ go test -cpu=1,2 ./...
...
--- FAIL: TestResolve (0.00 seconds)
panic: chdir ../../testdata: no such file or directory [recovered]
See https://blog.splice.com/lesser-known-features-go-test/
|
package dir_test
import (
"os"
"path"
"testing"
"github.com/mlafeldt/chef-runner/resolver/dir"
"github.com/mlafeldt/chef-runner/util"
"github.com/stretchr/testify/assert"
)
func TestResolve(t *testing.T) {
util.InDir("../../testdata", func() {
cookbookPath := "test-cookbooks"
defer os.RemoveAll(cookbookPath)
assert.NoError(t, dir.Resolver{}.Resolve(cookbookPath))
expectFiles := []string{
"practicingruby/README.md",
"practicingruby/attributes",
"practicingruby/metadata.rb",
"practicingruby/recipes",
}
for _, f := range expectFiles {
assert.True(t, util.FileExist(path.Join(cookbookPath, f)))
}
})
}
|
package dir_test
import (
"os"
"path"
"testing"
"github.com/mlafeldt/chef-runner/resolver/dir"
"github.com/mlafeldt/chef-runner/util"
"github.com/stretchr/testify/assert"
)
const CookbookPath = "test-cookbooks"
func TestResolve(t *testing.T) {
if err := os.Chdir("../../testdata"); err != nil {
panic(err)
}
defer os.RemoveAll(CookbookPath)
assert.NoError(t, dir.Resolver{}.Resolve(CookbookPath))
expectFiles := []string{
"practicingruby/README.md",
"practicingruby/attributes",
"practicingruby/metadata.rb",
"practicingruby/recipes",
}
for _, f := range expectFiles {
assert.True(t, util.FileExist(path.Join(CookbookPath, f)))
}
}
|
Fix updating to github gist
|
Template.viewGist.helpers({
description: function () {
return JSON.parse(this.content).description
},
files: function () {
return Object.keys(JSON.parse(this.content).files)
.map(filename => Object.assign(
JSON.parse(this.content).files[filename],
{ gistId: this._id }
))
}
})
Template.viewGist.events({
'submit form': function(event) {
event.preventDefault()
const updateContent = {
files: {}
}
updateContent.files[this.filename] = { content: event.target.gist.value }
const url = 'https://api.github.com/gists/' + this.gistId
const opts = {
method: 'PATCH',
headers: { Authorization: 'token ' + Meteor.user().services.github.accessToken },
body: JSON.stringify(updateContent)
}
fetch(url, opts).then(res => console.log('success'))
.catch(console.error)
}
})
|
Template.viewGist.helpers({
description: function () {
return JSON.parse(this.content).description
},
files: function () {
console.log(JSON.parse(this.content).files)
const array = Object.keys(JSON.parse(this.content).files).map(filename => JSON.parse(this.content).files[filename])
return array
}
})
Template.viewGist.events({
'submit form': function(event) {
event.preventDefault()
const updateContent = {
files: {}
}
updateContent.files[this.filename] = { content: event.target.gist.value }
const url = 'https://api.github.com/gists/' + this.gistId
const opts = {
method: 'PATCH',
headers: { Authorization: 'token ' + Meteor.user().services.github.accessToken },
body: JSON.stringify(updateContent)
}
fetch(url, opts).then(res => console.log('success'))
.catch(console.error)
}
})
|
Add a slash after port number
|
<?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->publicPath());
$host = $this->input->getOption('host');
$port = $this->input->getOption('port');
$base = $this->laravel->basePath();
$this->info("Laravel development server started on http://{$host}:{$port}/");
passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} \"{$base}\"/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->publicPath());
$host = $this->input->getOption('host');
$port = $this->input->getOption('port');
$base = $this->laravel->basePath();
$this->info("Laravel development server started on http://{$host}:{$port}");
passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} \"{$base}\"/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),
);
}
}
|
Use double quotes for strings
|
# -*- coding: utf-8 -*-
import django
DEBUG = False
USE_TZ = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
INSTALLED_APPS = [
"easy_pjax",
"tests"
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = "tests.urls"
SECRET_KEY = "secret"
if django.VERSION[:2] >= (1, 8):
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"APP_DIRS": True,
"OPTIONS": {
"builtins": ["easy_pjax.templatetags.pjax_tags"],
"context_processors": ["django.template.context_processors.request"]
}
}
]
else:
TEMPLATE_CONTEXT_PROCESSORS = ["django.core.context_processors.request"]
|
# -*- coding: utf-8 -*-
import django
DEBUG = False
USE_TZ = True
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
}
}
INSTALLED_APPS = [
"easy_pjax",
"tests"
]
MIDDLEWARE_CLASSES = []
ROOT_URLCONF = "tests.urls"
SECRET_KEY = "secret"
if django.VERSION[:2] >= (1, 8):
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'APP_DIRS': True,
'OPTIONS': {
'builtins': ["easy_pjax.templatetags.pjax_tags"],
'context_processors': ["django.template.context_processors.request"]
}
}
]
else:
TEMPLATE_CONTEXT_PROCESSORS = ["django.core.context_processors.request"]
|
Switch to PEP 440 compliant version string and bump to 0.6.7.dev0.
|
import platform
import sys
__version__ = "0.6.7.dev0"
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import version as twisted_version
from twisted.web import version as twisted_web_version
from twisted.python.versions import Version
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
"Please install them.\n")
raise
try:
if twisted_version < Version("twisted", 2, 5, 0):
raise ImportError("Twisted >= 2.5 is required. Please install it.")
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
for arg in exc.args:
sys.stderr.write("%s\n" % arg)
raise
|
import platform
import sys
__version_info__ = (0, 6, 7)
__version__ = '.'.join(map(str, __version_info__))
SERVER_ID = ','.join([platform.system(),
platform.release(),
'UPnP/1.0,Coherence UPnP framework',
__version__])
try:
from twisted import version as twisted_version
from twisted.web import version as twisted_web_version
from twisted.python.versions import Version
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
sys.stderr.write("Twisted >= 2.5 and Twisted.Web >= 2.5 are required. " \
"Please install them.\n")
raise
try:
if twisted_version < Version("twisted", 2, 5, 0):
raise ImportError("Twisted >= 2.5 is required. Please install it.")
except ImportError, exc:
# log error to stderr, might be useful for debugging purpose
for arg in exc.args:
sys.stderr.write("%s\n" % arg)
raise
|
Drop test database after run the test
|
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'lib/**/*.js',
'test/**/*.js'
]
},
bgShell: {
dropDatabase: {
cmd: 'mongo mwc_logs_test --eval "db.dropDatabase()"',
bg: false
}
},
mochacli: {
options: {
require: ['should'],
reporter: 'spec',
bail: true,
recursive: true,
timeout: '15s'
},
all: ['test/**/*.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-bg-shell');
grunt.registerTask('test', ['jshint', 'bgShell:dropDatabase', 'mochacli',
'bgShell:dropDatabase']);
};
|
module.exports = function (grunt) {
grunt.initConfig({
jshint: {
all: [
'Gruntfile.js',
'lib/**/*.js',
'test/**/*.js'
]
},
bgShell: {
dropDatabase: {
cmd: 'mongo mwc_logs_test --eval "db.dropDatabase()"',
bg: false
}
},
mochacli: {
options: {
require: ['should'],
reporter: 'spec',
bail: true,
recursive: true,
timeout: '15s'
},
all: ['test/**/*.js']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-mocha-cli');
grunt.loadNpmTasks('grunt-bg-shell');
grunt.registerTask('test', ['jshint', 'bgShell:dropDatabase', 'mochacli']);
};
|
Add integration test for db init
|
from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
from piper.cli.cli import CLIBase
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
clibase.assert_called_once_with(
'piper',
(build.ExecCLI, db.DbCLI),
args=self.mock
)
clibase.return_value.entry.assert_called_once_with()
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_return_value(self, clibase):
ret = cmd_piper.entry()
assert ret is clibase.return_value.entry.return_value
class TestEntryIntegration(object):
def test_db_init(self):
args = ['db', 'init']
cli = CLIBase('piper', (db.DbCLI,), args=args)
db.DbCLI.db = mock.Mock()
cli.entry()
db.DbCLI.db.init.assert_called_once_with(cli.config)
|
from piper import build
from piper.db import core as db
from piper.cli import cmd_piper
import mock
class TestEntry(object):
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_calls(self, clibase):
self.mock = mock.Mock()
cmd_piper.entry(self.mock)
clibase.assert_called_once_with(
'piper',
(build.ExecCLI, db.DbCLI),
args=self.mock
)
clibase.return_value.entry.assert_called_once_with()
@mock.patch('piper.cli.cmd_piper.CLIBase')
def test_return_value(self, clibase):
ret = cmd_piper.entry()
assert ret is clibase.return_value.entry.return_value
|
Use the url pathname so we don't include query args
|
var url = require('url')
exports.create = function(logger) {
return function(req, res, next) {
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Setup the key-value object of data to log and include some basic info
req.kvLog = {
date: req._rlStartTime.toISOString()
, method: req.method
, url: url.parse(req.originalUrl).pathname
, _rlLevel: 'info' // internal usage
, type: 'reqlog'
};
// Proxy the real end function
res.end = function(chunk, encoding) {
// Do the work expected
res.end = rEnd;
res.end(chunk, encoding);
// And do the work we want now (logging!)
// Save a few more variables that we can only get at the end
req.kvLog.status = res.statusCode;
req.kvLog.response_time = (new Date() - req._rlStartTime);
// Send the log off to winston
var level = req.kvLog._rlLevel
, msg = req.kvLog.message || '';
delete req.kvLog._rlLevel;
if (msg.length) {
delete req.kvLog.message;
}
logger.log(level, msg, req.kvLog);
};
next();
};
};
|
exports.create = function(logger) {
return function(req, res, next) {
var rEnd = res.end;
// To track response time
req._rlStartTime = new Date();
// Setup the key-value object of data to log and include some basic info
req.kvLog = {
date: req._rlStartTime.toISOString()
, method: req.method
, url: req.originalUrl
, _rlLevel: 'info' // internal usage
, type: 'reqlog'
};
// Proxy the real end function
res.end = function(chunk, encoding) {
// Do the work expected
res.end = rEnd;
res.end(chunk, encoding);
// And do the work we want now (logging!)
// Save a few more variables that we can only get at the end
req.kvLog.status = res.statusCode;
req.kvLog.response_time = (new Date() - req._rlStartTime);
// Send the log off to winston
var level = req.kvLog._rlLevel
, msg = req.kvLog.message || '';
delete req.kvLog._rlLevel;
if (msg.length) {
delete req.kvLog.message;
}
logger.log(level, msg, req.kvLog);
};
next();
};
};
|
Increase security loading the .env.testing file
|
<?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <support@blackfire.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Dotenv\Dotenv;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class LoadBlackfireEnvironmentVariables
{
/**
* Bootstrap the given application.
*
* @return void
*/
public function bootstrap(Application $app)
{
$request = Request::capture();
if (!($request->headers->has('X-BLACKFIRE-LARAVEL-TESTS') && $request->headers->has('X-BLACKFIRE-QUERY'))) {
return;
}
$dotenv = Dotenv::createImmutable(base_path(), '.env.testing');
$dotenv->load();
if (env('APP_ENV') !== 'testing') {
throw new \RuntimeException('The .env.testing file should contain APP_ENV=testing');
}
}
}
|
<?php
/*
* This file is part of the Blackfire SDK package.
*
* (c) Blackfire <support@blackfire.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Blackfire\Bridge\Laravel;
use Dotenv\Dotenv;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Http\Request;
class LoadBlackfireEnvironmentVariables
{
/**
* Bootstrap the given application.
*
* @return void
*/
public function bootstrap(Application $app)
{
$request = Request::capture();
if (!($request->headers->has('X-BLACKFIRE-LARAVEL-TESTS') && $request->headers->has('X-BLACKFIRE-QUERY'))) {
return;
}
$dotenv = Dotenv::createImmutable(base_path(), '.env.testing');
$dotenv->safeload();
}
}
|
Fix incorrect container layouts being used
#35 #36
|
package net.blay09.mods.trashslot.api;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.awt.Rectangle;
import java.util.List;
@SideOnly(Side.CLIENT)
public interface IGuiContainerLayout {
List<Rectangle> getCollisionAreas(GuiContainer gui);
List<Snap> getSnaps(GuiContainer gui, SlotRenderStyle renderStyle);
SlotRenderStyle getSlotRenderStyle(GuiContainer gui, int slotX, int slotY);
int getDefaultSlotX(GuiContainer gui);
int getDefaultSlotY(GuiContainer gui);
boolean isEnabledByDefault();
int getSlotOffsetX(GuiContainer gui, SlotRenderStyle renderStyle);
int getSlotOffsetY(GuiContainer gui, SlotRenderStyle renderStyle);
default String getContainerId(GuiContainer gui) {
return gui.getClass().getName().replace('.', '/');
}
}
|
package net.blay09.mods.trashslot.api;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.awt.Rectangle;
import java.util.List;
@SideOnly(Side.CLIENT)
public interface IGuiContainerLayout {
List<Rectangle> getCollisionAreas(GuiContainer gui);
List<Snap> getSnaps(GuiContainer gui, SlotRenderStyle renderStyle);
SlotRenderStyle getSlotRenderStyle(GuiContainer gui, int slotX, int slotY);
int getDefaultSlotX(GuiContainer gui);
int getDefaultSlotY(GuiContainer gui);
boolean isEnabledByDefault();
int getSlotOffsetX(GuiContainer gui, SlotRenderStyle renderStyle);
int getSlotOffsetY(GuiContainer gui, SlotRenderStyle renderStyle);
default String getContainerId(GuiContainer gui) {
return getClass().getName().replace('.', '/');
}
}
|
Disable fractal on empty config
|
<?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\LayerBuilder;
use Aztech\Phinject\Container;
use League\Fractal\Manager;
use Symfony\Component\HttpFoundation\Request;
use Aztech\Layers\Layer;
class FractalRenderingLayerBuilder implements LayerBuilder
{
private $container;
private $manager;
public function __construct(Container $container, Manager $manager)
{
$this->container = $container;
$this->manager = $manager;
}
/*
* (non-PHPdoc) @see \Aztech\LayerBuilder::buildLayer()
*/
public function buildLayer(Layer $nextLayer, array $arguments)
{
$arguments = array_values($arguments);
$transformerClass = isset($arguments[0]) ? $arguments[0] : '';
$isList = isset($arguments[1]) && $arguments[1] == true;
if (trim($transformerClass) == '') {
return $nextLayer;
}
return new FractalRenderingLayer($this->container, $this->manager, $nextLayer, $transformerClass, $isList);
}
}
|
<?php
namespace Aztech\Layers\Elements;
use Aztech\Layers\LayerBuilder;
use Aztech\Phinject\Container;
use League\Fractal\Manager;
use Symfony\Component\HttpFoundation\Request;
use Aztech\Layers\Layer;
class FractalRenderingLayerBuilder implements LayerBuilder
{
private $container;
private $manager;
public function __construct(Container $container, Manager $manager)
{
$this->container = $container;
$this->manager = $manager;
}
/*
* (non-PHPdoc) @see \Aztech\LayerBuilder::buildLayer()
*/
public function buildLayer(Layer $nextLayer, array $arguments)
{
$arguments = array_values($arguments);
$transformerClass = $arguments[0];
$isList = isset($arguments[1]) && $arguments[1] == true;
return new FractalRenderingLayer($this->container, $this->manager, $nextLayer, $transformerClass, $isList);
}
}
|
Update with reference to global nav partial
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var postcss = require('postcss')
var cssstats = require('cssstats')
var widths = require('tachyons-widths/package.json')
var widthsCss = fs.readFileSync('node_modules/tachyons-widths/tachyons-widths.min.css', 'utf8')
var widthsObj = cssstats(widthsCss)
var widthsSize = filesize(widthsObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_widths.css', 'utf8')
var navDocs = fs.readFileSync('./templates/nav_docs.html', 'utf8')
var template = fs.readFileSync('./templates/docs/widths/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
widthsVersion: widths.version,
widthsSize: widthsSize,
widthsObj:widthsObj,
srcCSS: srcCSS,
navDocs: navDocs
})
fs.writeFileSync('./docs/layout/widths/index.html', html)
|
var _ = require('lodash')
var fs = require('fs')
var gzip = require('gzip-size')
var filesize = require('filesize')
var postcss = require('postcss')
var cssstats = require('cssstats')
var tachyons = require('./package.json')
var widths = require('tachyons-widths/package.json')
var widthsCss = fs.readFileSync('node_modules/tachyons-widths/tachyons-widths.min.css', 'utf8')
var widthsObj = cssstats(widthsCss)
var widthsSize = filesize(widthsObj.gzipSize)
var srcCSS = fs.readFileSync('./src/_widths.css', 'utf8')
var template = fs.readFileSync('./templates/docs/widths/index.html', 'utf8')
var tpl = _.template(template)
var html = tpl({
widthsVersion: widths.version,
widthsSize: widthsSize,
widthsObj:widthsObj,
srcCSS: srcCSS
})
fs.writeFileSync('./docs/layout/widths/index.html', html)
|
tests: Fix typo in mock usage
The error was made evident by a newer mock version that no longer
swallowed the wrong assert as regular use of a spec-less mock.
|
from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('close')
close_mock.assert_called_once_with()
self.assertEqualResponse('OK')
def test_empty_request(self):
self.send_request('')
self.assertEqualResponse('ACK [5@0] {} No command given')
self.send_request(' ')
self.assertEqualResponse('ACK [5@0] {} No command given')
def test_kill(self):
self.send_request('kill')
self.assertEqualResponse(
'ACK [4@0] {kill} you don\'t have permission for "kill"')
def test_ping(self):
self.send_request('ping')
self.assertEqualResponse('OK')
|
from __future__ import absolute_import, unicode_literals
from mock import patch
from tests.mpd import protocol
class ConnectionHandlerTest(protocol.BaseTestCase):
def test_close_closes_the_client_connection(self):
with patch.object(self.session, 'close') as close_mock:
self.send_request('close')
close_mock.assertEqualResponsecalled_once_with()
self.assertEqualResponse('OK')
def test_empty_request(self):
self.send_request('')
self.assertEqualResponse('ACK [5@0] {} No command given')
self.send_request(' ')
self.assertEqualResponse('ACK [5@0] {} No command given')
def test_kill(self):
self.send_request('kill')
self.assertEqualResponse(
'ACK [4@0] {kill} you don\'t have permission for "kill"')
def test_ping(self):
self.send_request('ping')
self.assertEqualResponse('OK')
|
Disable react-in-jsx-scope ESLint rule because of Flareact
|
module.exports = {
extends: ['airbnb', 'plugin:prettier/recommended', 'prettier/react'],
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
rules: {
'jsx-a11y/href-no-hash': ['off'],
'react/react-in-jsx-scope': ['off'],
'react/jsx-filename-extension': ['warn', { extensions: ['.js', '.jsx'] }],
'max-len': [
'warn',
{
code: 80,
tabWidth: 2,
comments: 80,
ignoreComments: false,
ignoreTrailingComments: true,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
},
};
|
module.exports = {
extends: ['airbnb', 'plugin:prettier/recommended', 'prettier/react'],
env: {
browser: true,
commonjs: true,
es6: true,
jest: true,
node: true,
},
rules: {
'jsx-a11y/href-no-hash': ['off'],
'react/jsx-filename-extension': ['warn', { extensions: ['.js', '.jsx'] }],
'max-len': [
'warn',
{
code: 80,
tabWidth: 2,
comments: 80,
ignoreComments: false,
ignoreTrailingComments: true,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true,
},
],
},
};
|
Move matrix calcs from webglshadows
|
import { LightShadow } from './LightShadow.js';
import { _Math } from '../math/Math.js';
import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: SpotLightShadow,
isSpotLightShadow: true,
updateMatrices: function ( light, viewCamera, viewportIndex ) {
var camera = this.camera,
lookTarget = this._lookTarget,
lightPositionWorld = this._lightPositionWorld;
var fov = _Math.RAD2DEG * 2 * light.angle;
var aspect = this.mapSize.width / this.mapSize.height;
var far = light.distance || camera.far;
if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
camera.fov = fov;
camera.aspect = aspect;
camera.far = far;
camera.updateProjectionMatrix();
}
lightPositionWorld.setFromMatrixPosition( light.matrixWorld );
camera.position.copy( lightPositionWorld );
lookTarget.setFromMatrixPosition( light.target.matrixWorld );
camera.lookAt( lookTarget );
camera.updateMatrixWorld();
LightShadow.prototype.updateMatrices.call( this, light, viewCamera, viewportIndex );
}
} );
export { SpotLightShadow };
|
import { LightShadow } from './LightShadow.js';
import { _Math } from '../math/Math.js';
import { PerspectiveCamera } from '../cameras/PerspectiveCamera.js';
/**
* @author mrdoob / http://mrdoob.com/
*/
function SpotLightShadow() {
LightShadow.call( this, new PerspectiveCamera( 50, 1, 0.5, 500 ) );
}
SpotLightShadow.prototype = Object.assign( Object.create( LightShadow.prototype ), {
constructor: SpotLightShadow,
isSpotLightShadow: true,
update: function ( light ) {
var camera = this.camera;
var fov = _Math.RAD2DEG * 2 * light.angle;
var aspect = this.mapSize.width / this.mapSize.height;
var far = light.distance || camera.far;
if ( fov !== camera.fov || aspect !== camera.aspect || far !== camera.far ) {
camera.fov = fov;
camera.aspect = aspect;
camera.far = far;
camera.updateProjectionMatrix();
}
}
} );
export { SpotLightShadow };
|
feat: Merge prior order_to_card_order with order id
|
# importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
grouped = order_products_prior_df.groupby('order_id', as_index = False)
grouped_data = pd.DataFrame()
grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean)
def product_ids(group):
l = []
for e in group['product_id']:
l.append(str(e))
return ' '.join(l)
grouped_data['product_ids'] = grouped.apply(product_ids)
def add_to_cart_orders(group):
l = []
for e in group['add_to_cart_order']:
l.append(str(e))
return ' '.join(l)
grouped_data['add_to_cart_orders'] = grouped.apply(add_to_cart_orders)
print('First five rows of grouped_data:\n', grouped_data.head())
orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id')
print('First five rows of orders_prior_merged:\n', orders_prior_merged.head())
|
# importing modules/ libraries
import pandas as pd
import numpy as np
orders_prior_df = pd.read_csv('Data/orders_prior_sample.csv')
print('length of orders_prior_df:', len(orders_prior_df))
order_products_prior_df = pd.read_csv('Data/order_products_prior_sample.csv')
print('length of order_products_prior_df:', len(order_products_prior_df))
grouped = order_products_prior_df.groupby('order_id')
grouped_data = pd.DataFrame()
grouped_data['order_id'] = grouped['order_id'].aggregate(np.mean)
def product_ids(group):
l = []
ord_id = group['order_id']
for e in group['product_id']:
l.append(str(e))
return ' '.join(l)
grouped_data['product_ids'] = grouped.apply(product_ids)
print('length of grouped_data:', len(grouped_data))
orders_prior_merged = pd.merge(orders_prior_df, grouped_data, on='order_id')
print('length of orders_prior_merged:', len(orders_prior_merged))
|
Use PHPUnit's equality constraint for query assertion
|
<?php
namespace Helmich\MongoMock\Assert;
use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;
class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{
/** @var array */
private $filter;
/** @var array */
private $options;
public function __construct($filter, $options = [])
{
parent::__construct();
$this->filter = $filter;
$this->options = $options;
}
protected function matches($other)
{
if (!$other instanceof MockCollection) {
return false;
}
$constraint = \PHPUnit_Framework_Assert::equalTo(new Query($this->filter, $this->options));
foreach ($other->queries as $query) {
if ($constraint->evaluate($query, '', true)) {
return true;
}
}
return false;
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'executed query by ' . json_encode($this->filter);
}
}
|
<?php
namespace Helmich\MongoMock\Assert;
use Helmich\MongoMock\MockCollection;
use Helmich\MongoMock\Query;
class QueryWasExecutedConstraint extends \PHPUnit_Framework_Constraint
{
/** @var array */
private $filter;
/** @var array */
private $options;
public function __construct($filter, $options = [])
{
parent::__construct();
$this->filter = $filter;
$this->options = $options;
}
protected function matches($other)
{
if (!$other instanceof MockCollection) {
return false;
}
$ref = new Query($this->filter, $this->options);
foreach ($other->queries as $query) {
if ($query == $ref) {
return true;
}
}
return false;
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'executed query by ' . json_encode($this->filter);
}
}
|
Remove BaseMail dependency on User object
|
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, email_address, async_mail=None):
self.email_address = email_address
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.email_address])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
|
from django.core.mail import EmailMultiAlternatives
from django.template import Context, Template
from django.template.loader import get_template
from django.conf import settings
import threading
class EmailThread(threading.Thread):
def __init__(self, msg):
self.msg = msg
threading.Thread.__init__(self)
def run (self):
return self.msg.send() > 0
class BaseMail:
"""
This class is responsible for firing emails
"""
from_email = ''
def __init__(self, user, async_mail=None):
self.user = user
self.async_mail = async_mail
def sendEmail(self, template_name, subject, context):
ctx = Context(context)
text_content = get_template('email/{}.txt'.format(template_name)).render(ctx)
html_content = get_template('email/{}.html'.format(template_name)).render(ctx)
msg = EmailMultiAlternatives(subject, text_content, self.from_email, [self.user.email])
msg.attach_alternative(text_content, "text/plain")
msg.attach_alternative(html_content, "text/html")
if self.async_mail:
async_flag="async"
else:
async_flag=getattr(settings, "DEFAULT_SEND_EMAIL", "async")
if async_flag == "async":
t = EmailThread(msg)
t.start()
return t
else:
return msg.send() > 0
|
Remove this merge as numpy shouldn't be a dependency
|
# -*- coding: utf-8 -*-
"""
twython.compat
~~~~~~~~~~~~~~
This module contains imports and declarations for seamless Python 2 and
Python 3 compatibility.
"""
import sys
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except ImportError:
import json
if is_py2:
from urllib import urlencode, quote_plus
from urlparse import parse_qsl, urlsplit
str = unicode
basestring = basestring
numeric_types = (int, long, float)
elif is_py3:
from urllib.parse import urlencode, quote_plus, parse_qsl, urlsplit
str = str
basestring = (str, bytes)
numeric_types = (int, float)
|
# -*- coding: utf-8 -*-
"""
twython.compat
~~~~~~~~~~~~~~
This module contains imports and declarations for seamless Python 2 and
Python 3 compatibility.
"""
import sys
import numpy as np
_ver = sys.version_info
#: Python 2.x?
is_py2 = (_ver[0] == 2)
#: Python 3.x?
is_py3 = (_ver[0] == 3)
try:
import simplejson as json
except ImportError:
import json
if is_py2:
from urllib import urlencode, quote_plus
from urlparse import parse_qsl, urlsplit
str = unicode
basestring = basestring
numeric_types = (int, long, float, np.int64, np.float64)
elif is_py3:
from urllib.parse import urlencode, quote_plus, parse_qsl, urlsplit
str = str
basestring = (str, bytes)
numeric_types = (int, float, np.int64, np.float64)
|
Enable the correct exception check on the test, was disabled when inspecting the contents of the exception
|
package net.stickycode.configured.finder;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
public abstract class AbstractBeanFinderTest {
protected abstract BeanFinder getFinder();
@Test
public void lookupPrototype() {
Bean bean = getFinder().find(Bean.class);
assertThat(bean).isNotNull();
Bean bean2 = getFinder().find(Bean.class);
assertThat(bean).isNotSameAs(bean2);
}
@Test
public void lookupSingleton() {
BeanFinder finder = getFinder();
SingletonBean bean = finder.find(SingletonBean.class);
assertThat(bean).isNotNull();
SingletonBean bean2 = finder.find(SingletonBean.class);
assertThat(bean).isSameAs(bean2);
}
@Test(expected = BeanNotFoundException.class)
public void notFound() {
getFinder().find(getClass());
}
@Test(expected = BeanNotFoundException.class)
public void tooMany() {
getFinder().find(TooMany.class);
}
}
|
package net.stickycode.configured.finder;
import static org.fest.assertions.Assertions.assertThat;
import org.junit.Test;
public abstract class AbstractBeanFinderTest {
protected abstract BeanFinder getFinder();
@Test
public void lookupPrototype() {
Bean bean = getFinder().find(Bean.class);
assertThat(bean).isNotNull();
Bean bean2 = getFinder().find(Bean.class);
assertThat(bean).isNotSameAs(bean2);
}
@Test
public void lookupSingleton() {
BeanFinder finder = getFinder();
SingletonBean bean = finder.find(SingletonBean.class);
assertThat(bean).isNotNull();
SingletonBean bean2 = finder.find(SingletonBean.class);
assertThat(bean).isSameAs(bean2);
}
@Test(expected = BeanNotFoundException.class)
public void notFound() {
getFinder().find(getClass());
}
@Test
// (expected = BeanNotFoundException.class)
public void tooMany() {
getFinder().find(TooMany.class);
}
}
|
Set up argparse to accept params and display usage
|
"""Perform static analysis on a Swift source file."""
import argparse
import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListener
from tailor.output.printer import Printer
from tailor.swift.swiftlexer import SwiftLexer
from tailor.swift.swiftparser import SwiftParser
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('infile', type=os.path.abspath,
help='Swift source file')
parser.add_argument('-l', '--max-lines', type=int, default=0,
help='maximum file line length')
return parser.parse_args()
def main():
args = parse_args()
printer = Printer(filepath=args.infile)
lexer = SwiftLexer(FileStream(args.infile))
stream = CommonTokenStream(lexer)
parser = SwiftParser(stream)
tree = parser.topLevel()
listener = MainListener(printer)
walker = ParseTreeWalker()
walker.walk(listener, tree)
if __name__ == '__main__':
main()
|
import os
import sys
PARENT_PATH = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')
sys.path.append(PARENT_PATH)
from antlr4 import FileStream, CommonTokenStream, ParseTreeWalker
from tailor.listeners.mainlistener import MainListener
from tailor.output.printer import Printer
from tailor.swift.swiftlexer import SwiftLexer
from tailor.swift.swiftparser import SwiftParser
def main(argv):
infile = FileStream(argv[1])
printer = Printer(filepath=argv[1])
lexer = SwiftLexer(infile)
stream = CommonTokenStream(lexer)
parser = SwiftParser(stream)
tree = parser.topLevel()
listener = MainListener(printer)
walker = ParseTreeWalker()
walker.walk(listener, tree)
if __name__ == '__main__':
main(sys.argv)
|
Create a new string, instead of modifying the `template`
|
import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Description Found'
if strip_html:
string = strip_html_tags(string)
if markdown:
string = text_maker.handle(string)
return string
def get_formatted_book_data(book_data):
template = textwrap.dedent("""\
*Title:* {0} by {1}
*Rating:* {2} by {3} users
*Description:* {4}
*Link*: [click me]({5})
Tip: {6}""")
title = book_data['title']
authors = book_data['authors']
average_rating = book_data['average_rating']
ratings_count = book_data['ratings_count']
description = html_to_md(book_data.get('description', ''))
url = book_data['url']
tip = 'Use author name also for better search results'
response = template.format(title, authors, average_rating, ratings_count,
description, url, tip)
return response
|
import re
import textwrap
import html2text
text_maker = html2text.HTML2Text()
text_maker.body_width = 0
def strip_html_tags(text):
text = re.sub(r'<a.*?</a>', '', text)
return re.sub('<[^<]+?>', '', text)
def html_to_md(string, strip_html=True, markdown=False):
if not string:
return 'No Description Found'
if strip_html:
string = strip_html_tags(string)
if markdown:
string = text_maker.handle(string)
return string
def get_formatted_book_data(book_data):
template = textwrap.dedent("""\
*Title:* {0} by {1}
*Rating:* {2} by {3} users
*Description:* {4}
*Link*: [click me]({5})
Tip: {6}""")
title = book_data['title']
authors = book_data['authors']
average_rating = book_data['average_rating']
ratings_count = book_data['ratings_count']
description = html_to_md(book_data.get('description', ''))
url = book_data['url']
tip = 'Use author name also for better search results'
template = template.format(title, authors, average_rating, ratings_count,
description, url, tip)
return template
|
Remove page, add offset and limit to filtered filters
|
import React, { Component } from 'react'
import { isArray, forEach } from 'lodash'
import qs from 'qs'
import Datasets from './Datasets'
const DISABLED_FILTERS = [ 'q', 'offset', 'limit' ]
export function _extractFilters(query) {
let filters = []
forEach(query, function(value, key) {
if (DISABLED_FILTERS.includes(key)) {
return
}
if (isArray(value)) {
forEach(value, function(current) {
filters.push({name: key, value: current})
})
} else {
filters.push({name: key, value})
}
})
return filters
}
export function parseQuery(query) {
const parse = qs.parse(query)
return {
textInput: parse.q,
page: parse.page,
filters: _extractFilters(parse),
}
}
class WrappedDatasets extends Component {
constructor(props) {
super(props)
this.state = { query: parseQuery(this.props.location.query) }
}
render() {
return <Datasets query={this.state.query}/>
}
}
export default WrappedDatasets
|
import React, { Component } from 'react'
import { isArray, forEach } from 'lodash'
import qs from 'qs'
import Datasets from './Datasets'
const DISABLED_FILTERS = ['q', 'page', ]
export function _extractFilters(query) {
let filters = []
forEach(query, function(value, key) {
if (DISABLED_FILTERS.includes(key)) {
return
}
if (isArray(value)) {
forEach(value, function(current) {
filters.push({name: key, value: current})
})
} else {
filters.push({name: key, value})
}
})
return filters
}
export function parseQuery(query) {
const parse = qs.parse(query)
return {
textInput: parse.q,
page: parse.page,
filters: _extractFilters(parse),
}
}
class WrappedDatasets extends Component {
constructor(props) {
super(props)
this.state = { query: parseQuery(this.props.location.query) }
}
render() {
return <Datasets query={this.state.query}/>
}
}
export default WrappedDatasets
|
Add script, style, meta and link filters.
|
<?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Html View Class
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @package Nooku_Server
* @subpackage Articles
*/
class ComApplicationViewHtml extends KViewHtml
{
protected function _initialize(KConfig $config)
{
$config->append(array(
'auto_assign' => false,
'template_filters' => array('script', 'style', 'link', 'meta'),
));
parent::_initialize($config);
}
public function display()
{
//Set the language information
$this->language = JFactory::getLanguage()->getTag();
$this->direction = JFactory::getLanguage()->isRTL() ? 'rtl' : 'ltr';
return parent::display();
}
}
|
<?php
/**
* @version $Id$
* @package Nooku_Server
* @subpackage Articles
* @copyright Copyright (C) 2011 - 2012 Timble CVBA and Contributors. (http://www.timble.net).
* @license GNU GPLv3 <http://www.gnu.org/licenses/gpl.html>
* @link http://www.nooku.org
*/
/**
* Html View Class
*
* @author Johan Janssens <http://nooku.assembla.com/profile/johanjanssens>
* @package Nooku_Server
* @subpackage Articles
*/
class ComApplicationViewHtml extends KViewHtml
{
protected function _initialize(KConfig $config)
{
$config->append(array(
'auto_assign' => false,
));
parent::_initialize($config);
}
public function display()
{
//Set the language information
$this->language = JFactory::getLanguage()->getTag();
$this->direction = JFactory::getLanguage()->isRTL() ? 'rtl' : 'ltr';
return parent::display();
}
}
|
Remove error handling and useless winston
|
var amqp = require('amqplib');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
_connection.on('close', reconnect);
_connection.on('error', reconnect);
intervalID = clearInterval(intervalID);
return _connection.createChannel()
.then(function (_channel) {
return _channel;
});
});
}
function reconnect() {
if (!intervalID) {
intervalID = setInterval(connect, 1000);
}
}
function disconnect() {
if (amqpConnection) {
amqpConnection.close();
}
}
module.exports = function () {
return {
connect: connect,
reconnect: reconnect,
disconnect: disconnect
};
};
|
var amqp = require('amqplib');
var winston = require('winston');
var amqpUrl, amqpConnection, intervalID;
function connect(_amqpUrl) {
amqpUrl = amqpUrl || _amqpUrl || process.env.AMQP_URL || 'amqp://localhost';
return amqp.connect(amqpUrl)
.then(function (_connection) {
amqpConnection = _connection;
_connection.on('close', reconnect);
_connection.on('error', reconnect);
intervalID = clearInterval(intervalID);
return _connection.createChannel()
.then(function (_channel) {
return _channel;
});
}).catch(function (err) {
winston.error(err);
reconnect();
});
}
function reconnect() {
if (!intervalID) {
intervalID = setInterval(connect, 1000);
}
}
function disconnect() {
if (amqpConnection) {
amqpConnection.close();
}
}
module.exports = function () {
return {
connect: connect,
reconnect: reconnect,
disconnect: disconnect
};
};
|
Switch from deprecated ActionBarActivity to AppCompatActivity
|
package io.github.hidroh.materialistic;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.analytics.GoogleAnalytics;
public abstract class TrackableActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Preferences.darkThemeEnabled(this)) {
setTheme(R.style.AppTheme_Dark);
}
getTheme().applyStyle(Preferences.resolveTextSizeResId(this), true);
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
@Override
protected void onStop() {
GoogleAnalytics.getInstance(this).reportActivityStop(this);
super.onStop();
}
}
|
package io.github.hidroh.materialistic;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import com.google.android.gms.analytics.GoogleAnalytics;
public abstract class TrackableActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
if (Preferences.darkThemeEnabled(this)) {
setTheme(R.style.AppTheme_Dark);
}
getTheme().applyStyle(Preferences.resolveTextSizeResId(this), true);
super.onCreate(savedInstanceState);
}
@Override
protected void onStart() {
super.onStart();
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
@Override
protected void onStop() {
GoogleAnalytics.getInstance(this).reportActivityStop(this);
super.onStop();
}
}
|
Fix sources protocol to HTTPS.
|
module.exports = function (grunt) {
return {
options: {
separator: Array(3).join(grunt.util.linefeed),
sourceRoot: process.env.CI ? 'https://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
},
all: {
files: {
'dist/<%= pkgName %>.js': [
'umd/header.js',
'src/shim.js',
'src/utils.js',
'src/core.js',
'src/proto/cache.js',
'src/proto/context.js',
'src/type.js',
'src/template.js',
'src/proto/as.js',
'src/proto/position.js',
'src/proto/props.js',
'src/typeSet/*.js',
'src/io/toURI.js',
'src/io/load.js',
'src/io/save.js',
'umd/footer.js'
]
}
}
};
};
|
module.exports = function (grunt) {
return {
options: {
separator: Array(3).join(grunt.util.linefeed),
sourceRoot: process.env.CI ? 'http://raw.github.com/' + process.env.TRAVIS_REPO_SLUG + '/' + process.env.TRAVIS_COMMIT : '../..'
},
all: {
files: {
'dist/<%= pkgName %>.js': [
'umd/header.js',
'src/shim.js',
'src/utils.js',
'src/core.js',
'src/proto/cache.js',
'src/proto/context.js',
'src/type.js',
'src/template.js',
'src/proto/as.js',
'src/proto/position.js',
'src/proto/props.js',
'src/typeSet/*.js',
'src/io/toURI.js',
'src/io/load.js',
'src/io/save.js',
'umd/footer.js'
]
}
}
};
};
|
Remove link to unused color palette
|
var $elements = {
game_over: document.getElementById('game_over'),
you_won: document.getElementById('you_won'),
};
var canvas = SVG('canvas').size(window.innerWidth-40, window.innerHeight-document.getElementById('canvas').offsetTop-20);
var board = new Board(canvas);
var stopwatch = new StopWatch({delay: 5, timer: document.getElementById('instructions')});
var level = 4;
var MAX_LEVEL = 9;
board.draw(level);
board.on('start', function() {
stopwatch.reset();
stopwatch.start();
});
board.on('done', function() {
stopwatch.stop();
document.getElementById("level"+level).classList.add("done");
if (level == MAX_LEVEL) {
$elements.you_won.classList.add("active");
} else {
level += 1;
setTimeout(function() {
board.draw(level);
}, 500);
}
});
board.on('fail', function() {
stopwatch.stop();
$elements.game_over.classList.add("active");
});
document.getElementById('start_over').addEventListener('click', function() {
location.reload();
});
document.getElementById('retry').addEventListener('click', function() {
$elements.game_over.classList.remove("active");
board.draw(level);
});
document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });
|
// http://www.colourlovers.com/palette/3459622/Flowering_Tiles
var $elements = {
game_over: document.getElementById('game_over'),
you_won: document.getElementById('you_won'),
};
var canvas = SVG('canvas').size(window.innerWidth-40, window.innerHeight-document.getElementById('canvas').offsetTop-20);
var board = new Board(canvas);
var stopwatch = new StopWatch({delay: 5, timer: document.getElementById('instructions')});
var level = 4;
var MAX_LEVEL = 9;
board.draw(level);
board.on('start', function() {
stopwatch.reset();
stopwatch.start();
});
board.on('done', function() {
stopwatch.stop();
document.getElementById("level"+level).classList.add("done");
if (level == MAX_LEVEL) {
$elements.you_won.classList.add("active");
} else {
level += 1;
setTimeout(function() {
board.draw(level);
}, 500);
}
});
board.on('fail', function() {
stopwatch.stop();
$elements.game_over.classList.add("active");
});
document.getElementById('start_over').addEventListener('click', function() {
location.reload();
});
document.getElementById('retry').addEventListener('click', function() {
$elements.game_over.classList.remove("active");
board.draw(level);
});
document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });
|
Rename Promise var to avoid conflict with native promise
|
var base = require('42-cent-base');
var util = require('util');
var P = require('bluebird');
function GatewayMock(options) {
base.BaseGateway.call(this);
this.options = options;
}
util.inherits(GatewayMock, base.BaseGateway);
GatewayMock.prototype.submitTransaction = function (order, cc, prospect, other) {
var self = this;
return GatewayMock.resolveValue ? P.resolve(GatewayMock.resolveValue).then(function (val) {
GatewayMock.resolveValue = null;
return val;
}) : P.reject(GatewayMock.rejectValue || new Error('mock has no resolve value')).then(function (val) {
GatewayMock.rejectValue = null;
return val;
});
};
GatewayMock.resolveWith = function resolveWith(val) {
GatewayMock.resolveValue = val;
};
GatewayMock.rejectWith = function rejectValue(val) {
GatewayMock.rejectValue = val;
};
module.exports = {
factory: function (opt) {
return new GatewayMock(opt);
},
GatewayMock: GatewayMock
};
|
var base = require('42-cent-base');
var util = require('util');
var Promise = require('bluebird');
function GatewayMock(options) {
base.BaseGateway.call(this);
this.options = options;
}
util.inherits(GatewayMock, base.BaseGateway);
GatewayMock.prototype.submitTransaction = function (order, cc, prospect, other) {
var self = this;
return GatewayMock.resolveValue ? Promise.resolve(GatewayMock.resolveValue).then(function (val) {
GatewayMock.resolveValue = null;
return val;
}) : Promise.reject(GatewayMock.rejectValue || new Error('mock has no resolve value')).then(function (val) {
GatewayMock.rejectValue = null;
return val;
});
};
GatewayMock.resolveWith = function resolveWith(val) {
GatewayMock.resolveValue = val;
};
GatewayMock.rejectWith = function rejectValue(val) {
GatewayMock.rejectValue = val;
};
module.exports = {
factory: function (opt) {
return new GatewayMock(opt);
},
GatewayMock: GatewayMock
};
|
Add user activated Nova filter name
|
<?php
namespace OpenDominion\Nova\Filters;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;
class UserActivated extends Filter
{
/**
* The displayable name of the action.
*
* @var string
*/
public $name = 'Activated';
/**
* Apply the filter to the given query.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->where('activated', $value);
}
/**
* Get the filter's available options.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function options(Request $request)
{
return [
'Active' => 1,
'Inactive' => 0,
];
}
}
|
<?php
namespace OpenDominion\Nova\Filters;
use Illuminate\Http\Request;
use Laravel\Nova\Filters\Filter;
class UserActivated extends Filter
{
/**
* Apply the filter to the given query.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @param mixed $value
* @return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->where('activated', $value);
}
/**
* Get the filter's available options.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function options(Request $request)
{
return [
'Active' => 1,
'Inactive' => 0,
];
}
}
|
Use new copy API (db, aws, callback)
The couch-to-s3 api was refactored, so we adjust.
|
#!/usr/bin/env node
var nconf = require('nconf');
var toS3 = require('couch-to-s3');
var cred = require('./lib/cred.js');
nconf.file('dev', 'config-dev.json').argv().env().file('config.json');
nconf.defaults({
"dbUrl": "http://localhost:5984",
"dbName": "database",
"s3BucketName": "bucket",
"awsCredentialsPath": ".aws/credentials"
});
var awsCred = cred(nconf.get('awsCredentialsPath'));
var db = {
url: nconf.get('dbUrl'),
name: nconf.get('dbName')
};
var aws = {
accessKeyId: awsCred.aws_access_key_id,
secretAccessKey: awsCred.aws_secret_access_key,
bucket: nconf.get('s3BucketName')
};
toS3(db, aws, function (err, body) {
if (err) {
console.log("FAILURE");
console.log(err.message);
console.log(err.error);
return;
}
console.log("SUCCESS");
console.log(body.response.headers);
});
|
#!/usr/bin/env node
var nconf = require('nconf');
var toS3 = require('couch-to-s3');
var cred = require('./lib/cred.js');
nconf.file('dev', 'config-dev.json').argv().env().file('config.json');
nconf.defaults({
"dbUrl": "http://localhost:5984",
"dbName": "database",
"s3BucketName": "bucket",
"awsCredentialsPath": ".aws/credentials"
});
var awsCred = cred(nconf.get('awsCredentialsPath'));
var options = {
db: {
url: nconf.get('dbUrl'),
name: nconf.get('dbName')
},
aws: {
accessKeyId: awsCred.aws_access_key_id,
secretAccessKey: awsCred.aws_secret_access_key,
bucket: nconf.get('s3BucketName')
}
};
toS3(options, function (err, body) {
if (err) {
console.log("FAILURE");
console.log(err.message);
console.log(err.error);
return;
}
console.log("SUCCESS");
console.log(body.response.headers);
});
|
Add logging for missing CELERY_BROKER_URL
|
from celery import Celery
class NewAcropolisCelery(Celery):
def init_app(self, app):
if not app.config['CELERY_BROKER_URL']:
app.logger.info('Celery broker URL not set')
return
super(NewAcropolisCelery, self).__init__(
app.import_name,
broker=app.config['CELERY_BROKER_URL'],
)
app.logger.info('Setting up celery: %s', app.config['CELERY_BROKER_URL'])
self.conf.update(app.config)
class ContextTask(self.Task):
def __call__(self, *args, **kwargs): # noqa
with app.app_context():
return self.run(*args, **kwargs)
self.Task = ContextTask
|
from celery import Celery
class NewAcropolisCelery(Celery):
def init_app(self, app):
super(NewAcropolisCelery, self).__init__(
app.import_name,
broker=app.config['CELERY_BROKER_URL'],
)
app.logger.info('Setting up celery: %s', app.config['CELERY_BROKER_URL'])
self.conf.update(app.config)
class ContextTask(self.Task):
def __call__(self, *args, **kwargs): # noqa
with app.app_context():
return self.run(*args, **kwargs)
self.Task = ContextTask
|
Fix mapping for codon keys for Tyrosine
|
# Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UAA, UAG, UGA | STOP
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UAU": "Tyrosine",
"UAC": "Tyrosine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
# Codon | Protein
# :--- | :---
# AUG | Methionine
# UUU, UUC | Phenylalanine
# UUA, UUG | Leucine
# UCU, UCC, UCA, UCG | Serine
# UAU, UAC | Tyrosine
# UGU, UGC | Cysteine
# UGG | Tryptophan
# UAA, UAG, UGA | STOP
CODON_TO_PROTEIN = {
"AUG": "Methionine",
"UUU": "Phenylalanine",
"UUC": "Phenylalanine",
"UUA": "Leucine",
"UUG": "Leucine",
"UCU": "Serine",
"UCC": "Serine",
"UCA": "Serine",
"UCG": "Serine",
"UGU": "Cysteine",
"UGC": "Cysteine",
"UGG": "Tryptophan",
"UAA": "STOP",
"UAG": "STOP",
"UGA": "STOP"
}
def proteins(strand):
return [CODON_TO_PROTEIN[strand]]
|
Check for nil file as well.
|
package main
// #include "types.h"
import "C"
import (
"fmt"
"github.com/amarburg/go-lazyquicktime"
)
//export MovInfo
func MovInfo(path *C.char) C.MovieInfo {
file, err := sourceFromCPath(path)
if file == nil || err != nil {
fmt.Printf("Error opening path: %s", err.Error())
return C.MovieInfo{}
}
qtInfo, err := lazyquicktime.LoadMovMetadata(file)
if err != nil {
fmt.Printf("Error getting metadata: %s", err.Error())
return C.MovieInfo{}
}
return qtInfoToMovieInfo(qtInfo)
}
func qtInfoToMovieInfo(qtInfo *lazyquicktime.LazyQuicktime) C.MovieInfo {
return C.MovieInfo{
duration: C.float(qtInfo.Duration()),
num_frames: C.int(qtInfo.NumFrames()),
valid: 1,
}
}
|
package main
// #include "types.h"
import "C"
import (
"fmt"
"github.com/amarburg/go-lazyquicktime"
)
//export MovInfo
func MovInfo(path *C.char) C.MovieInfo {
file, err := sourceFromCPath(path)
if err != nil {
fmt.Printf("Error opening path: %s", err.Error())
return C.MovieInfo{}
}
qtInfo, err := lazyquicktime.LoadMovMetadata(file)
if err != nil {
fmt.Printf("Error getting metadata: %s", err.Error())
return C.MovieInfo{}
}
return qtInfoToMovieInfo(qtInfo)
}
func qtInfoToMovieInfo(qtInfo *lazyquicktime.LazyQuicktime) C.MovieInfo {
return C.MovieInfo{
duration: C.float(qtInfo.Duration()),
num_frames: C.int(qtInfo.NumFrames()),
valid: 1,
}
}
|
Validate the schema when loading it.
|
"""The Pibstack.yaml parsing code."""
import yaml
from .schema import validate
class StackConfig(object):
"""The configuration for the stack."""
def __init__(self, path_to_repo):
self.services = {} # map service name to config dict
self.databases = {} # map database name to config dict
self.path_to_repo = path_to_repo
stack = path_to_repo / "Pibstack.yaml"
with stack.open() as f:
data = yaml.safe_load(f.read())
validate(data)
self.name = data["main"]["name"]
for service in [data["main"]] + data["requires"]:
name = service["name"]
if service["type"] == "service":
self.services[name] = service
elif service["type"] == "postgres":
self.databases[name] = service
else:
raise ValueError("Unknown type: " + service["type"])
|
"""The Pibstack.yaml parsing code."""
import yaml
class StackConfig(object):
"""The configuration for the stack."""
def __init__(self, path_to_repo):
self.services = {} # map service name to config dict
self.databases = {} # map database name to config dict
self.path_to_repo = path_to_repo
stack = path_to_repo / "Pibstack.yaml"
with stack.open() as f:
data = yaml.safe_load(f.read())
self.name = data["main"]["name"]
for service in [data["main"]] + data["requires"]:
name = service["name"]
if service["type"] == "service":
self.services[name] = service
elif service["type"] == "postgres":
self.databases[name] = service
else:
raise ValueError("Unknown type: " + service["type"])
|
Set block to air after picking up fluids
|
package mariculture.core.handlers;
import mariculture.core.Core;
import mariculture.core.blocks.base.BlockFluid;
import mariculture.core.items.ItemBuckets;
import net.minecraft.block.Block;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import cpw.mods.fml.common.eventhandler.Event.Result;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class BucketHandler {
@SubscribeEvent
public void onFillBucket(FillBucketEvent event) {
Block block = event.world.getBlock(event.target.blockX, event.target.blockY, event.target.blockZ);
if (block instanceof BlockFluid) if (event.current.getItem() == Items.bucket) {
ItemStack ret = ((ItemBuckets) Core.buckets).getBucket(block);
if (ret != null) {
event.world.setBlockToAir(event.target.blockX, event.target.blockY, event.target.blockZ);
event.result = ret;
event.setResult(Result.ALLOW);
}
}
}
}
|
package mariculture.core.handlers;
import mariculture.core.Core;
import mariculture.core.blocks.base.BlockFluid;
import mariculture.core.items.ItemBuckets;
import net.minecraft.block.Block;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraftforge.event.entity.player.FillBucketEvent;
import cpw.mods.fml.common.eventhandler.Event.Result;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
public class BucketHandler {
@SubscribeEvent
public void onFillBucket(FillBucketEvent event) {
Block block = event.world.getBlock(event.target.blockX, event.target.blockY, event.target.blockZ);
if (block instanceof BlockFluid) if (event.current.getItem() == Items.bucket) {
ItemStack ret = ((ItemBuckets) Core.buckets).getBucket(block);
if (ret != null) {
event.result = ret;
event.setResult(Result.ALLOW);
}
}
}
}
|
Use Device.js to determine mobile editor use
Ref #2570
- Adds new library, device.js to determine if the user is on an ios mobile
or tablet.
|
/*global CodeMirror, device*/
import mobileUtils from 'ghost/utils/mobile-utils';
import createTouchEditor from 'ghost/assets/lib/touch-editor';
var setupMobileCodeMirror,
TouchEditor,
init;
setupMobileCodeMirror = function setupMobileCodeMirror() {
var noop = function () {},
key;
for (key in CodeMirror) {
if (CodeMirror.hasOwnProperty(key)) {
CodeMirror[key] = noop;
}
}
CodeMirror.fromTextArea = function (el, options) {
return new TouchEditor(el, options);
};
CodeMirror.keyMap = { basic: {} };
};
init = function init() {
//Codemirror does not function on mobile devices,
// nor on any iDevice.
if (device.mobile() || (device.tablet() && device.ios())) {
$('body').addClass('touch-editor');
// make editor tabs touch-to-toggle in portrait mode
$('.floatingheader').on('touchstart', function () {
$('.entry-markdown').toggleClass('active');
$('.entry-preview').toggleClass('active');
});
Ember.touchEditor = true;
mobileUtils.initFastClick();
TouchEditor = createTouchEditor();
setupMobileCodeMirror();
}
};
export default {
createIfMobile: init
};
|
/*global CodeMirror*/
import mobileUtils from 'ghost/utils/mobile-utils';
import createTouchEditor from 'ghost/assets/lib/touch-editor';
var setupMobileCodeMirror,
TouchEditor,
init;
setupMobileCodeMirror = function setupMobileCodeMirror() {
var noop = function () {},
key;
for (key in CodeMirror) {
if (CodeMirror.hasOwnProperty(key)) {
CodeMirror[key] = noop;
}
}
CodeMirror.fromTextArea = function (el, options) {
return new TouchEditor(el, options);
};
CodeMirror.keyMap = { basic: {} };
};
init = function init() {
if (mobileUtils.hasTouchScreen()) {
$('body').addClass('touch-editor');
// make editor tabs touch-to-toggle in portrait mode
$('.floatingheader').on('touchstart', function () {
$('.entry-markdown').toggleClass('active');
$('.entry-preview').toggleClass('active');
});
Ember.touchEditor = true;
mobileUtils.initFastClick();
TouchEditor = createTouchEditor();
setupMobileCodeMirror();
}
};
export default {
createIfMobile: init
};
|
Make constructor public, needs to be accessible from org.glassfish.jersey.*
|
/*
* Copyright 2014, The OpenNMS Group
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opennms.newts.rest;
import org.opennms.newts.api.Duration;
import io.dropwizard.jersey.params.AbstractParam;
/**
* JAX-RS parameter that encapsulates creation of {@link Duration} instances from a string
* specifier. Non-parseable values will result in a {@code 400 Bad Request} response.
*
* @author eevans
*/
public class DurationParam extends AbstractParam<Duration> {
public DurationParam(String input) {
super(input);
}
@Override
protected String errorMessage(String input, Exception e) {
return String.format("Unable to parse '%s' as resolution", input);
}
@Override
protected Duration parse(String input) throws Exception {
if (input.matches("^[\\d]+$")) {
return Duration.seconds(Integer.valueOf(input));
}
return Duration.parse(input);
}
}
|
/*
* Copyright 2014, The OpenNMS Group
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.opennms.newts.rest;
import org.opennms.newts.api.Duration;
import io.dropwizard.jersey.params.AbstractParam;
/**
* JAX-RS parameter that encapsulates creation of {@link Duration} instances from a string
* specifier. Non-parseable values will result in a {@code 400 Bad Request} response.
*
* @author eevans
*/
public class DurationParam extends AbstractParam<Duration> {
protected DurationParam(String input) {
super(input);
}
@Override
protected String errorMessage(String input, Exception e) {
return String.format("Unable to parse '%s' as resolution", input);
}
@Override
protected Duration parse(String input) throws Exception {
if (input.matches("^[\\d]+$")) {
return Duration.seconds(Integer.valueOf(input));
}
return Duration.parse(input);
}
}
|
Apply mongoose and promise pattern.
|
var config = require('./config'),
Twit = require('twit'),
mongoose = require('mongoose');
var T = new Twit(config.oauth_creds),
quotes = mongoose.model('quotes', {msg: String, src: String});
var tweet = function () {
var promise = quotes.count().exec();
promise.then(function (cnt) {
var n = Math.floor(Math.random() * cnt);
return quotes.findOne({}).skip(n).exec();
}).then(function (quote) {
var msg = quote.msg + '\n' + quote.src;
T.post('statuses/update', {status: msg}, function (err, reply) {
if (err) console.dir(err);
console.log('--->>>');
console.log(new Date);
console.log(msg);
});
}).end();
};
mongoose.connect('mongodb://tweetbot:kdznbmfsib@paulo.mongohq.com:10098/ntalbs-mongodb');
setInterval(tweet, 5000);
|
var config = require('./config'),
Twit = require('twit'),
MongoClient = require('mongodb').MongoClient;
var T = new Twit(config.oauth_creds);
var tweet = function() {
MongoClient.connect(config.db_uri, function (err, db) {
if (err) throw err;
var collection = db.collection('quotes');
collection.count(function (err, count) {
var rnd = Math.floor(Math.random() * count);
db.collection('quotes').find({}).limit(1).skip(rnd).toArray(function (err, results) {
var quote = results[0],
msg = quote.msg + '\n' + quote.src;
T.post('statuses/update', {status: msg}, function (err, reply) {
if (err) throw err;
console.log(new Date);
console.log(msg);
});
db.close();
});
});
});
};
setInterval(tweet, config.tweet_interval);
|
Add attribution to quotes in plugin
|
"""Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def generate_phrase(phrases, cache):
seed_phrase = []
while len(seed_phrase) < 3:
seed_phrase = random.choice(phrases).split()
w1, w2 = seed_phrase[:2]
chosen = [w1, w2]
while "{}|{}".format(w1, w2) in cache:
choice = random.choice(cache["{}|{}".format(w1, w2)])
w1, w2 = w2, choice
chosen.append(choice)
return ' '.join(chosen)
def on_message(bot, channel, user, message):
return '> {} ~brian'.format(generate_phrase(phrases, cache))
|
"""Displays a randomly generated witticism from Brian Chu himself."""
import json
import random
__match__ = r"!brian"
with open('plugins/brian_corpus/cache.json', 'r') as infile:
cache = json.load(infile)
with open('plugins/brian_corpus/phrases.json', 'r') as infile:
phrases = json.load(infile)
def generate_phrase(phrases, cache):
seed_phrase = []
while len(seed_phrase) < 3:
seed_phrase = random.choice(phrases).split()
w1, w2 = seed_phrase[:2]
chosen = [w1, w2]
while "{}|{}".format(w1, w2) in cache:
choice = random.choice(cache["{}|{}".format(w1, w2)])
w1, w2 = w2, choice
chosen.append(choice)
return ' '.join(chosen)
def on_message(bot, channel, user, message):
return '> {}'.format(generate_phrase(phrases, cache))
|
Disable RRD queue feature when testing so files are actually written when we write to them. :-)
|
package org.opennms.netmgt.dao.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;
public class RrdTestUtils {
// Reference the class name this way so that it is refactoring resistant
private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName()
+ "\norg.opennms.rrd.usequeue=false";
/**
* This class cannot be instantiated. Use static methods.
*/
private RrdTestUtils() {
}
public static void initialize() throws IOException, RrdException {
RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes()));
RrdUtils.initialize();
}
}
|
package org.opennms.netmgt.dao.support;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.opennms.netmgt.rrd.RrdConfig;
import org.opennms.netmgt.rrd.RrdException;
import org.opennms.netmgt.rrd.RrdUtils;
import org.opennms.netmgt.rrd.jrobin.JRobinRrdStrategy;
public class RrdTestUtils {
// Reference the class name this way so that it is refactoring resistant
private static final String RRD_CONFIG = "org.opennms.rrd.strategyClass=" + JRobinRrdStrategy.class.getName();
/**
* This class cannot be instantiated. Use static methods.
*/
private RrdTestUtils() {
}
public static void initialize() throws IOException, RrdException {
RrdConfig.loadProperties(new ByteArrayInputStream(RRD_CONFIG.getBytes()));
RrdUtils.initialize();
}
}
|
Set the alias of the function `val` to `v`.
|
# encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
template = "%s=%s"
for name in self.attrs:
try:
attrs.append(template % (name, getattr(self, name)))
except AttributeError:
pass
return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs))
def val(obj, name, default=None):
if hasattr(obj, name):
return obj.name
elif name in obj:
return obj[name]
elif isinstance(obj, (list, tuple)) and isinstance(name, int):
try:
return obj[name]
except Exception:
return default
else:
return default
v = val
|
# encoding: utf-8
### Attribute Wrapper
class AttrWrapper(object):
attrs = []
def __setattr__(self, name, value):
if name not in self.attrs:
raise AttributeError("'%s' is not supported" % name)
object.__setattr__(self, name, value)
def __repr__(self):
attrs = []
template = "%s=%s"
for name in self.attrs:
try:
attrs.append(template % (name, getattr(self, name)))
except AttributeError:
pass
return "%s(%s)" % (self.__class__.__name__, ", ".join(attrs))
def val(obj, name, default=None):
if hasattr(obj, name):
return obj.name
elif name in obj:
return obj[name]
elif isinstance(obj, (list, tuple)) and isinstance(name, int):
try:
return obj[name]
except Exception:
return default
else:
return default
|
Add test to Path compare.
|
from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
def test_cmp():
assert Path("/a/b") < Path("/a/c")
assert Path("/a/c") > Path("/a/b")
assert Path("/a/2") < Path("/b/1")
|
from farmfs.fs import normpath as _normalize
from farmfs.fs import userPath2Path as up2p
from farmfs.fs import Path
def test_normalize_abs():
assert _normalize("/") == "/"
assert _normalize("/a") == "/a"
assert _normalize("/a/") == "/a"
assert _normalize("/a/b") == "/a/b"
assert _normalize("/a/b/") == "/a/b"
assert _normalize("/a//b") == "/a/b"
assert _normalize("/a//b//") == "/a/b"
def test_normalize_relative():
assert _normalize("a") == "a"
assert _normalize("a/") == "a"
assert _normalize("a/b") == "a/b"
assert _normalize("a/b/") == "a/b"
assert _normalize("a//b") == "a/b"
assert _normalize("a//b//") == "a/b"
def test_userPath2Path():
assert up2p("c", Path("/a/b")) == Path("/a/b/c")
assert up2p("/c", Path("/a/b")) == Path("/c")
|
Handle supplying metric collector by env var.
|
var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
var host = parts[0];
var port = 9001;
if (parts.length > 1) {
port = parseInt(parts[1]);
}
var client = net.connect({host: host, port: port}, function () {
var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n';
client.write(metricReport);
client.destroy();
});
};
MonitoringPlugin.prototype.getTasksLeft = function () {
return this.engine.nTasksLeft;
};
MonitoringPlugin.prototype.init = function (rcl, wflib, engine) {
if (this.hasOwnProperty('initialized') && this.initialized === true) {
return;
}
this.rcl = rcl;
this.wflib = wflib;
this.engine = engine;
var that = this;
setInterval(function () {
that.sendMetrics();
}, 1000);
this.initialized = true;
};
module.exports = MonitoringPlugin;
|
var net = require('net');
var config = require('hyperflowMonitoringPlugin.config.js');
var MonitoringPlugin = function () {
};
MonitoringPlugin.prototype.sendMetrics = function () {
var that = this;
//TODO: Create connection once and then try to reuse it
var parts = config.metricCollector.split(':');
var host = parts[0];
var port = parts[1];
var client = net.connect({host: host, port: port}, function () {
var metricReport = config.serverName + ' nTasksLeft ' + that.getTasksLeft() + ' ' + parseInt(Date.now() / 1000) + '\r\n';
client.write(metricReport);
client.destroy();
});
};
MonitoringPlugin.prototype.getTasksLeft = function () {
return this.engine.nTasksLeft;
};
MonitoringPlugin.prototype.init = function (rcl, wflib, engine) {
if (this.hasOwnProperty('initialized') && this.initialized === true) {
return;
}
this.rcl = rcl;
this.wflib = wflib;
this.engine = engine;
var that = this;
setInterval(function () {
that.sendMetrics();
}, 1000);
this.initialized = true;
};
module.exports = MonitoringPlugin;
|
Use professional vs instead of community if found
|
#!/bin/python3.5
import os
config = """
.WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10'
.WindowsSDKSubVersion = '10.0.15063.0'
#if __WINDOWS__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = 'C:/temp/fazecache'
.VulkanSDKBasePath = 'C:/VulkanSDK/1.0.54.0'
#endif
#if __LINUX__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = '/tmp/.fbuild.fazecache'
.VulkanSDKBasePath = '/usr/lib'
#endif"""
curDir = os.getcwd().replace("\\", "/")
print("current directory: " + curDir)
config = config.replace("CURRENT_DIRECTORY", curDir)
with open('config.bff', 'w') as out:
if os.path.isdir('C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional'):
out.write(""".VSBasePath = 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional'""")
else:
out.write(""".VSBasePath = 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community'""")
out.write("\n")
out.write(config)
|
#!/bin/python3.5
import os
config = """
.VSBasePath = 'C:/Program Files (x86)/Microsoft Visual Studio/2017/Community'
.WindowsSDKBasePath10 = 'C:/Program Files (x86)/Windows Kits/10'
.WindowsSDKSubVersion = '10.0.15063.0'
#if __WINDOWS__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = 'C:/temp/fazecache'
.VulkanSDKBasePath = 'C:/VulkanSDK/1.0.54.0'
#endif
#if __LINUX__
.FazEPath = 'CURRENT_DIRECTORY'
.FBuildCache = '/tmp/.fbuild.fazecache'
.VulkanSDKBasePath = '/usr/lib'
#endif"""
curDir = os.getcwd().replace("\\", "/")
print("current directory: " + curDir)
config = config.replace("CURRENT_DIRECTORY", curDir)
with open('config.bff', 'w') as out:
out.write(config)
|
Reword and add emoji on reference
|
export function createPostbackAction(label, input, issuedAt) {
return {
type: 'postback',
label,
data: JSON.stringify({
input,
issuedAt,
}),
};
}
export function createFeedbackWords(feedbacks) {
let positive = 0;
let negative = 0;
feedbacks.forEach(e => {
if (e.score > 0) {
positive++;
}
if (e.score < 0) {
negative++;
}
});
if (positive + negative === 0) return '[還沒有人針對此回應評價]';
let result = '';
if (positive) result += `有 ${positive} 人覺得此回應有幫助\n`;
if (negative) result += `有 ${negative} 人覺得此回應沒幫助\n`;
return `[${result.trim()}]`;
}
export function createReferenceWords(reference) {
if (reference) return `出處:${reference}`;
return '\uDBC0\uDC85 ⚠️️ 此回應沒有出處,請自行斟酌回應真實。⚠️️ \uDBC0\uDC85';
}
|
export function createPostbackAction(label, input, issuedAt) {
return {
type: 'postback',
label,
data: JSON.stringify({
input,
issuedAt,
}),
};
}
export function createFeedbackWords(feedbacks) {
let positive = 0, negative = 0;
feedbacks.forEach(e => {
if (e.score > 0) {
positive++;
}
if (e.score < 0) {
negative++;
}
});
if (positive + negative === 0) return '[還沒有人針對此回應評價]';
let result = '';
if (positive) result += `有 ${positive} 人覺得此回應有幫助\n`;
if (negative) result += `有 ${negative} 人覺得此回應沒幫助\n`;
return `[${result.trim()}]`;
}
export function createReferenceWords(reference) {
if (reference) return `出處:${reference}`;
return '出處:此回應沒有出處';
}
|
Allow install of multiple programs
Fixes #26
|
#!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>...]',
'',
'where <program> is one or more of of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
]
});
if (cli.input.length === 0) {
console.error('Error: No command specified');
cli.showHelp();
process.exit(1);
}
var commands = {
'install': install
};
if (cli.input[0] in commands) {
commands[cli.input[0]].call(undefined, cli.input.splice(1));
}
function install(programList) {
if (programList.length === 0) {
allPrograms.forEach(installProgram);
} else {
programList.forEach(installProgram);
}
}
function installProgram(program) {
if (allPrograms.indexOf(program) === -1) {
console.error('Error: tried to install non-existing program "' + program + '"');
return;
}
require('./' + program).install();
}
|
#!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>]',
'',
'where <program> is one of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
]
});
if (cli.input.length === 0) {
console.error('Error: No command specified');
cli.showHelp();
process.exit(1);
}
var commands = {
'install': install
};
if (cli.input[0] in commands) {
commands[cli.input[0]].apply(undefined, cli.input.slice(1));
}
function install(programList) {
if (programList === undefined) {
allPrograms.forEach(installProgram);
} else {
installProgram(programList);
}
}
function installProgram(program) {
if (allPrograms.indexOf(program) === -1) {
console.error('Error: tried to install non-existing program "' + program + '"');
return;
}
require('./' + program).install();
}
|
Add a download_url for pypi
|
#!/usr/bin/python
import distutils
from setuptools import setup, Extension
long_desc = """This is a C extension module for Python which
implements extended attributes manipulation. It is a wrapper on top
of the attr C library - see attr(5)."""
version = "0.5.1"
author = "Iustin Pop"
author_email = "iusty@k1024.org"
macros = [
("_XATTR_VERSION", '"%s"' % version),
("_XATTR_AUTHOR", '"%s"' % author),
("_XATTR_EMAIL", '"%s"' % author_email),
]
setup(name = "pyxattr",
version = version,
description = "Filesystem extended attributes for python",
long_description = long_desc,
author = author,
author_email = author_email,
url = "http://pyxattr.k1024.org/",
download_url = "https://github.com/iustin/pyxattr/downloads",
license = "LGPL",
ext_modules = [Extension("xattr", ["xattr.c"],
libraries=["attr"],
define_macros=macros)],
test_suite = "test",
)
|
#!/usr/bin/python
import distutils
from setuptools import setup, Extension
long_desc = """This is a C extension module for Python which
implements extended attributes manipulation. It is a wrapper on top
of the attr C library - see attr(5)."""
version = "0.5.1"
author = "Iustin Pop"
author_email = "iusty@k1024.org"
macros = [
("_XATTR_VERSION", '"%s"' % version),
("_XATTR_AUTHOR", '"%s"' % author),
("_XATTR_EMAIL", '"%s"' % author_email),
]
setup(name = "pyxattr",
version = version,
description = "Filesystem extended attributes for python",
long_description = long_desc,
author = author,
author_email = author_email,
url = "http://pyxattr.k1024.org/",
license = "LGPL",
ext_modules = [Extension("xattr", ["xattr.c"],
libraries=["attr"],
define_macros=macros)],
test_suite = "test",
)
|
Return *SMSResponse for text and *CALLResponse for call
|
package twigo
func NewClient(account_sid, auth_token, number string) (*Client, error) {
c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}
err := Validate(*c)
if err != nil {
return nil,err
}
return c, nil
}
func (c *Client) Text(msg_sms *SMS) (*SMSResponse, error) {
err := Validate(*msg_sms)
if err != nil {
return nil, err
}
smsResponse := &SMSResponse{}
err = Send(c, msg_sms, smsResponse)
return smsResponse, err
}
func (c *Client) Call(msg_voice *CALL) (*CALLResponse, error) {
err := Validate(*msg_voice)
if err != nil {
return nil, err
}
callResponse := &CALLResponse{}
err = Send(c, msg_voice, callResponse)
return callResponse, err
}
|
package twigo
func NewClient(account_sid, auth_token, number string) (*Client, error) {
c := &Client{AccountSid:account_sid,AuthToken:auth_token,Number:number}
err := Validate(*c)
if err != nil {
return nil,err
}
return c, nil
}
func (c *Client) Text(msg_sms *SMS) (interface{}, error) {
err := Validate(*msg_sms)
if err != nil {
return nil, err
}
smsResponse := &SMSResponse{}
resp, err := Send(c, msg_sms, smsResponse)
return resp,err
}
func (c *Client) Call(msg_voice *CALL) (interface{}, error) {
err := Validate(*msg_voice)
if err != nil {
return nil, err
}
callResponse := &CALLResponse{}
resp, err := Send(c, msg_voice, callResponse)
return resp,err
}
|
Fix fixture for older versions
|
import pytest
import factory
from factory.alchemy import SQLAlchemyModelFactory
from pytest_factoryboy import register
from ckan.plugins import toolkit
import ckan.model as model
from ckanext.googleanalytics.model import PackageStats, ResourceStats
if toolkit.requires_ckan_version("2.9"):
@pytest.fixture()
def clean_db(reset_db, migrate_db_for):
reset_db()
migrate_db_for("googleanalytics")
else:
from dbutil import init_tables
@pytest.fixture()
def clean_db(reset_db):
reset_db()
init_tables()
@register
class PackageStatsFactory(SQLAlchemyModelFactory):
class Meta:
sqlalchemy_session = model.Session
model = PackageStats
package_id = factory.Faker("uuid4")
visits_recently = factory.Faker("pyint")
visits_ever = factory.Faker("pyint")
@register
class ResourceStatsFactory(SQLAlchemyModelFactory):
class Meta:
sqlalchemy_session = model.Session
model = ResourceStats
resource_id = factory.Faker("uuid4")
visits_recently = factory.Faker("pyint")
visits_ever = factory.Faker("pyint")
|
import pytest
import factory
from factory.alchemy import SQLAlchemyModelFactory
from pytest_factoryboy import register
import ckan.model as model
from ckanext.googleanalytics.model import PackageStats, ResourceStats
@pytest.fixture()
def clean_db(reset_db, migrate_db_for):
reset_db()
migrate_db_for("googleanalytics")
@register
class PackageStatsFactory(SQLAlchemyModelFactory):
class Meta:
sqlalchemy_session = model.Session
model = PackageStats
package_id = factory.Faker("uuid4")
visits_recently = factory.Faker("pyint")
visits_ever = factory.Faker("pyint")
@register
class ResourceStatsFactory(SQLAlchemyModelFactory):
class Meta:
sqlalchemy_session = model.Session
model = ResourceStats
resource_id = factory.Faker("uuid4")
visits_recently = factory.Faker("pyint")
visits_ever = factory.Faker("pyint")
|
Remove apply shortcut from external api
|
"use strict";
window.arethusaExternalApi = function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
return true;
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can implement this safely. We just ask if arethusa is loaded and proceed -
// if it's not, we provide a mock object that just does nothing.
if (obj.isArethusaLoaded()) {
angular.element(document.body).ready(function() {
obj.injector = angular.element(document.body).injector();
obj.state = obj.injector.get('state');
obj.scope = angular.element(document.getElementById('arethusa-main-view')).scope();
obj.fireEvent = function(token, category, oldVal, newVal) {
obj.state.fireEvent(token, category, oldVal, newVal);
};
});
} else {
// tbd - BlackHole object
}
return obj;
};
|
"use strict";
window.arethusaExternalApi = function () {
var obj = {};
obj.isArethusaLoaded = function() {
try {
angular.module('arethusa');
return true;
} catch(err) {
return false;
}
};
// I guess it might come to this sort of guarding close, so that other plugin
// can implement this safely. We just ask if arethusa is loaded and proceed -
// if it's not, we provide a mock object that just does nothing.
if (obj.isArethusaLoaded()) {
angular.element(document.body).ready(function() {
obj.injector = angular.element(document.body).injector();
obj.state = obj.injector.get('state');
obj.scope = angular.element(document.getElementById('arethusa-main-view')).scope();
obj.apply = obj.scope.$apply;
obj.fireEvent = function(token, category, oldVal, newVal) {
obj.state.fireEvent(token, category, oldVal, newVal);
};
});
} else {
// tbd - BlackHole object
}
return obj;
};
|
Simplify tests to new format.
|
"""
Test suite for Reflex Axelrod PD player.
"""
import axelrod
from test_player import TestPlayer
class Reflex_test(TestPlayer):
name = "Reflex"
player = axelrod.Reflex
stochastic = False
def test_strategy(self):
""" First response should always be cooperation. """
p1 = axelrod.Reflex()
p2 = axelrod.Player()
self.assertEqual(p1.strategy(p2), 'C')
def test_reset_method(self):
""" Does self.reset() reset the self? """
p1 = axelrod.Reflex()
p1.history = ['C', 'D', 'C', 'C']
p1.reset()
self.assertEqual(p1.history, [])
self.assertEqual(p1.response, 'C')
|
"""
Test suite for Reflex Axelrod PD player.
"""
import axelrod
from test_player import TestPlayer
class Reflex_test(TestPlayer):
def test_initial_nice_strategy(self):
""" First response should always be cooperation. """
p1 = axelrod.Reflex()
p2 = axelrod.Player()
self.assertEqual(p1.strategy(p2), 'C')
def test_representation(self):
""" How do we appear? """
p1 = axelrod.Reflex()
self.assertEqual(str(p1), "Reflex")
def test_reset_method(self):
""" Does self.reset() reset the self? """
p1 = axelrod.Reflex()
p1.history = ['C', 'D', 'C', 'C']
p1.reset()
self.assertEqual(p1.history, [])
self.assertEqual(p1.response, 'C')
def test_stochastic(self):
""" We are not stochastic. """
self.assertFalse(axelrod.Reflex().stochastic)
|
serve: Remove plugin name from URL before passing it to the plugin.
|
import { createServer } from 'http'
import { Plugin } from 'munar-core'
import micro, { createError } from 'micro'
export default class Serve extends Plugin {
static defaultOptions = {
port: 3000
}
enable () {
this.server = micro(this.onRequest)
this.server.listen(this.options.port)
}
disable () {
this.server.close()
}
onRequest = async (req, res) => {
const pluginName = req.url.split('/')[1]
const plugin = await this.bot.getPlugin(pluginName)
if (!plugin || typeof plugin.serve !== 'function') {
throw createError(404, 'That plugin does not exist or does not expose a web interface.')
}
// Remove plugin name from the URL.
const parts = req.url.split('/')
parts.splice(1, 1)
req.url = parts.join('/')
return plugin.serve(req, res, {
send: micro.send,
sendError: micro.sendError,
createError: micro.createError,
json: micro.json
})
}
}
|
import { createServer } from 'http'
import { Plugin } from 'munar-core'
import micro, { createError } from 'micro'
export default class Serve extends Plugin {
static defaultOptions = {
port: 3000
}
enable () {
this.server = micro(this.onRequest)
this.server.listen(this.options.port)
}
disable () {
this.server.close()
}
onRequest = async (req, res) => {
const pluginName = req.url.split('/')[1]
const plugin = await this.bot.getPlugin(pluginName)
if (!plugin || typeof plugin.serve !== 'function') {
throw createError(404, 'That plugin does not exist or does not expose a web interface.')
}
return plugin.serve(req, res, {
send: micro.send,
sendError: micro.sendError,
createError: micro.createError,
json: micro.json
})
}
}
|
Fix ClickableBox dropping styles when not clickable
|
// @flow
import React from 'react'
import type {Props} from './clickable-box'
import Box from './box'
import {TouchableHighlight, TouchableWithoutFeedback} from 'react-native'
import {globalColors} from '../styles'
const ClickableBox = ({onClick, onLongPress, style, children, underlayColor, onPressIn, onPressOut, feedback = true}: Props) => {
if (onClick) {
if (feedback) {
return <TouchableHighlight
disabled={!onClick}
onPress={onClick}
onPressIn={onPressIn}
onPressOut={onPressOut}
onLongPress={onLongPress}
style={{...boxStyle, ...style}}
underlayColor={underlayColor || globalColors.black_10}>
{children}
</TouchableHighlight>
} else {
return <TouchableWithoutFeedback
onPressIn={onPressIn}
onPressOut={onPressOut}
style={{...boxStyle, ...style}}
onPress={onClick}
onLongPress={onLongPress}>
{children}
</TouchableWithoutFeedback>
}
} else {
return <Box
style={{...boxStyle, ...style}}>
{children}
</Box>
}
}
const boxStyle = {
borderRadius: 3,
}
export default ClickableBox
|
// @flow
import React from 'react'
import type {Props} from './clickable-box'
import {TouchableHighlight, TouchableWithoutFeedback} from 'react-native'
import {globalColors} from '../styles'
const ClickableBox = ({onClick, onLongPress, style, children, underlayColor, onPressIn, onPressOut, feedback = true}: Props) => {
if (onClick) {
if (feedback) {
return <TouchableHighlight
disabled={!onClick}
onPress={onClick}
onPressIn={onPressIn}
onPressOut={onPressOut}
onLongPress={onLongPress}
style={{...boxStyle, ...style}}
underlayColor={underlayColor || globalColors.black_10}>
{children}
</TouchableHighlight>
} else {
return <TouchableWithoutFeedback
onPressIn={onPressIn}
onPressOut={onPressOut}
style={{...boxStyle, ...style}}
onPress={onClick}
onLongPress={onLongPress}>
{children}
</TouchableWithoutFeedback>
}
} else {
return children
}
}
const boxStyle = {
borderRadius: 3,
}
export default ClickableBox
|
Fix location type in get video
- Can just use raw int from C*
|
import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
* Gets the details of a specific video from the catalog.
*/
export function getVideo(call, cb) {
return Promise.try(() => {
let { request } = call;
let client = getCassandraClient();
let requestParams = [
toCassandraUuid(request.videoId)
];
return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams);
})
.then(resultSet => {
let row = resultSet.first();
if (row === null) {
throw new NotFoundError(`A video with id ${request.videoId.value} was not found`);
}
return new GetVideoResponse({
videoId: toProtobufUuid(row.videoid),
userId: toProtobufUuid(row.userid),
name: row.name,
description: row.description,
location: row.location,
locationType: row.location_type,
tags: row.tags,
addedDate: toProtobufTimestamp(row.added_date)
});
})
.asCallback(cb);
};
|
import Promise from 'bluebird';
import { GetVideoResponse, VideoLocationType } from './protos';
import { toCassandraUuid, toProtobufTimestamp, toProtobufUuid } from '../common/protobuf-conversions';
import { NotFoundError } from '../common/grpc-errors';
import { getCassandraClient } from '../../common/cassandra';
/**
* Gets the details of a specific video from the catalog.
*/
export function getVideo(call, cb) {
return Promise.try(() => {
let { request } = call;
let client = getCassandraClient();
let requestParams = [
toCassandraUuid(request.videoId)
];
return client.executeAsync('SELECT * FROM videos WHERE videoid = ?', requestParams);
})
.then(resultSet => {
let row = resultSet.first();
if (row === null) {
throw new NotFoundError(`A video with id ${request.videoId.value} was not found`);
}
return new GetVideoResponse({
videoId: toProtobufUuid(row.videoid),
userId: toProtobufUuid(row.userid),
name: row.name,
description: row.description,
location: row.location,
locationType: new VideoLocationType(row.location_type),
tags: row.tags,
addedDate: toProtobufTimestamp(row.added_date)
});
})
.asCallback(cb);
};
|
Check to see if the url has the context path first.
|
/**
* Since IRIDA can be served within a container, all requests need to have
* the correct base url. This will add, if required, the base url.
*
* NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL
* BE AUTOMATICALLY HANDLED.
*
* @param {string} url
* @return {string|*}
*/
export function setBaseUrl(url) {
/*
Get the base url which is set via the thymeleaf template engine.
*/
const BASE_URL = window.TL?._BASE_URL || "/";
/*
Check to make sure that the given url has not already been given the
base url.
*/
if (url.startsWith(BASE_URL) || url.startsWith("http")) {
return url;
}
// Remove any leading slashes
url = url.replace(/^\/+/, "");
/*
Create the new url
*/
return `${BASE_URL}${url}`;
}
|
/**
* Since IRIDA can be served within a container, all requests need to have
* the correct base url. This will add, if required, the base url.
*
* NOTE: THIS ONLY NEEDS TO BE CALLED FOR LINKS, ASYNCHRONOUS REQUESTS WILL
* BE AUTOMATICALLY HANDLED.
*
* @param {string} url
* @return {string|*}
*/
export function setBaseUrl(url) {
// Remove any leading slashes
url = url.replace(/^\/+/, "");
/*
Get the base url which is set via the thymeleaf template engine.
*/
const BASE_URL = window.TL?._BASE_URL || "/";
/*
Check to make sure that the given url has not already been given the
base url.
*/
if (
(BASE_URL !== "/" && url.startsWith(BASE_URL)) ||
url.startsWith("http")
) {
return url;
}
/*
Create the new url
*/
return `${BASE_URL}${url}`;
}
|
Add error message to NFC sample
|
scanButton.addEventListener("click", async () => {
log("User clicked scan button");
try {
const reader = new NDEFReader();
await reader.scan();
log("> Scan started");
reader.addEventListener("error", () => {
log(`Argh! ${error.message}`);
});
reader.addEventListener("reading", ({ message, serialNumber }) => {
log(`> Serial Number: ${serialNumber}`);
log(`> Records: (${message.records.length})`);
});
} catch (error) {
log("Argh! " + error);
}
});
writeButton.addEventListener("click", async () => {
log("User clicked write button");
try {
const writer = new NDEFWriter();
await writer.write("Hello world!");
log("> Message written");
} catch (error) {
log("Argh! " + error);
}
});
|
scanButton.addEventListener("click", async () => {
log("User clicked scan button");
try {
const reader = new NDEFReader();
await reader.scan();
log("> Scan started");
reader.addEventListener("error", () => {
log("Argh! Cannot read data from the NFC tag. Try a different one?");
});
reader.addEventListener("reading", ({ message, serialNumber }) => {
log(`> Serial Number: ${serialNumber}`);
log(`> Records: (${message.records.length})`);
});
} catch (error) {
log("Argh! " + error);
}
});
writeButton.addEventListener("click", async () => {
log("User clicked write button");
try {
const writer = new NDEFWriter();
await writer.write("Hello world!");
log("> Message written");
} catch (error) {
log("Argh! " + error);
}
});
|
Make it clearer that exactly one item allows psum < 0
|
def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = float('inf'), limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if score < best and (psum >= 0 or i == j):
best = score
index = i
scores.append(best)
trace.append(index)
return _build_indices(trace)
def _build_indices(trace):
indices, index = [], len(trace) - 1
while index >= 0:
indices.append((trace[index], index + 1))
index = trace[index] - 1
return indices[::-1]
|
def _dynamic_wrap(items, limit):
scores, trace = [0], []
for j in range(len(items)):
best, psum, index = 0, limit, -1
for i in reversed(range(j + 1)):
psum -= items[i]
score = scores[i] + psum ** 2
if i == j or score < best and psum >= 0:
best = score
index = i
scores.append(best)
trace.append(index)
return _build_indices(trace)
def _build_indices(trace):
indices, index = [], len(trace) - 1
while index >= 0:
indices.append((trace[index], index + 1))
index = trace[index] - 1
return indices[::-1]
|
Fix argument count on `Error`
|
import ls from 'local-storage';
const defaulGetDocumentStorageId = (doc, name) => {
const { _id, conversationId } = doc
if (_id && name) { return {id: `${_id}${name}`, verify: true}}
if (_id) { return {id: _id, verify: true }}
if (conversationId) { return {id: conversationId, verify: true }}
if (name) { return {id: name, verify: true }}
else {
throw Error(`Can't get storage ID for this document: ${doc}`)
}
}
export const getLSHandlers = (getLocalStorageId = null) => {
const idGenerator = getLocalStorageId || defaulGetDocumentStorageId
return {
get: ({doc, name}) => {
const { id, verify } = idGenerator(doc, name)
const savedState = ls.get(id)
if (verify && savedState && Meteor.isClient && window) {
const result = window.confirm("We've found a previously saved state for this document, would you like to restore it?")
return result ? savedState : null
} else {
return savedState
}
},
set: ({state, doc, name}) => {ls.set(idGenerator(doc, name).id, state)},
reset: ({doc, name}) => {ls.remove(idGenerator(doc, name).id)}
}
}
|
import ls from 'local-storage';
const defaulGetDocumentStorageId = (doc, name) => {
const { _id, conversationId } = doc
if (_id && name) { return {id: `${_id}${name}`, verify: true}}
if (_id) { return {id: _id, verify: true }}
if (conversationId) { return {id: conversationId, verify: true }}
if (name) { return {id: name, verify: true }}
else { throw Error("Can't get storage ID for this document:", doc)}
}
export const getLSHandlers = (getLocalStorageId = null) => {
const idGenerator = getLocalStorageId || defaulGetDocumentStorageId
return {
get: ({doc, name}) => {
const { id, verify } = idGenerator(doc, name)
const savedState = ls.get(id)
if (verify && savedState && Meteor.isClient && window) {
const result = window.confirm("We've found a previously saved state for this document, would you like to restore it?")
return result ? savedState : null
} else {
return savedState
}
},
set: ({state, doc, name}) => {ls.set(idGenerator(doc, name).id, state)},
reset: ({doc, name}) => {ls.remove(idGenerator(doc, name).id)}
}
}
|
Fix JSCS violation that snuck in while the reporter was broken
|
(function() {
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/orders/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Order Details',
resolve: {
order: resolveOrder
}
}
};
}
/** @ngInject */
function resolveOrder($stateParams, Order) {
return Order.get({
id: $stateParams.orderId,
'includes[]': ['product', 'project', 'service', 'staff']
}).$promise;
}
/** @ngInject */
function StateController(order) {
var vm = this;
vm.order = order;
vm.staff = order.staff;
vm.product = order.product;
vm.service = order.service;
vm.project = order.project;
vm.activate = activate;
activate();
function activate() {
}
}
})();
|
(function(){
'use strict';
angular.module('app.states')
.run(appRun);
/** @ngInject */
function appRun(routerHelper) {
routerHelper.configureStates(getStates());
}
function getStates() {
return {
'orders.details': {
url: '/details/:orderId',
templateUrl: 'app/states/orders/details/details.html',
controller: StateController,
controllerAs: 'vm',
title: 'Order Details',
resolve: {
order: resolveOrder
}
}
};
}
/** @ngInject */
function resolveOrder($stateParams, Order){
return Order.get({
id: $stateParams.orderId,
'includes[]': ['product', 'project', 'service', 'staff']
}).$promise;
}
/** @ngInject */
function StateController(order) {
var vm = this;
vm.order = order;
vm.staff = order.staff;
vm.product = order.product;
vm.service = order.service;
vm.project = order.project;
vm.activate = activate;
activate();
function activate() {
}
}
})();
|
Fix for BISERVER-7626
Unable to create a CSV based data source
|
package org.pentaho.platform.dataaccess.datasource.wizard.models;
/**
* User: nbaker
* Date: Aug 13, 2010
*/
public class DatasourceDTOUtil {
public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.setCsvModelInfo(model.getModelInfo());
dto.setDatasourceType(model.getDatasourceType());
dto.setQuery(model.getQuery());
if(model.getSelectedRelationalConnection() != null){
dto.setConnectionName(model.getSelectedRelationalConnection().getName());
}
return dto;
}
public static void populateModel(DatasourceDTO dto, DatasourceModel model){
model.setDatasourceName(dto.getDatasourceName());
model.setModelInfo(dto.getCsvModelInfo());
model.setDatasourceType(dto.getDatasourceType());
model.setQuery(dto.getQuery());
model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName()));
}
}
|
package org.pentaho.platform.dataaccess.datasource.wizard.models;
/**
* User: nbaker
* Date: Aug 13, 2010
*/
public class DatasourceDTOUtil {
public static DatasourceDTO generateDTO(DatasourceModel model){
DatasourceDTO dto = new DatasourceDTO();
dto.setDatasourceName(model.getDatasourceName());
dto.setCsvModelInfo(model.getModelInfo());
dto.setDatasourceType(model.getDatasourceType());
dto.setQuery(model.getQuery());
dto.setConnectionName(model.getSelectedRelationalConnection().getName());
return dto;
}
public static void populateModel(DatasourceDTO dto, DatasourceModel model){
model.setDatasourceName(dto.getDatasourceName());
model.setModelInfo(dto.getCsvModelInfo());
model.setDatasourceType(dto.getDatasourceType());
model.setQuery(dto.getQuery());
model.setSelectedRelationalConnection(model.getGuiStateModel().getConnectionByName(dto.getConnectionName()));
}
}
|
Check if dataset exist on `head` node
document.body migth not be present if scripts are loaded in <head/>
|
module.exports=dataset;
/*global document*/
// replace namesLikeThis with names-like-this
function toDashed(name) {
return name.replace(/([A-Z])/g, function(u) {
return "-" + u.toLowerCase();
});
}
var fn;
if (document.head.dataset) {
fn = {
set: function(node, attr, value) {
node.dataset[attr] = value;
},
get: function(node, attr) {
return node.dataset[attr];
}
};
} else {
fn = {
set: function(node, attr, value) {
node.setAttribute('data-' + toDashed(attr), value);
},
get: function(node, attr) {
return node.getAttribute('data-' + toDashed(attr));
}
};
}
function dataset(node, attr, value) {
var self = {
set: set,
get: get
};
function set(attr, value) {
fn.set(node, attr, value);
return self;
}
function get(attr) {
return fn.get(node, attr);
}
if (arguments.length === 3) {
return set(attr, value);
}
if (arguments.length == 2) {
return get(attr);
}
return self;
}
|
module.exports=dataset;
/*global document*/
// replace namesLikeThis with names-like-this
function toDashed(name) {
return name.replace(/([A-Z])/g, function(u) {
return "-" + u.toLowerCase();
});
}
var fn;
if (document.body.dataset) {
fn = {
set: function(node, attr, value) {
node.dataset[attr] = value;
},
get: function(node, attr) {
return node.dataset[attr];
}
};
} else {
fn = {
set: function(node, attr, value) {
node.setAttribute('data-' + toDashed(attr), value);
},
get: function(node, attr) {
return node.getAttribute('data-' + toDashed(attr));
}
};
}
function dataset(node, attr, value) {
var self = {
set: set,
get: get
};
function set(attr, value) {
fn.set(node, attr, value);
return self;
}
function get(attr) {
return fn.get(node, attr);
}
if (arguments.length === 3) {
return set(attr, value);
}
if (arguments.length == 2) {
return get(attr);
}
return self;
}
|
Add users count to json representation.
|
from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
def to_json(self):
json = super(WaifuModel, self).to_json()
json['users_count'] = self.users.count()
return json
|
from models.base_model import BaseModel
from datetime import datetime
from models.user_model import UserModel
from peewee import CharField, TextField, DateTimeField, IntegerField, ForeignKeyField
WAIFU_SHARING_STATUS_PRIVATE = 1
WAIFU_SHARING_STATUS_PUBLIC_MODERATION = 2
WAIFU_SHARING_STATUS_PUBLIC = 3
class WaifuModel(BaseModel):
class Meta:
db_table = 'waifus'
name = CharField(max_length=128, null=False)
description = TextField(null=False)
pic = CharField(max_length=128, null=False)
created_at = DateTimeField(null=False, default=datetime.now)
updated_at = DateTimeField(null=False, default=datetime.now)
rating = IntegerField(null=False, default=0)
sharing_status = IntegerField(null=False, default=WAIFU_SHARING_STATUS_PRIVATE)
owner = ForeignKeyField(UserModel, related_name='waifus_created_by_me')
|
Clean up the temporary file when done with it.
|
import os
from test_support import TESTFN
from UserList import UserList
# verify writelines with instance sequence
l = UserList(['1', '2'])
f = open(TESTFN, 'wb')
f.writelines(l)
f.close()
f = open(TESTFN, 'rb')
buf = f.read()
f.close()
assert buf == '12'
# verify writelines with integers
f = open(TESTFN, 'wb')
try:
f.writelines([1, 2, 3])
except TypeError:
pass
else:
print "writelines accepted sequence of integers"
f.close()
# verify writelines with integers in UserList
f = open(TESTFN, 'wb')
l = UserList([1,2,3])
try:
f.writelines(l)
except TypeError:
pass
else:
print "writelines accepted sequence of integers"
f.close()
# verify writelines with non-string object
class NonString: pass
f = open(TESTFN, 'wb')
try:
f.writelines([NonString(), NonString()])
except TypeError:
pass
else:
print "writelines accepted sequence of non-string objects"
f.close()
os.unlink(TESTFN)
|
from test_support import TESTFN
from UserList import UserList
# verify writelines with instance sequence
l = UserList(['1', '2'])
f = open(TESTFN, 'wb')
f.writelines(l)
f.close()
f = open(TESTFN, 'rb')
buf = f.read()
f.close()
assert buf == '12'
# verify writelines with integers
f = open(TESTFN, 'wb')
try:
f.writelines([1, 2, 3])
except TypeError:
pass
else:
print "writelines accepted sequence of integers"
f.close()
# verify writelines with integers in UserList
f = open(TESTFN, 'wb')
l = UserList([1,2,3])
try:
f.writelines(l)
except TypeError:
pass
else:
print "writelines accepted sequence of integers"
f.close()
# verify writelines with non-string object
class NonString: pass
f = open(TESTFN, 'wb')
try:
f.writelines([NonString(), NonString()])
except TypeError:
pass
else:
print "writelines accepted sequence of non-string objects"
f.close()
|
fix: Use new interface for twine
|
"""PyPI
"""
from invoke import run
from twine import settings
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
run('python setup.py {}'.format(dists))
twine_upload.upload(
settings.Settings(
username=username,
password=password,
skip_existing=skip_existing,
),
['dist/*'],
)
run('rm -rf build dist')
|
"""PyPI
"""
from invoke import run
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dists: The dists string passed to setup.py. Default: 'bdist_wheel'
:param username: PyPI account username string
:param password: PyPI account password string
:param skip_existing: Continue uploading files if one already exists. (Only valid when
uploading to PyPI. Other implementations may not support this.)
"""
run('python setup.py {}'.format(dists))
twine_upload.upload(
dists=['dist/*'],
sign=False,
identity=None,
username=username,
password=password,
comment=None,
sign_with='gpg',
config_file='~/.pypirc',
skip_existing=skip_existing,
cert=None,
client_cert=None,
repository_url=None
)
run('rm -rf build dist')
|
Use django reverse function to obtain url instead of hard-coding
|
from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
from django.urls import reverse
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user_object = auth.authenticate(request, username=username, password=password)
if user_object is None:
messages.error(request, "Invalid credentials")
return self.get(request)
auth.login(request, user_object)
messages.success(request, "You've been logged in")
return http.HttpResponseRedirect(self.get_next_url(request))
def get_next_url(self, request):
if "next" in request.GET:
return request.GET['next']
else:
return reverse("admin:Panel")
class Panel(TemplateView):
template_name = "admin/panel.html"
class LogoutView(View):
def get(self, request):
auth.logout(request)
return http.HttpResponseRedirect("/administration/login")
|
from django.views import View
from django.views.generic import TemplateView
from django.contrib import auth
from django.contrib import messages
from django import http
class LoginView(TemplateView):
template_name = "admin/login.html"
def post(self, request):
username = request.POST['username']
password = request.POST['password']
user_object = auth.authenticate(request, username=username, password=password)
if user_object is None:
messages.error(request, "Invalid credentials")
return self.get(request)
auth.login(request, user_object)
messages.success(request, "You've been logged in")
return http.HttpResponseRedirect(self.get_next_url(request))
def get_next_url(self, request):
if "next" in request.GET:
return request.GET['next']
else:
return "/administration/panel"
class Panel(TemplateView):
template_name = "admin/panel.html"
class LogoutView(View):
def get(self, request):
auth.logout(request)
return http.HttpResponseRedirect("/administration/login")
|
Add 'Q' as a hotkey for panning
|
/*globals svgEditor, svgCanvas*/
/*jslint eqeq: true*/
/*
* ext-panning.js
*
* Licensed under the MIT License
*
* Copyright(c) 2013 Luis Aguirre
*
*/
/*
This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem
*/
svgEditor.addExtension('ext-panning', function() {'use strict';
return {
name: 'Extension Panning',
svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml',
buttons: [{
id: 'ext-panning',
type: 'mode',
title: 'Panning',
key: 'Q',
events: {
click: function() {
svgCanvas.setMode('ext-panning');
}
}
}],
mouseDown: function() {
if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(true);
return {started: true};
}
},
mouseUp: function() {
if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(false);
return {
keep: false,
element: null
};
}
}
};
});
|
/*globals svgEditor, svgCanvas*/
/*jslint eqeq: true*/
/*
* ext-panning.js
*
* Licensed under the MIT License
*
* Copyright(c) 2013 Luis Aguirre
*
*/
/*
This is a very basic SVG-Edit extension to let tablet/mobile devices panning without problem
*/
svgEditor.addExtension('ext-panning', function() {'use strict';
return {
name: 'Extension Panning',
svgicons: svgEditor.curConfig.extPath + 'ext-panning.xml',
buttons: [{
id: 'ext-panning',
type: 'mode',
title: 'Panning',
events: {
click: function() {
svgCanvas.setMode('ext-panning');
}
}
}],
mouseDown: function() {
if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(true);
return {started: true};
}
},
mouseUp: function() {
if (svgCanvas.getMode() == 'ext-panning') {
svgEditor.setPanning(false);
return {
keep: false,
element: null
};
}
}
};
});
|
Fix webpack bundle output path
|
/* global require */
var webpack = require('webpack');
//noinspection JSUnresolvedVariable
module.exports = {
entry: './client/main.js',
output: {
path: __dirname,
filename: './server/src/static/scripts/bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: {presets: ['es2015', 'react']}
}],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
]
}
]
}
};
|
/* global require */
var webpack = require('webpack');
//noinspection JSUnresolvedVariable
module.exports = {
entry: './client/main.js',
output: {
path: __dirname,
filename: './server/static/scripts/bundle.js'
},
module: {
rules: [
{
test: /\.js$/,
exclude: [/node_modules/],
use: [{
loader: 'babel-loader',
options: {presets: ['es2015', 'react']}
}],
},
{
test: /\.scss$/,
use: [
'style-loader',
'css-loader',
'sass-loader',
]
}
]
}
};
|
Make naming consistent with our standard (camelcase always, even with acronymn)
|
import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXmlDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
def testCsvDocumentExists(self):
self.assertTrue(os.path.exists(csv_doc))
if __name__ == '__main__':
unittest.main()
|
import os
import unittest
import numpy
import arcpy
from utils import *
# import our constants;
# configure test data
# XXX: use .ini files for these instead? used in other 'important' unit tests
from config import *
# import our local directory so we can use the internal modules
import_paths = ['../Install/toolbox', '../Install']
addLocalPaths(import_paths)
class TestBpiScript(unittest.TestCase):
from scripts import bpi
def testBpiImport(self, method=bpi):
self.assertRaises(ValueError, method.main(), None)
def testBpiRun(self):
pass
class TestStandardizeBpiGridsScript(unittest.TestCase):
from scripts import standardize_bpi_grids
def testStdImport(self, method=standardize_bpi_grids):
pass
def testStdRun(self):
pass
class TestBtmDocument(unittest.TestCase):
# XXX this won't automatically get the right thing... how can we fix it?
import utils
def testXMLDocumentExists(self):
self.assertTrue(os.path.exists(xml_doc))
if __name__ == '__main__':
unittest.main()
|
Add java 6 compatible generic declaration
|
package controllers;
import models.Panic;
import play.mvc.Controller;
import play.mvc.results.RenderJson;
import java.util.ArrayList;
import java.util.List;
public class Application extends Controller {
public static List<Panic> panics = new ArrayList<Panic>();
public static void index() {
render();
}
public static void getData() {
throw new RenderJson(panics.size());
}
public static void submit() {
String sessionHash = Panic.getPanicHash(session);
long sessionTime = Panic.getPanicTime();
for (Panic panic : panics) {
if (panic.getId().equals(sessionHash)) {
panic.setTime(sessionTime);
index();
return;
}
}
panics.add(new Panic(sessionHash, sessionTime));
index();
}
}
|
package controllers;
import models.Panic;
import play.mvc.Controller;
import play.mvc.results.RenderJson;
import java.util.ArrayList;
import java.util.List;
public class Application extends Controller {
public static List<Panic> panics = new ArrayList<>();
public static void index() {
render();
}
public static void getData() {
throw new RenderJson(panics.size());
}
public static void submit() {
String sessionHash = Panic.getPanicHash(session);
long sessionTime = Panic.getPanicTime();
for (Panic panic : panics) {
if (panic.getId().equals(sessionHash)) {
panic.setTime(sessionTime);
index();
return;
}
}
panics.add(new Panic(sessionHash, sessionTime));
index();
}
}
|
Update aerial-accounts version -> 0.4.0
|
Package.describe({
name: 'bquarks:aerialjs',
version: '0.1.4',
// Brief, one-line summary of the package.
summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/bquarks/aerialjs.git',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.3.2.4');
api.use(['ecmascript', 'bquarks:aerial-mongo@0.0.14', 'bquarks:aerial-minimongo@0.0.14',
'bquarks:aerial-corbel@0.2.1', 'bquarks:aerial-accounts@0.4.0'], {weak: false, unordered:false});
api.mainModule('aerialjs.js');
});
// Package.onTest(function(api) {
// api.use('ecmascript');
// api.use('tinytest');
// api.use('bquarks:aerialjs');
// api.mainModule('aerialjs-tests.js');
// });
|
Package.describe({
name: 'bquarks:aerialjs',
version: '0.1.4',
// Brief, one-line summary of the package.
summary: 'Suite Aerialjs to connect Meteor applications with Corble Platform.',
// URL to the Git repository containing the source code for this package.
git: 'https://github.com/bquarks/aerialjs.git',
// By default, Meteor will default to using README.md for documentation.
// To avoid submitting documentation, set this field to null.
documentation: 'README.md'
});
Package.onUse(function(api) {
api.versionsFrom('METEOR@1.3.2.4');
api.use(['ecmascript', 'bquarks:aerial-mongo@0.0.14', 'bquarks:aerial-minimongo@0.0.14',
'bquarks:aerial-corbel@0.2.1', 'bquarks:aerial-accounts@0.3.1'], {weak: false, unordered:false});
api.mainModule('aerialjs.js');
});
// Package.onTest(function(api) {
// api.use('ecmascript');
// api.use('tinytest');
// api.use('bquarks:aerialjs');
// api.mainModule('aerialjs-tests.js');
// });
|
Support for listing all packages
|
package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
"sort"
)
func init() {
RootCmd.AddCommand(searchCommand)
}
var searchCommand = &cobra.Command{
Use: "search [TERM]",
Short: "Search for packages on Docker Hub",
Long: "Search for Whalebrew packages on Docker Hub. If no search term is provided, all packages are listed.",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 1 {
return fmt.Errorf("Only one search term is supported")
}
cli, err := client.NewEnvClient()
if err != nil {
return err
}
term := "whalebrew/"
if len(args) == 1 {
term = term + args[0]
}
options := types.ImageSearchOptions{Limit: 100}
results, err := cli.ImageSearch(context.Background(), term, options)
if err != nil {
return err
}
names := make([]string, len(results))
for i, result := range results {
names[i] = result.Name
}
sort.Strings(names)
for _, name := range names {
fmt.Println(name)
}
return nil
},
}
|
package cmd
import (
"context"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
)
func init() {
RootCmd.AddCommand(searchCommand)
}
var searchCommand = &cobra.Command{
Use: "search TERM",
Short: "Search for packages on Docker Hub",
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) < 1 {
return cmd.Help()
}
if len(args) > 1 {
return fmt.Errorf("Only one search term is supported")
}
cli, err := client.NewEnvClient()
if err != nil {
return err
}
term := "whalebrew/" + args[0]
options := types.ImageSearchOptions{Limit: 100}
results, err := cli.ImageSearch(context.Background(), term, options)
if err != nil {
return err
}
for _, res := range results {
fmt.Println(res.Name)
}
return nil
},
}
|
Use throw instead of reject when possible
|
import fs from 'fs';
import crypto from 'crypto';
import multihash from 'multihashes';
import bs58 from 'bs58';
export const HASH_MAP = {
sha1: 'sha1',
sha256: 'sha2-256',
sha512: 'sha2-512'
};
export default function hashFile(input, algorithm) {
return new Promise((resolve, reject) => {
const algorithmName = HASH_MAP[algorithm];
if (typeof algorithmName === 'undefined') {
throw new Error('Unsupported algorithm: ' + algorithm);
}
const hash = crypto.createHash(algorithm);
const reader = typeof input === 'string' ?
fs.createReadStream(input) :
input;
reader.on('error', reject);
reader.on('data', data => hash.update(data));
reader.on('end', () => {
const res = bs58.encode(multihash.encode(hash.digest(), algorithmName));
resolve(res);
});
});
}
|
import fs from 'fs';
import crypto from 'crypto';
import multihash from 'multihashes';
import bs58 from 'bs58';
export const HASH_MAP = {
sha1: 'sha1',
sha256: 'sha2-256',
sha512: 'sha2-512'
};
export default function hashFile(input, algorithm) {
return new Promise((resolve, reject) => {
const algorithmName = HASH_MAP[algorithm];
if (typeof algorithmName === 'undefined') {
reject(new Error('Unsupported algorithm: ' + algorithm));
return;
}
const hash = crypto.createHash(algorithm);
const reader = typeof input === 'string' ?
fs.createReadStream(input) :
input;
reader.on('error', reject);
reader.on('data', data => hash.update(data));
reader.on('end', () => {
const res = bs58.encode(multihash.encode(hash.digest(), algorithmName));
resolve(res);
});
});
}
|
Add ignore all events function
|
type LivEventHandler = (msgData: Object) => void;
export default class LiveEvents {
messageHandlers: Object;
constructor() {
this.messageHandlers = {};
}
emitSingle(msgType: string, msgData: Object) {
const handlers = this.messageHandlers[msgType] || [];
handlers.forEach(handler => {
handler(msgData);
});
}
emitWildcard(msgData: Object) {
const handlers = this.messageHandlers['*'] || [];
handlers.forEach(handler => {
handler(msgData);
});
}
emit(msgType: string, msgData: Object) {
this.emitSingle(msgType, msgData);
this.emitWildcard(msgData);
}
on(msgType: string, callback: LivEventHandler) {
if (!this.messageHandlers[msgType]) {
this.messageHandlers[msgType] = [callback];
} else {
this.messageHandlers[msgType].push(callback);
}
}
ignoreAll(msgType: string) {
delete this.messageHandlers[msgType];
}
}
|
type LivEventHandler = (msgData: Object) => void;
export default class LiveEvents {
messageHandlers: Object;
constructor() {
this.messageHandlers = {};
}
emitSingle(msgType: string, msgData: Object) {
const handlers = this.messageHandlers[msgType] || [];
handlers.forEach(handler => {
handler(msgData);
});
}
emitWildcard(msgData: Object) {
const handlers = this.messageHandlers['*'] || [];
handlers.forEach(handler => {
handler(msgData);
});
}
emit(msgType: string, msgData: Object) {
this.emitSingle(msgType, msgData);
this.emitWildcard(msgData);
}
on(msgType: string, callback: LivEventHandler) {
if (!this.messageHandlers[msgType]) {
this.messageHandlers[msgType] = [callback];
} else {
this.messageHandlers[msgType].push(callback);
}
}
}
|
Update link to IRC page
|
<article>
<h1>Welcome to laravel.io</h1>
<p>Laravel: Ins and Outs is a project created and maintained by the {{ HTML::link('http://laravel.io/irc', '#Laravel community on irc.freenode.net') }}. Our focus is to provide regular study topics that will grow our combined knowledge of the Laravel framework.</p>
<p>Join us here or on twitter {{ HTML::link('http://twitter.com/laravelio', '@laravelio') }} to participate in a global study group where we focus on two digestible topics per week.</p>
<section class="recent-topics">
RECENT TOPICS
</section>
<ul class="latest">
@foreach($recent_topics as $topic)
<li>
<time>{{ $topic->short_published_date }} -</time>
@if($topic->author)
<span>{{ HTML::image($topic->author->image(16)) }}
@endif
- </span>
{{ $topic->link }}
</li>
@endforeach
</ul>
</article>
|
<article>
<h1>Welcome to laravel.io</h1>
<p>Laravel: Ins and Outs is a project created and maintained by the {{ HTML::link('http://laravel.com/irc', '#Laravel community on irc.freenode.net') }}. Our focus is to provide regular study topics that will grow our combined knowledge of the Laravel framework.</p>
<p>Join us here or on twitter {{ HTML::link('http://twitter.com/laravelio', '@laravelio') }} to participate in a global study group where we focus on two digestible topics per week.</p>
<section class="recent-topics">
RECENT TOPICS
</section>
<ul class="latest">
@foreach($recent_topics as $topic)
<li>
<time>{{ $topic->short_published_date }} -</time>
@if($topic->author)
<span>{{ HTML::image($topic->author->image(16)) }}
@endif
- </span>
{{ $topic->link }}
</li>
@endforeach
</ul>
</article>
|
Fix browsertesting tests behaving differently on different browsers
|
describe('admin add contexts', function() {
it('should add new contexts', function() {
var deferred = protractor.promise.defer();
browser.setLocation('admin/contexts');
var add_context = function(context) {
element(by.model('new_context.name')).sendKeys(context);
return element(by.css('[data-ng-click="add_context()"]')).click();
};
element(by.css('.actionButtonContextEdit')).click().then(function() {
element(by.id('context-0')).element(by.css('.actionButtonAdvancedSettings')).click().then(function() {
element(by.id('context-0')).element(by.model('context.show_receivers')).click().then(function() {
element(by.id('context-0')).element(by.css('.actionButtonContextSave')).click().then(function() {
add_context('Context 2').then(function() {
add_context('Context 3');
deferred.fulfill();
});
});
});
});
});
return deferred;
});
});
|
describe('admin add contexts', function() {
it('should add new contexts', function() {
var deferred = protractor.promise.defer();
browser.setLocation('admin/contexts');
var add_context = function(context) {
element(by.model('new_context.name')).sendKeys(context);
return element(by.css('[data-ng-click="add_context()"]')).click();
};
element(by.id('context-0')).click().then(function() {
element(by.id('context-0')).element(by.css('.actionButtonAdvancedSettings')).click().then(function() {
element(by.id('context-0')).element(by.model('context.show_receivers')).click().then(function() {
element(by.id('context-0')).element(by.css('.actionButtonContextSave')).click().then(function() {
add_context('Context 2').then(function() {
add_context('Context 3');
deferred.fulfill();
});
});
});
});
});
return deferred;
});
});
|
Add only() option for filtering clients for a broadcast
|
var EventEmitter = require('events').EventEmitter;
function ClientPool(){
var list = {};
var client_pool = this;
this.list = list;
this.count = 0;
//called in the context of the client (this = client)
this._on_client_disconnect = function(){
client_pool.remove(this);
}
}
var proto = ClientPool.prototype = new EventEmitter();;
proto.add = function(client){
this.list[client.sessionId] = client;
this.count++;
this.emit('added', client);
client.on('disconnect', this._on_client_disconnect);
};
proto.remove = function(client){
delete this.list[client.sessionId];
this.count--;
};
proto.broadcast = function(msg, options){
var except_client, only;
if(options){
if(options.meta_data)
except_client = options;
else
only = options.only;
}
var list = this.list;
for(var id in list){
var client = list[id];
if(except_client && (except_client == client)) continue;
if(only && !only(client)) continue;
client.send(msg);
}
};
exports.ClientPool = ClientPool;
|
var EventEmitter = require('events').EventEmitter;
function ClientPool(){
var list = {};
var client_pool = this;
this.list = list;
this.count = 0;
//called in the context of the client (this = client)
this._on_client_disconnect = function(){
client_pool.remove(this);
}
}
var proto = ClientPool.prototype = new EventEmitter();;
proto.add = function(client){
this.list[client.sessionId] = client;
this.count++;
this.emit('added', client);
client.on('disconnect', this._on_client_disconnect);
};
proto.remove = function(client){
delete this.list[client.sessionId];
this.count--;
};
proto.broadcast = function(msg, except){
var list = this.list;
for(var id in list){
var client = list[id];
if(except == client) continue;
client.send(msg);
}
};
exports.ClientPool = ClientPool;
|
Add DIR to HOME
* Add .pyrosar directory to HOME-path.
|
from setuptools import setup, find_packages
import os
# Create .pyrosar in HOME - Directory
directory = os.path.join(os.path.expanduser("~"), '.pyrosar')
if not os.path.exists(directory):
os.makedirs(directory)
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
from setuptools import setup, find_packages
setup(name='pyroSAR',
packages=find_packages(),
include_package_data=True,
version='0.1',
description='a framework for large-scale SAR satellite data processing',
classifiers=[
'Programming Language :: Python :: 2.7',
],
install_requires=['progressbar==2.3',
'pathos>=0.2',
'numpy',
'scoop'],
url='https://github.com/johntruckenbrodt/pyroSAR.git',
author='John Truckenbrodt',
author_email='john.truckenbrodt@uni-jena.de',
license='MIT',
zip_safe=False)
|
Clarify tusks solenoid on slot 2
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Tusks extends Subsystem {
Solenoid solenoidExtend;
Solenoid solenoidRetract;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public Tusks() {
// In "2nd" cRio slot, or 4th physical
solenoidExtend = new Solenoid(2, RobotMap.TUSKS_SOLENOID_EXTEND);
solenoidRetract = new Solenoid(2, RobotMap.TUSKS_SOLENOID_RETRACT);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void extend() {
solenoidExtend.set(true);
solenoidRetract.set(false);
}
public void retract() {
solenoidRetract.set(true);
solenoidExtend.set(false);
}
public boolean isExtended() {
return solenoidExtend.get();
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package edu.stuy.subsystems;
import edu.stuy.RobotMap;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
/**
*
* @author Kevin Wang
*/
public class Tusks extends Subsystem {
Solenoid solenoidExtend;
Solenoid solenoidRetract;
// Put methods for controlling this subsystem
// here. Call these from Commands.
public Tusks() {
solenoidExtend = new Solenoid(2, RobotMap.TUSKS_SOLENOID_EXTEND);
solenoidRetract = new Solenoid(2, RobotMap.TUSKS_SOLENOID_RETRACT);
}
public void initDefaultCommand() {
// Set the default command for a subsystem here.
//setDefaultCommand(new MySpecialCommand());
}
public void extend() {
solenoidExtend.set(true);
solenoidRetract.set(false);
}
public void retract() {
solenoidRetract.set(true);
solenoidExtend.set(false);
}
public boolean isExtended() {
return solenoidExtend.get();
}
}
|
Change $Identity so that it can be used as part of an html identifier
|
/* eslint no-unused-vars: 0 */
/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
watches: ['data', 'columns'],
runs: function (options) {
if (!options.model.ui.selectable) {
return;
}
if (options.model.logging) {
console.log('Calculating row identities');
}
var identityColumns = options.model.columns.filter(function (col) {
return col.isIdentity;
}).sort(function (colA, colB) {
return colA.id < colB.id ? -1 : 1;
});
options.model.data.forEach(function (row) {
var identity = identityColumns.reduce(function (total, col) {
return total + '_' + getCellData(row, col);
}, '');
row.$identity = identity.replace(/[\s\.\@\+\-\|]/g, "");
});
// todo calculate identities
}
};
function getCellData(row, col) {
return row[col.id];
}
|
/* eslint no-unused-vars: 0 */
/***********************************/
/** data-calculate-row-identities **/
/***********************************/
gridState.processors['data-calculate-row-identities'] = {
watches: ['data', 'columns'],
runs: function (options) {
if (!options.model.ui.selectable) {
return;
}
if (options.model.logging) {
console.log('Calculating row identities');
}
var identityColumns = options.model.columns.filter(function (col) {
return col.isIdentity;
}).sort(function (colA, colB) {
return colA.id < colB.id ? -1 : 1;
});
options.model.data.forEach(function (row) {
var identity = identityColumns.reduce(function (total, col) {
return total + '$' + getCellData(row, col);
}, '');
row.$identity = identity;
});
// todo calculate identities
}
};
function getCellData(row, col) {
return row[col.id];
}
|
Throw undefined error more friendly
|
import { helper } from 'ember-helper'
import { defaultLocale, changeLocale, localeHasBeenChanged } from '../utils/locale'
import generateImageURL from '../utils/image'
import faker from 'faker'
faker.locale = defaultLocale
export function fake([signature, ...args], {parse = false, locale, ...opts}) {
// running in node environment w/ fastboot server
if ('undefined' !== typeof FastBoot // eslint-disable-line
// and not to trying to generate an image URL
&& (signature && !/^image/i.test(signature))) return ''
if (!signature) throw new Error(faker.fake())
if (localeHasBeenChanged || locale) changeLocale(faker, locale)
if (parse) {
return faker.fake(signature.replace(/\[/g, '{{').replace(/\]/g, '}}'))
} else {
const [namespace, method] = signature.split('.')
if ('image' === namespace && 'unsplash' === method) {
return generateImageURL([namespace, method, ...args], opts)
}
try {
return faker[namespace][method].apply(null, args)
} catch (error) {
if ("Cannot read property 'apply' of undefined" === error.message) {
throw new ReferenceError(`${namespace}.${method} 不是有效的 faker 方法名称`)
}
throw new Error(error)
}
}
}
export default helper(fake)
|
import { helper } from 'ember-helper'
import { defaultLocale, changeLocale, localeHasBeenChanged } from '../utils/locale'
import generateImageURL from '../utils/image'
import faker from 'faker'
faker.locale = defaultLocale
export function fake([signature, ...args], {parse = false, locale, ...opts}) {
// running in node environment w/ fastboot server
if ('undefined' !== typeof FastBoot // eslint-disable-line
// and not to trying to generate an image URL
&& (signature && !/^image/i.test(signature))) return ''
if (!signature) throw new Error(faker.fake())
if (localeHasBeenChanged || locale) changeLocale(faker, locale)
if (parse) {
return faker.fake(signature.replace(/\[/g, '{{').replace(/\]/g, '}}'))
} else {
const [namespace, method] = signature.split('.')
if ('image' === namespace && 'unsplash' === method) {
return generateImageURL([namespace, method, ...args], opts)
}
return faker[namespace][method].apply(null, args)
}
}
export default helper(fake)
|
Enable SASI indexes when running mapper tests against C* 4
|
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.testinfra.ccm;
import com.datastax.oss.driver.api.core.Version;
public class DefaultCcmBridgeBuilderCustomizer {
public static CcmBridge.Builder configureBuilder(CcmBridge.Builder builder) {
if (!CcmBridge.DSE_ENABLEMENT
&& CcmBridge.VERSION.nextStable().compareTo(Version.V4_0_0) >= 0) {
builder.withCassandraConfiguration("enable_materialized_views", true);
builder.withCassandraConfiguration("enable_sasi_indexes", true);
}
return builder;
}
}
|
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datastax.oss.driver.api.testinfra.ccm;
import com.datastax.oss.driver.api.core.Version;
public class DefaultCcmBridgeBuilderCustomizer {
public static CcmBridge.Builder configureBuilder(CcmBridge.Builder builder) {
if (!CcmBridge.DSE_ENABLEMENT && CcmBridge.VERSION.compareTo(Version.V4_0_0) >= 0) {
builder.withCassandraConfiguration("enable_materialized_views", true);
}
return builder;
}
}
|
Hide window by hotkey if it is visible
|
import { BrowserWindow, globalShortcut } from 'electron';
import {
INPUT_HEIGHT,
WINDOW_WIDTH,
RESULT_HEIGHT,
MIN_VISIBLE_RESULTS
} from './constants/ui';
import buildMenu from './createWindow/buildMenu';
export default (url) => {
const mainWindow = new BrowserWindow({
alwaysOnTop: true,
show: false,
width: WINDOW_WIDTH,
minWidth: WINDOW_WIDTH,
maxWidth: WINDOW_WIDTH,
height: INPUT_HEIGHT,
minHeight: INPUT_HEIGHT + RESULT_HEIGHT * MIN_VISIBLE_RESULTS,
frame: false,
resizable: false
});
mainWindow.loadURL(url);
if (process.env.NODE_ENV !== 'development') {
// Hide window on blur in production move
// In development we usually use developer tools
mainWindow.on('blur', () => mainWindow.hide());
}
// const HOTKEY = 'Cmd+Alt+Shift+Control+Space';
const HOTKEY = 'Control+Space';
globalShortcut.register(HOTKEY, () => {
if (mainWindow.isVisible()) {
mainWindow.hide();
} else {
mainWindow.show();
mainWindow.focus();
}
});
buildMenu(mainWindow);
return mainWindow;
}
|
import { BrowserWindow, globalShortcut } from 'electron';
import {
INPUT_HEIGHT,
WINDOW_WIDTH,
RESULT_HEIGHT,
MIN_VISIBLE_RESULTS
} from './constants/ui';
import buildMenu from './createWindow/buildMenu';
export default (url) => {
const mainWindow = new BrowserWindow({
alwaysOnTop: true,
show: false,
width: WINDOW_WIDTH,
minWidth: WINDOW_WIDTH,
maxWidth: WINDOW_WIDTH,
height: INPUT_HEIGHT,
minHeight: INPUT_HEIGHT + RESULT_HEIGHT * MIN_VISIBLE_RESULTS,
frame: false,
resizable: false
});
mainWindow.loadURL(url);
if (process.env.NODE_ENV !== 'development') {
// Hide window on blur in production move
// In development we usually use developer tools
mainWindow.on('blur', () => mainWindow.hide());
}
// const HOTKEY = 'Cmd+Alt+Shift+Control+Space';
const HOTKEY = 'Control+Space';
globalShortcut.register(HOTKEY, () => {
mainWindow.show();
mainWindow.focus();
});
buildMenu(mainWindow);
return mainWindow;
}
|
Move proxyRes out of request handler; trap errors
|
var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization"
};
var proxy = httpProxy.createProxyServer();
// Add CORS headers to every other request also.
proxy.on('proxyRes', function(proxyRes, req, res) {
for (var key in CORS_HEADERS) {
proxyRes.headers[key] = CORS_HEADERS[key];
}
});
proxy.on('error', function(err, req, res) {
console.log(err);
var json = { error: 'proxy_error', reason: err.message };
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
res.end(JSON.stringify(json));
});
http.createServer(function(req, res) {
if (req.method === 'OPTIONS') {
// Respond to OPTIONS requests advertising we support full CORS for *
res.writeHead(200, CORS_HEADERS);
res.end();
return
}
// Remove our original host so it doesn't mess up Google's header parsing.
delete req.headers.host;
proxy.web(req, res, {
target: 'https://spreadsheets.google.com:443',
xfwd: false
});
}).listen(process.env.PORT || 5000);
|
var httpProxy = require('http-proxy');
var http = require('http');
var CORS_HEADERS = {
'access-control-allow-origin': '*',
'access-control-allow-methods': 'HEAD, POST, GET, PUT, PATCH, DELETE',
'access-control-max-age': '86400',
'access-control-allow-headers': "X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization"
};
var proxy = httpProxy.createProxyServer();
http.createServer(function(req, res) {
if (req.method === 'OPTIONS') {
// Respond to OPTIONS requests advertising we support full CORS for *
res.writeHead(200, CORS_HEADERS);
res.end();
return
}
// Remove our original host so it doesn't mess up Google's header parsing.
delete req.headers.host;
proxy.web(req, res, {
target: 'https://spreadsheets.google.com:443',
xfwd: false
});
// Add CORS headers to every other request also.
proxy.on('proxyRes', function(proxyRes, req, res) {
for (var key in CORS_HEADERS) {
proxyRes.headers[key] = CORS_HEADERS[key];
}
});
}).listen(process.env.PORT || 5000);
|
Stop using soft ipmi resets until figuring out why it does not work in a lot of cases
|
import time
import logging
import multiprocessing.pool
from rackattack.physical.ipmi import IPMI
class ColdReclaim:
_CONCURRENCY = 8
_pool = None
def __init__(self, hostname, username, password, hardReset):
self._hostname = hostname
self._username = username
self._password = password
self._hardReset = hardReset
if ColdReclaim._pool is None:
ColdReclaim._pool = multiprocessing.pool.ThreadPool(self._CONCURRENCY)
ColdReclaim._pool.apply_async(self._run)
def _run(self):
ipmi = IPMI(self._hostname, self._username, self._password)
try:
ipmi.powerCycle()
# if self._hardReset == "True":
# ipmi.powerCycle()
# else:
# ipmi.softReset()
except:
logging.exception("Unable to reclaim by cold restart '%(hostname)s'",
dict(hostname=self._hostname))
|
import time
import logging
import multiprocessing.pool
from rackattack.physical.ipmi import IPMI
class ColdReclaim:
_CONCURRENCY = 8
_pool = None
def __init__(self, hostname, username, password, hardReset):
self._hostname = hostname
self._username = username
self._password = password
self._hardReset = hardReset
if ColdReclaim._pool is None:
ColdReclaim._pool = multiprocessing.pool.ThreadPool(self._CONCURRENCY)
ColdReclaim._pool.apply_async(self._run)
def _run(self):
ipmi = IPMI(self._hostname, self._username, self._password)
try:
if self._hardReset == "True":
ipmi.powerCycle()
else:
ipmi.softReset()
except:
logging.exception("Unable to reclaim by cold restart '%(hostname)s'",
dict(hostname=self._hostname))
|
Fix config variable exposing to global scope
|
/**
* Simple wrapper to wrap around the Cacheman nodejs package to integrate easily with SailsJS for caching.
* @param {[string]} name Name the Cache Instance.
*/
var Cache = function (name) {
var Cacheman = require('cacheman');
var _ = require('underscore');
var options = {};
// Get configuration
var config = sails.config.cacheman;
if (config === undefined) {
throw new Error('No configuration file found. Please add the configuration app/config/cacheman.js');
}
// if a valid driver is selected.
if(_.indexOf(['memory', 'redis', 'mongo', 'file'], config.driver) < 0) {
throw new Error("Invalid Driver selected. Please choose from ('memory', 'redis', 'mongo', 'file')");
}
var cache = new Cacheman(name, config[config.driver]);
return cache;
};
module.exports = Cache;
|
/**
* Simple wrapper to wrap around the Cacheman nodejs package to integrate easily with SailsJS for caching.
* @param {[string]} name Name the Cache Instance.
*/
var Cache = function (name) {
var Cacheman = require('cacheman');
var _ = require('underscore');
var options = {};
// Get configuration
config = sails.config.cacheman;
if (config === undefined) {
throw new Error('No configuration file found. Please add the configuration app/config/cacheman.js');
}
// if a valid driver is selected.
if(_.indexOf(['memory', 'redis', 'mongo', 'file'], config.driver) < 0) {
throw new Error("Invalid Driver selected. Please choose from ('memory', 'redis', 'mongo', 'file')");
}
var cache = new Cacheman(name, config[config.driver]);
return cache;
};
module.exports = Cache;
|
Remove duplicate addFiles in test-in-browser
This actually resulted in two copies of diff_match_patch in the package!
|
Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.7',
documentation: null
});
Package.onUse(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap@1.0.1');
api.use('underscore');
api.use('session');
api.use('reload');
api.use(['blaze', 'templating', 'spacebars',
'ddp', 'tracker'], 'client');
api.addFiles('diff_match_patch_uncompressed.js', 'client');
api.addFiles([
'driver.css',
'driver.html',
'driver.js'
], "client");
api.use('autoupdate', 'server', {weak: true});
api.use('random', 'server');
api.addFiles('autoupdate.js', 'server');
});
|
Package.describe({
summary: "Run tests interactively in the browser",
version: '1.0.7',
documentation: null
});
Package.onUse(function (api) {
// XXX this should go away, and there should be a clean interface
// that tinytest and the driver both implement?
api.use('tinytest');
api.use('bootstrap@1.0.1');
api.use('underscore');
api.use('session');
api.use('reload');
api.use(['blaze', 'templating', 'spacebars',
'ddp', 'tracker'], 'client');
api.addFiles('diff_match_patch_uncompressed.js', 'client');
api.addFiles('diff_match_patch_uncompressed.js', 'client');
api.addFiles([
'driver.css',
'driver.html',
'driver.js'
], "client");
api.use('autoupdate', 'server', {weak: true});
api.use('random', 'server');
api.addFiles('autoupdate.js', 'server');
});
|
Change RemindableInterface to correct namespace
|
<?php namespace Analogue\LaravelAuth;
use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Entity implements UserInterface, RemindableInterface {
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->id;
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->{$this->getRememberTokenName()};
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->{$this->getRememberTokenName()} = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
}
|
<?php namespace Analogue\LaravelAuth;
use Analogue\ORM\Entity;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\RemindableInterface;
class User extends Entity implements UserInterface, RemindableInterface {
/**
* Get the unique identifier for the user.
*
* @return mixed
*/
public function getAuthIdentifier()
{
return $this->id;
}
/**
* Get the password for the user.
*
* @return string
*/
public function getAuthPassword()
{
return $this->password;
}
/**
* Get the token value for the "remember me" session.
*
* @return string
*/
public function getRememberToken()
{
return $this->{$this->getRememberTokenName()};
}
/**
* Set the token value for the "remember me" session.
*
* @param string $value
* @return void
*/
public function setRememberToken($value)
{
$this->{$this->getRememberTokenName()} = $value;
}
/**
* Get the column name for the "remember me" token.
*
* @return string
*/
public function getRememberTokenName()
{
return 'remember_token';
}
}
|
Fix NodeJS shim in Vector2 file
|
function Vector2(x, y) {
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot add '" + other + "'' to '" + this + "'!");
return new Vector2(this.x + other.x, this.y + other.y);
};
Vector2.prototype.subtract = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot subtract '" + other + "'' from '" + this + "'!");
return new Vector2(this.x - other.x, this.y - other.y);
};
Vector2.prototype.equals = function(other) {
return ((other instanceof Vector2) && (this.x == other.x) && (this.y == other.y));
};
Vector2.prototype.toString = function() {
return this.constructor.name + "(" + this.x + ", " + this.y + ")";
};
// For NodeJS
if (typeof exports == "undefined") exports = {};
exports.Vector2 = Vector2;
|
function Vector2(x, y) {
this.x = x;
this.y = y;
}
Vector2.prototype.add = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot add '" + other + "'' to '" + this + "'!");
return new Vector2(this.x + other.x, this.y + other.y);
};
Vector2.prototype.subtract = function(other) {
if (!(other instanceof Vector2)) throw new TypeError("Cannot subtract '" + other + "'' from '" + this + "'!");
return new Vector2(this.x - other.x, this.y - other.y);
};
Vector2.prototype.equals = function(other) {
return ((other instanceof Vector2) && (this.x == other.x) && (this.y == other.y));
};
Vector2.prototype.toString = function() {
return this.constructor.name + "(" + this.x + ", " + this.y + ")";
};
// For NodeJS
if (exports === undefined) exports = {};
exports.Vector2 = Vector2;
|
Add test case for svg() (like h() is)
|
'use strict';
/* global describe, it */
let assert = require('assert');
let Cycle = require('../../src/cycle');
describe('Cycle', function () {
describe('API', function () {
it('should have `applyToDOM`', function () {
assert.strictEqual(typeof Cycle.applyToDOM, 'function');
});
it('should have `renderAsHTML`', function () {
assert.strictEqual(typeof Cycle.renderAsHTML, 'function');
});
it('should have `registerCustomElement`', function () {
assert.strictEqual(typeof Cycle.registerCustomElement, 'function');
});
it('should have a shortcut to Rx', function () {
assert.strictEqual(typeof Cycle.Rx, 'object');
});
it('should have a shortcut to virtual-hyperscript', function () {
assert.strictEqual(typeof Cycle.h, 'function');
});
it('should have a shortcut to virtual-dom\'s svg', function () {
assert.strictEqual(typeof Cycle.svg, 'function');
});
});
});
|
'use strict';
/* global describe, it */
let assert = require('assert');
let Cycle = require('../../src/cycle');
describe('Cycle', function () {
describe('API', function () {
it('should have `applyToDOM`', function () {
assert.strictEqual(typeof Cycle.applyToDOM, 'function');
});
it('should have `renderAsHTML`', function () {
assert.strictEqual(typeof Cycle.renderAsHTML, 'function');
});
it('should have `registerCustomElement`', function () {
assert.strictEqual(typeof Cycle.registerCustomElement, 'function');
});
it('should have a shortcut to Rx', function () {
assert.strictEqual(typeof Cycle.Rx, 'object');
});
it('should have a shortcut to virtual-hyperscript', function () {
assert.strictEqual(typeof Cycle.h, 'function');
});
});
});
|
Remove phase from project factory
|
import factory
import logging
from django.conf import settings
from bluebottle.projects.models import (
Project, ProjectTheme, ProjectDetailField, ProjectBudgetLine)
from .accounts import BlueBottleUserFactory
# Suppress debug information for Factory Boy
logging.getLogger('factory').setLevel(logging.WARN)
class ProjectFactory(factory.DjangoModelFactory):
FACTORY_FOR = Project
owner = factory.SubFactory(BlueBottleUserFactory)
title = factory.Sequence(lambda n: 'Project_{0}'.format(n))
class ProjectThemeFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectTheme
name = factory.Sequence(lambda n: 'Theme_{0}'.format(n))
name_nl = name
slug = name
description = 'ProjectTheme factory model'
class ProjectDetailFieldFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectDetailField
name = factory.Sequence(lambda n: 'Field_{0}'.format(n))
description = 'DetailField factory model'
slug = name
type = 'text'
class ProjectBudgetLineFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectBudgetLine
project = factory.SubFactory(ProjectFactory)
amount = 100000
|
import factory
import logging
from django.conf import settings
from bluebottle.projects.models import (
Project, ProjectTheme, ProjectDetailField, ProjectBudgetLine)
from .accounts import BlueBottleUserFactory
# Suppress debug information for Factory Boy
logging.getLogger('factory').setLevel(logging.WARN)
class ProjectFactory(factory.DjangoModelFactory):
FACTORY_FOR = Project
owner = factory.SubFactory(BlueBottleUserFactory)
phase = settings.PROJECT_PHASES[0][1][0][0]
title = factory.Sequence(lambda n: 'Project_{0}'.format(n))
class ProjectThemeFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectTheme
name = factory.Sequence(lambda n: 'Theme_{0}'.format(n))
name_nl = name
slug = name
description = 'ProjectTheme factory model'
class ProjectDetailFieldFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectDetailField
name = factory.Sequence(lambda n: 'Field_{0}'.format(n))
description = 'DetailField factory model'
slug = name
type = 'text'
class ProjectBudgetLineFactory(factory.DjangoModelFactory):
FACTORY_FOR = ProjectBudgetLine
project = factory.SubFactory(ProjectFactory)
amount = 100000
|
Save compressed files to a different directory
|
var gulp = require('gulp')
, concat = require('gulp-concat')
, uglify = require('gulp-uglify');
gulp.task('compress-css', function () {
gulp.src([
"public/css/leaflet.css",
"public/css/bootstrap.min.css",
"public/css/main.css"
])
.pipe(concat('build.css'))
.pipe(gulp.dest('public/dist/'));
});
gulp.task('compress-js', function () {
gulp.src([
"public/js/leaflet.js",
"public/js/polyline.js",
"public/js/underscore-min.js",
"public/js/moment.min.js",
"public/js/per_date.js",
"public/js/main.js",
])
.pipe(uglify())
.pipe(concat('build.js'))
.pipe(gulp.dest('public/dist/'));
});
gulp.task('watch', function() {
gulp.watch('public/css/*.css', ['compress-css']);
gulp.watch('public/js/*.js', ['compress-js']);
})
gulp.task('default', [
'watch'
]);
|
var gulp = require('gulp')
, concat = require('gulp-concat')
, uglify = require('gulp-uglify');
gulp.task('compress-css', function () {
gulp.src([
"public/css/leaflet.css",
"public/css/bootstrap.min.css",
"public/css/main.css"
])
.pipe(concat('build.css'))
.pipe(gulp.dest('public/css'));
});
gulp.task('compress-js', function () {
gulp.src([
"public/js/leaflet.js",
"public/js/polyline.js",
"public/js/underscore-min.js",
"public/js/moment.min.js",
"public/js/per_date.js",
"public/js/main.js",
])
.pipe(uglify())
.pipe(concat('build.js'))
.pipe(gulp.dest('public/js/'));
});
gulp.task('watch', function() {
gulp.watch('public/css/*.css', ['compress-css']);
gulp.watch('public/js/*.js', ['compress-js']);
})
gulp.task('default', [
'watch'
]);
|
Allow formSelector directive as attribute
|
"use strict";
angular.module('arethusa.morph').directive('formSelector', function() {
return {
restrict: 'AE',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.selected = function() {
return $scope.plugin.isFormSelected(id, form);
};
$scope.text = function() {
return $scope.selected() ? 'Deselect' : 'Select';
};
$scope.action = function(event) {
event.stopPropagation();
if ($scope.selected()) {
$scope.plugin.unsetState(id);
} else {
$scope.plugin.setState(id, form);
}
};
},
template: '<span ng-click="action($event)">{{ text() }}</span>'
};
});
|
"use strict";
angular.module('arethusa.morph').directive('formSelector', function() {
return {
restrict: 'E',
replace: true,
controller: function($scope, $element, $attrs) {
var id = $scope.id;
var form = $scope.form;
$scope.selected = function() {
return $scope.plugin.isFormSelected(id, form);
};
$scope.text = function() {
return $scope.selected() ? 'Deselect' : 'Select';
};
$scope.action = function(event) {
event.stopPropagation();
if ($scope.selected()) {
$scope.plugin.unsetState(id);
} else {
$scope.plugin.setState(id, form);
}
};
},
template: '<span ng-click="action($event)">{{ text() }}</span>'
};
});
|
Remove placeholders in the controller arrays
|
'use strict';
var kanjiApp = angular.module('kanjiApp', []);
kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
$scope.saved = [];
$scope.findKanji = search.findKanji;
$scope.findWords = search.findWords;
$scope.getKanjiMeaning = kanjiDictionary.getMeaning;
$scope.wordSearchResults = [];
$scope.kanjiSearchResults = [];
$scope.updateSearchResults = function(query) {
search.findKanji($scope.query).then(function(results) {
console.log("Inside kanji callback");
$scope.kanjiSearchResults = results;
console.log($scope.kanjiSearchResults);
});
search.findWords($scope.query).then(function(results) {
console.log("Inside words callback");
$scope.wordSearchResults = results;
console.log($scope.wordSearchResults);
});
};
$scope.searchDisabled = true;
search.onReady(function() {
console.log("Enabling search");
$scope.searchDisabled = false;
});
}]);
|
'use strict';
var kanjiApp = angular.module('kanjiApp', []);
kanjiApp.controller('KanjiCtrl', ['$scope', 'search', 'kanjiDictionary', function($scope, search, kanjiDictionary) {
$scope.saved = ["blah"];
$scope.findKanji = search.findKanji;
$scope.findWords = search.findWords;
$scope.getKanjiMeaning = kanjiDictionary.getMeaning;
$scope.wordSearchResults = ["happy"];
$scope.kanjiSearchResults = ["日"];
$scope.updateSearchResults = function(query) {
search.findKanji($scope.query).then(function(results) {
console.log("Inside kanji callback");
$scope.kanjiSearchResults = results;
console.log($scope.kanjiSearchResults);
});
search.findWords($scope.query).then(function(results) {
console.log("Inside words callback");
$scope.wordSearchResults = results;
console.log($scope.wordSearchResults);
});
};
$scope.searchDisabled = true;
search.onReady(function() {
console.log("Enabling search");
$scope.searchDisabled = false;
});
}]);
|
Use shortcut instead of an ID as a key.
|
import './Gallery.scss';
import React, { Component, PropTypes } from 'react';
import Image from './Image.react';
import map from 'lodash/collection/map';
import AssetSchema from '../schemas/asset';
import BaguetteBox from 'baguettebox.js';
class Gallery extends Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
BaguetteBox.run('.image header', {
// Pick up all links from the header no matter what the href is holding.
filter: /.+/i,
});
}
componentWillUnmount() {
BaguetteBox.destroy();
}
renderAssetCollection() {
return map(this.props.assets, (asset) =>
<Image {...asset} key={asset.shortcut}/>
);
}
render() {
return (
<section className="gallery">
{this.renderAssetCollection()}
</section>
);
}
}
Gallery.propTypes = {
assets: PropTypes.arrayOf(PropTypes.shape(AssetSchema)).isRequired,
};
export default Gallery;
|
import './Gallery.scss';
import React, { Component, PropTypes } from 'react';
import Image from './Image.react';
import map from 'lodash/collection/map';
import AssetSchema from '../schemas/asset';
import BaguetteBox from 'baguettebox.js';
class Gallery extends Component {
constructor(props, context) {
super(props, context);
}
componentDidMount() {
BaguetteBox.run('.image header', {
// Pick up all links from the header no matter what the href is holding.
filter: /.+/i,
});
}
componentWillUnmount() {
BaguetteBox.destroy();
}
renderAssetCollection() {
return map(this.props.assets, (asset) =>
<Image {...asset} key={asset.id}/>
);
}
render() {
return (
<section className="gallery">
{this.renderAssetCollection()}
</section>
);
}
}
Gallery.propTypes = {
assets: PropTypes.arrayOf(PropTypes.shape(AssetSchema)),
};
export default Gallery;
|
Support multi-db for user creation signal
|
from __future__ import absolute_import, print_function
from django.db import router
from django.db.models.signals import post_syncdb
from sentry.models import User
def create_first_user(app, created_models, verbosity, db, **kwargs):
if User not in created_models:
return
if not router.allow_syncdb(db, User):
return
if not kwargs.get('interactive', True):
return
import click
if not click.confirm('\nWould you like to create a user account now?', default=True):
# Not using `abort=1` because we don't want to exit out from further execution
click.echo('\nRun `sentry createuser` to do this later.\n')
return
from sentry.runner import call_command
call_command('sentry.runner.commands.createuser.createuser')
post_syncdb.connect(
create_first_user,
dispatch_uid="create_first_user",
weak=False,
)
|
from __future__ import absolute_import, print_function
from django.db.models.signals import post_syncdb
from sentry.models import User
def create_first_user(app, created_models, verbosity, db, **kwargs):
if User not in created_models:
return
if not kwargs.get('interactive', True):
return
import click
if not click.confirm('\nWould you like to create a user account now?', default=True):
# Not using `abort=1` because we don't want to exit out from further execution
click.echo('\nRun `sentry createuser` to do this later.\n')
return
from sentry.runner import call_command
call_command('sentry.runner.commands.createuser.createuser')
post_syncdb.connect(
create_first_user,
dispatch_uid="create_first_user",
weak=False,
)
|
Fix currency converter. Use multiply.
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\MoneyBundle\Converter;
use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface;
class CurrencyConverter implements CurrencyConverterInterface
{
protected $exchangeRateRepository;
private $cache;
public function __construct(RepositoryInterface $exchangeRateRepository)
{
$this->exchangeRateRepository = $exchangeRateRepository;
}
public function convert($value, $currency)
{
$exchangeRate = $this->getExchangeRate($currency);
if (null === $exchangeRate) {
return $value;
}
return $value * $exchangeRate->getRate();
}
private function getExchangeRate($currency)
{
if (isset($this->cache[$currency])) {
return $this->cache[$currency];
}
return $this->cache[$currency] = $this->exchangeRateRepository->findOneBy(array('currency' => $currency));
}
}
|
<?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sylius\Bundle\MoneyBundle\Converter;
use Sylius\Bundle\ResourceBundle\Model\RepositoryInterface;
class CurrencyConverter implements CurrencyConverterInterface
{
protected $exchangeRateRepository;
private $cache;
public function __construct(RepositoryInterface $exchangeRateRepository)
{
$this->exchangeRateRepository = $exchangeRateRepository;
}
public function convert($value, $currency)
{
$exchangeRate = $this->getExchangeRate($currency);
if (null === $exchangeRate) {
return $value;
}
return $value / $exchangeRate->getRate();
}
private function getExchangeRate($currency)
{
if (isset($this->cache[$currency])) {
return $this->cache[$currency];
}
return $this->cache[$currency] = $this->exchangeRateRepository->findOneBy(array('currency' => $currency));
}
}
|
Fix an issue with the Jasmine log not outputting the full string.
|
var vui = vui || {};
vui.matchers = vui.matchers || {};
vui.matchers.jasmine = {
toMatchRecordedObjectAt: function() {
return {
compare: function ( actual, recordedObjectPath, exceptions ) {
var expectedResult;
//@if !RECORDING
expectedResult = vui.records.getRecord(recordedObjectPath);
//@endif
//@if RECORDING
expectedResult = actual
vui.records.setRecord(recordedObjectPath, expectedResult);
//@endif
var diff = vui.differs.json.diffLogs( actual, expectedResult, exceptions );
var retStr = "";
for( d in diff ) {
retStr = retStr + "Expected " + d + " to be " + diff[d].expected + " but got " + diff[d].actual + "\n";
}
return {
pass: retStr == "",
message: retStr
};
}
};
}
};
|
var vui = vui || {};
vui.matchers = vui.matchers || {};
vui.matchers.jasmine = {
toMatchRecordedObjectAt: function() {
return {
compare: function ( actual, recordedObjectPath, exceptions ) {
var expectedResult;
//@if !RECORDING
expectedResult = vui.records.getRecord(recordedObjectPath);
//@endif
//@if RECORDING
expectedResult = actual
vui.records.setRecord(recordedObjectPath, expectedResult);
//@endif
var diff = vui.differs.json.diffLogs( actual, expectedResult, exceptions );
var retStr = "";
for( d in diff ) {
retStr = "Expected " + d + " to be " + diff[d].expected + " but got " + diff[d].actual;
}
return {
pass: retStr == "",
message: retStr
};
}
};
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.