text stringlengths 16 4.96k | positive stringlengths 321 2.24k | negative stringlengths 310 2.21k |
|---|---|---|
Handle responses without JSON or detail field
Check the response for JSON and a detail field before trying to access
them within SmartFileResponseException. This could occur if the server
returns a 500. | from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = u'{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
if not response.json or not 'detail' in response.json:
self.detail = u'Check response for errors'
else:
self.detail = response.json['detail']
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
| from requests.exceptions import ConnectionError
class SmartFileException(Exception):
pass
class SmartFileConnException(SmartFileException):
""" Exception for issues regarding a request. """
def __init__(self, exc, *args, **kwargs):
self.exc = exc
if isinstance(exc, ConnectionError):
self.detail = exc.message.strerror
else:
self.detail = '{0}: {1}'.format(exc.__class__, exc)
super(SmartFileConnException, self).__init__(*args, **kwargs)
def __str__(self):
return self.detail
class SmartFileResponseException(SmartFileException):
""" Exception for issues regarding a response. """
def __init__(self, response, *args, **kwargs):
self.response = response
self.status_code = response.status_code
self.detail = response.json.get('detail', 'Check response for errors')
super(SmartFileResponseException, self).__init__(*args, **kwargs)
def __str__(self):
return 'Response {0}: {1}'.format(self.status_code, self.detail)
|
Save the build log every time the log is updated. | <?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Logging;
use b8\Store\Factory;
use Monolog\Handler\AbstractProcessingHandler;
use PHPCI\Model\Build;
class BuildDBLogHandler extends AbstractProcessingHandler
{
/**
* @var Build
*/
protected $build;
protected $logValue;
public function __construct(
Build $build,
$level = LogLevel::INFO,
$bubble = true
) {
parent::__construct($level, $bubble);
$this->build = $build;
// We want to add to any existing saved log information.
$this->logValue = $build->getLog();
}
protected function write(array $record)
{
$message = (string)$record['message'];
$message = str_replace($this->build->currentBuildPath, '/', $message);
$this->logValue .= $message . PHP_EOL;
$this->build->setLog($this->logValue);
Factory::getStore('Build')->save($this->build);
}
}
| <?php
/**
* PHPCI - Continuous Integration for PHP
*
* @copyright Copyright 2014, Block 8 Limited.
* @license https://github.com/Block8/PHPCI/blob/master/LICENSE.md
* @link https://www.phptesting.org/
*/
namespace PHPCI\Logging;
use b8\Store;
use Monolog\Handler\AbstractProcessingHandler;
use PHPCI\Model\Build;
class BuildDBLogHandler extends AbstractProcessingHandler
{
/**
* @var Build
*/
protected $build;
protected $logValue;
public function __construct(
Build $build,
$level = LogLevel::INFO,
$bubble = true
) {
parent::__construct($level, $bubble);
$this->build = $build;
// We want to add to any existing saved log information.
$this->logValue = $build->getLog();
}
protected function write(array $record)
{
$message = (string)$record['message'];
$message = str_replace($this->build->currentBuildPath, '/', $message);
$this->logValue .= $message . PHP_EOL;
$this->build->setLog($this->logValue);
}
}
|
Add validation to error xml parse | var JSON5 = require('json5');
var xml2js = require('xml2js').parseString;
var lo = require("lodash");
var reader = function(query, callback){
xml2js("<root>" + query + "</root>", (err, result) => {
if(err){
callback({
head: {
"error": "Unable to parse JSON"
}
});
return;
}
var root = result.root;
var head = {};
try{
head = JSON5.parse(root.head[0]);
}
catch(ex){
head = {
"error": "Unable to parse JSON"
};
}
var script = "";
var labels = [];
var queries = [];
lo.forEach(root.Q, q => {
labels.push({
label: q.$.label,
index: q.$.i
});
queries.push({
index: q.$.i,
label: q.$.label,
script: q._
});
script += q._ + "\n";
});
callback({
head: head,
labels: lo.sortBy(labels, k=> k.index),
queries: lo.sortBy(queries, k=> k.index),
script: script
});
});
};
export default reader; | var JSON5 = require('json5');
var xml2js = require('xml2js').parseString;
var lo = require("lodash");
var reader = function(query, callback){
xml2js("<root>" + query + "</root>", (err, result) => {
var root = result.root;
var head = {};
try{
head = JSON5.parse(root.head[0]);
}
catch(ex){
head = {
"error": "Unable to parse JSON"
};
}
var script = "";
var labels = [];
var queries = [];
lo.forEach(root.Q, q => {
labels.push({
label: q.$.label,
index: q.$.i
});
queries.push({
index: q.$.i,
label: q.$.label,
script: q._
});
script += q._ + "\n";
});
callback({
head: head,
labels: lo.sortBy(labels, k=> k.index),
queries: lo.sortBy(queries, k=> k.index),
script: script
});
});
};
export default reader; |
Use setUp method for cache | <?php
use Flintstone\Cache\ArrayCache;
class ArrayCacheTest extends PHPUnit_Framework_TestCase
{
/**
* @var ArrayCache
*/
private $cache;
protected function setUp()
{
$this->cache = new ArrayCache();
}
public function testGetAndSet()
{
$this->cache->set('foo', 'bar');
$this->assertTrue($this->cache->contains('foo'));
$this->assertEquals('bar', $this->cache->get('foo'));
}
public function testDelete()
{
$this->cache->set('foo', 'bar');
$this->cache->delete('foo');
$this->assertFalse($this->cache->contains('foo'));
}
public function testFlush()
{
$this->cache->set('foo', 'bar');
$this->cache->flush();
$this->assertFalse($this->cache->contains('foo'));
}
}
| <?php
use Flintstone\Cache\ArrayCache;
class ArrayCacheTest extends PHPUnit_Framework_TestCase
{
public function testGetAndSet()
{
$cache = new ArrayCache();
$cache->set('foo', 'bar');
$this->assertTrue($cache->contains('foo'));
$this->assertEquals('bar', $cache->get('foo'));
}
public function testDelete()
{
$cache = new ArrayCache();
$cache->set('foo', 'bar');
$cache->delete('foo');
$this->assertFalse($cache->contains('foo'));
}
public function testFlush()
{
$cache = new ArrayCache();
$cache->set('foo', 'bar');
$cache->flush();
$this->assertFalse($cache->contains('foo'));
}
}
|
Remove deprecated jsondiff entry point. | import os
import re
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'jsondiff', '__init__.py')) as f:
version = re.compile(r".*__version__ = '(.*?)'", re.S).match(f.read()).group(1)
setup(
name='jsondiff',
packages=find_packages(exclude=['tests']),
version=version,
description='Diff JSON and JSON-like structures in Python',
author='Zoomer Analytics LLC',
author_email='eric.reynolds@zoomeranalytics.com',
url='https://github.com/ZoomerAnalytics/jsondiff',
keywords=['json', 'diff', 'diffing', 'difference', 'patch', 'delta', 'dict', 'LCS'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
entry_points={
'console_scripts': [
'jdiff=jsondiff.cli:main'
]
}
)
| import os
import re
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'jsondiff', '__init__.py')) as f:
version = re.compile(r".*__version__ = '(.*?)'", re.S).match(f.read()).group(1)
setup(
name='jsondiff',
packages=find_packages(exclude=['tests']),
version=version,
description='Diff JSON and JSON-like structures in Python',
author='Zoomer Analytics LLC',
author_email='eric.reynolds@zoomeranalytics.com',
url='https://github.com/ZoomerAnalytics/jsondiff',
keywords=['json', 'diff', 'diffing', 'difference', 'patch', 'delta', 'dict', 'LCS'],
classifiers=[
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
],
entry_points={
'console_scripts': [
'jsondiff=jsondiff.cli:main_deprecated',
'jdiff=jsondiff.cli:main'
]
}
)
|
Add comment to prompt changing of pepper | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# Change to a secret random string.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" | # -*- coding: utf-8 -*-
# Copyright 2015, 2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ._base import Config
class PasswordConfig(Config):
"""Password login configuration
"""
def read_config(self, config):
password_config = config.get("password_config", {})
self.password_enabled = password_config.get("enabled", True)
self.pepper = password_config.get("pepper", "")
def default_config(self, config_dir_path, server_name, **kwargs):
return """
# Enable password for login.
password_config:
enabled: true
# Uncomment for extra security for your passwords.
# DO NOT CHANGE THIS AFTER INITIAL SETUP!
#pepper: "HR32t0xZcQnzn3O0ZkEVuetdFvH1W6TeEPw6JjH0Cl+qflVOseGyFJlJR7ACLnywjN9"
""" |
Remove oblivious not used param. | <?php
namespace ivol;
use ivol\EventDispatcher\AfterExecuteEvent;
use ivol\EventDispatcher\BeforeExecuteEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ExecutionWrapper
{
/**
* @var EventDispatcher
*/
private $eventDispatcher;
public function __construct()
{
$this->eventDispatcher = new EventDispatcher();
}
/**
* @return EventDispatcher
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* @param string $command Sprintf formatted string @see http://php.net/manual/en/function.sprintf.php
* @param array $params
* @return Result
*/
public function exec($command, $params)
{
$beforeExecuteEvent = new BeforeExecuteEvent(new ExecParams($command, $params));
$this->eventDispatcher->dispatch(BeforeExecuteEvent::EVENT_NAME, $beforeExecuteEvent);
exec($beforeExecuteEvent->getParams()->getFullCommand(), $output, $returnValue);
$afterExecuteEvent = new AfterExecuteEvent(new Result($returnValue, $output));
$this->eventDispatcher->dispatch(AfterExecuteEvent::EVENT_NAME, $afterExecuteEvent);
return $afterExecuteEvent->getResult();
}
} | <?php
namespace ivol;
use ivol\EventDispatcher\AfterExecuteEvent;
use ivol\EventDispatcher\BeforeExecuteEvent;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ExecutionWrapper
{
/**
* @var EventDispatcher
*/
private $eventDispatcher;
/** @var array */
private $observers = array();
public function __construct()
{
$this->eventDispatcher = new EventDispatcher();
}
/**
* @return EventDispatcher
*/
public function getEventDispatcher()
{
return $this->eventDispatcher;
}
/**
* @param string $command Sprintf formatted string @see http://php.net/manual/en/function.sprintf.php
* @param array $params
* @return Result
*/
public function exec($command, $params)
{
$beforeExecuteEvent = new BeforeExecuteEvent(new ExecParams($command, $params));
$this->eventDispatcher->dispatch(BeforeExecuteEvent::EVENT_NAME, $beforeExecuteEvent);
exec($beforeExecuteEvent->getParams()->getFullCommand(), $output, $returnValue);
$afterExecuteEvent = new AfterExecuteEvent(new Result($returnValue, $output));
$this->eventDispatcher->dispatch(AfterExecuteEvent::EVENT_NAME, $afterExecuteEvent);
return $afterExecuteEvent->getResult();
}
} |
Make test task depend on lint task | // gulpfile.js
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var karma = require('gulp-karma');
var testFiles;
require('./.karma.js')({set: function (config) { testFiles = config['files']; }});
var exec = require('child_process').exec;
/**
* Lint source code and specs
*/
gulp.task('lint', function () {
return gulp.src(['./straw-ios.js', './straw-ios-spec.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
/**
* Run test using karma and output code coverage
*/
gulp.task('test', ['lint'], function () {
return gulp.src(testFiles).pipe(karma({
configFile: '.karma.js',
action: 'start'
})).on('error', function (err) {
throw err;
});
});
gulp.task('doc', function (cb) {
exec('jsduck', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('default', ['lint', 'test']);
| // gulpfile.js
var gulp = require('gulp');
var jshint = require('gulp-jshint');
var karma = require('gulp-karma');
var testFiles;
require('./.karma.js')({set: function (config) { testFiles = config['files']; }});
var exec = require('child_process').exec;
/**
* Lint source code and specs
*/
gulp.task('lint', function () {
return gulp.src(['./straw-ios.js', './straw-ios-spec.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
/**
* Run test using karma and output code coverage
*/
gulp.task('test', function () {
return gulp.src(testFiles).pipe(karma({
configFile: '.karma.js',
action: 'start'
})).on('error', function (err) {
throw err;
});
});
gulp.task('doc', function (cb) {
exec('jsduck', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
});
gulp.task('default', ['lint', 'test']);
|
Modify name field to unique on photos table | <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string('name')->unique();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('photos');
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePhotosTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('post_id')->unsigned();
$table->string('name');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('photos');
}
}
|
Update email address to ph7builder.com domain | <?php
/**
* @author Pierre-Henry Soria <hello@ph7builder.com>
* @copyright (c) 2021-2022, Pierre-Henry Soria. All Rights Reserved.
* @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Test / Unit
*/
defined('PH7') or exit('Restricted access');
echo 'ℹ️ GD installed: ' . (extension_loaded('gd') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ Zip installed: ' . (extension_loaded('zip') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ Zlib installed: ' . (extension_loaded('zlib') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ mbstring installed: ' . (extension_loaded('mbstring') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ exif installed: ' . (extension_loaded('exif') ? '✅' : '❌') . PHP_EOL;
| <?php
/**
* @author Pierre-Henry Soria <hello@ph7cms.com>
* @copyright (c) 2021-2022, Pierre-Henry Soria. All Rights Reserved.
* @license MIT License; See PH7.LICENSE.txt and PH7.COPYRIGHT.txt in the root directory.
* @package PH7 / Test / Unit
*/
defined('PH7') or exit('Restricted access');
echo 'ℹ️ GD installed: ' . (extension_loaded('gd') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ Zip installed: ' . (extension_loaded('zip') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ Zlib installed: ' . (extension_loaded('zlib') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ mbstring installed: ' . (extension_loaded('mbstring') ? '✅' : '❌') . PHP_EOL;
echo 'ℹ️ exif installed: ' . (extension_loaded('exif') ? '✅' : '❌') . PHP_EOL;
|
Use 'source' command instead of deprecated '.' alias
Closes #125 | from __future__ import print_function
import os
import sys
import pkg_resources
if __name__ == "__main__":
version = pkg_resources.get_distribution('virtualfish').version
base_path = os.path.dirname(os.path.abspath(__file__))
commands = [
'set -g VIRTUALFISH_VERSION {}'.format(version),
'set -g VIRTUALFISH_PYTHON_EXEC {}'.format(sys.executable),
'source {}'.format(os.path.join(base_path, 'virtual.fish')),
]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fish')
if os.path.exists(path):
commands.append('source {}'.format(path))
else:
print('virtualfish loader error: plugin {} does not exist!'.format(plugin), file=sys.stderr)
commands.append('emit virtualfish_did_setup_plugins')
print(';'.join(commands))
| from __future__ import print_function
import os
import sys
import pkg_resources
if __name__ == "__main__":
version = pkg_resources.get_distribution('virtualfish').version
base_path = os.path.dirname(os.path.abspath(__file__))
commands = [
'set -g VIRTUALFISH_VERSION {}'.format(version),
'set -g VIRTUALFISH_PYTHON_EXEC {}'.format(sys.executable),
'. {}'.format(os.path.join(base_path, 'virtual.fish')),
]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fish')
if os.path.exists(path):
commands.append('. {}'.format(path))
else:
print('virtualfish loader error: plugin {} does not exist!'.format(plugin), file=sys.stderr)
commands.append('emit virtualfish_did_setup_plugins')
print(';'.join(commands))
|
Tweak the class for 'today' in the bootstrap theme |
var BootstrapTheme = Theme.extend({
classes: {
widget: 'fc-bootstrap3',
tableGrid: 'table-bordered', // avoid `table` class b/c don't want margins. only border color
tableList: 'table table-striped', // `table` class creates bottom margin but who cares
buttonGroup: 'btn-group',
button: 'btn btn-default',
stateActive: 'active',
stateDisabled: 'disabled',
today: 'alert alert-info', // the plain `info` class requires `.table`, too much to ask
popover: 'panel panel-default',
popoverHeader: 'panel-heading',
popoverContent: 'panel-body',
// day grid
headerRow: 'panel-default', // avoid `panel` class b/c don't want margins/radius. only border color
dayRow: 'panel-default', // "
// list view
listView: 'panel panel-default'
},
baseIconClass: 'glyphicon',
iconClasses: {
close: 'glyphicon-remove',
prev: 'glyphicon-chevron-left',
next: 'glyphicon-chevron-right',
prevYear: 'glyphicon-backward',
nextYear: 'glyphicon-forward'
},
iconOverrideOption: 'bootstrapGlyphicons',
iconOverrideCustomButtonOption: 'bootstrapGlyphicon',
iconOverridePrefix: 'glyphicon-'
});
ThemeRegistry.register('bootstrap3', BootstrapTheme);
|
var BootstrapTheme = Theme.extend({
classes: {
widget: 'fc-bootstrap3',
tableGrid: 'table-bordered', // avoid `table` class b/c don't want margins. only border color
tableList: 'table table-striped', // `table` class creates bottom margin but who cares
buttonGroup: 'btn-group',
button: 'btn btn-default',
stateActive: 'active',
stateDisabled: 'disabled',
today: 'alert alert-warning', // the plain `warning` class requires `.table`, too much to ask
popover: 'panel panel-default',
popoverHeader: 'panel-heading',
popoverContent: 'panel-body',
// day grid
headerRow: 'panel-default', // avoid `panel` class b/c don't want margins/radius. only border color
dayRow: 'panel-default', // "
// list view
listView: 'panel panel-default'
},
baseIconClass: 'glyphicon',
iconClasses: {
close: 'glyphicon-remove',
prev: 'glyphicon-chevron-left',
next: 'glyphicon-chevron-right',
prevYear: 'glyphicon-backward',
nextYear: 'glyphicon-forward'
},
iconOverrideOption: 'bootstrapGlyphicons',
iconOverrideCustomButtonOption: 'bootstrapGlyphicon',
iconOverridePrefix: 'glyphicon-'
});
ThemeRegistry.register('bootstrap3', BootstrapTheme);
|
Add "applied" timestamp to schema migrations table | # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL,
applied TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
| # -*- coding: utf-8 -*-
# ###
# Copyright (c) 2015, Rice University
# This software is subject to the provisions of the GNU Affero General
# Public License version 3 (AGPLv3).
# See LICENCE.txt for details.
# ###
from .. import utils
__all__ = ('cli_loader',)
@utils.with_cursor
def cli_command(cursor, migrations_directory='', **kwargs):
cursor.execute("""\
CREATE TABLE IF NOT EXISTS schema_migrations (
version TEXT NOT NULL
)""")
cursor.execute("""\
DELETE FROM schema_migrations""")
versions = []
for version, name in utils.get_migrations(migrations_directory):
versions.append((version,))
cursor.executemany("""\
INSERT INTO schema_migrations VALUES (%s)
""", versions)
def cli_loader(parser):
return cli_command
|
Allow setting of etcd store via flags | package cmd
import (
"flag"
"github.com/asim/go-micro/registry"
"github.com/asim/go-micro/server"
"github.com/asim/go-micro/store"
)
var (
flagBindAddress string
flagRegistry string
flagStore string
)
func init() {
flag.StringVar(&flagBindAddress, "bind_address", ":0", "Bind address for the server. 127.0.0.1:8080")
flag.StringVar(&flagRegistry, "registry", "consul", "Registry for discovery. kubernetes, consul, etc")
flag.StringVar(&flagStore, "store", "consul", "Store used as a basic key/value store using consul, memcached, etc")
}
func Init() {
flag.Parse()
server.Address = flagBindAddress
switch flagRegistry {
case "kubernetes":
registry.DefaultRegistry = registry.NewKubernetesRegistry()
}
switch flagStore {
case "memcached":
store.DefaultStore = store.NewMemcacheStore()
case "etcd":
store.DefaultStore = store.NewEtcdStore()
}
}
| package cmd
import (
"flag"
"github.com/asim/go-micro/registry"
"github.com/asim/go-micro/server"
"github.com/asim/go-micro/store"
)
var (
flagBindAddress string
flagRegistry string
flagStore string
)
func init() {
flag.StringVar(&flagBindAddress, "bind_address", ":0", "Bind address for the server. 127.0.0.1:8080")
flag.StringVar(&flagRegistry, "registry", "consul", "Registry for discovery. kubernetes, consul, etc")
flag.StringVar(&flagStore, "store", "consul", "Store used as a basic key/value store using consul, memcached, etc")
}
func Init() {
flag.Parse()
server.Address = flagBindAddress
switch flagRegistry {
case "kubernetes":
registry.DefaultRegistry = registry.NewKubernetesRegistry()
}
switch flagStore {
case "memcached":
store.DefaultStore = store.NewMemcacheStore()
}
}
|
Switch off weird AEP-1.0 model-renaming bullshit.
git-svn-id: 062a66634e56759c7c3cc44955c32d2ce0012d25@295 c02d1e6f-6a35-45f2-ab14-3b6f79a691ff | from ragendja.settings_pre import *
import environment
MEDIA_VERSION = environment.MAJOR_VERSION
DEBUG = environment.IS_DEVELOPMENT
TEMPLATE_DEBUG = environment.IS_DEVELOPMENT
DATABASE_ENGINE = 'appengine'
USE_I18N = False
TEMPLATE_LOADERS = (
# Load basic template files in the normal way
'django.template.loaders.filesystem.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = (
)
MIDDLEWARE_CLASSES = (
# does things like APPEND_SLASH for URLs
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'urls'
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
ROOT_PATH + '/resources/templates'
)
INSTALLED_APPS = (
'appenginepatcher',
'tasks',
'public',
'admin',
)
DJANGO_STYLE_MODEL_KIND = False
from ragendja.settings_post import *
| from ragendja.settings_pre import *
import environment
MEDIA_VERSION = environment.MAJOR_VERSION
DEBUG = environment.IS_DEVELOPMENT
TEMPLATE_DEBUG = environment.IS_DEVELOPMENT
DATABASE_ENGINE = 'appengine'
USE_I18N = False
TEMPLATE_LOADERS = (
# Load basic template files in the normal way
'django.template.loaders.filesystem.load_template_source',
)
TEMPLATE_CONTEXT_PROCESSORS = (
)
MIDDLEWARE_CLASSES = (
# does things like APPEND_SLASH for URLs
'django.middleware.common.CommonMiddleware',
)
ROOT_URLCONF = 'urls'
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DIRS = (
ROOT_PATH + '/resources/templates'
)
INSTALLED_APPS = (
'appenginepatcher',
'tasks',
'public',
'admin',
)
from ragendja.settings_post import *
|
Add device icon to User.devices() | var extend = require('extend');
var Hoek = require('hoek');
module.exports = function(client) {
var User = function(_obj, _accessToken) {
extend(this, _obj);
this.accessToken = _accessToken;
};
User.prototype.devices = function() {
var self = this;
Hoek.assert(self.accessToken);
return client.authGet('user/devices', self.accessToken).then(function(resp) {
return {
list: resp.devices.map(function(dev) {
return new client.Device({ id: dev.id, name: dev.name, icon: dev.icon });
})
};
});
};
User.fetch = function(accessToken) {
return client.authGet('user', accessToken).then(function(resp) {
return new User(resp.user, accessToken);
});
};
User.forge = function(accessToken) {
return new User({}, accessToken);
};
return User;
}; | var extend = require('extend');
var Hoek = require('hoek');
module.exports = function(client) {
var User = function(_obj, _accessToken) {
extend(this, _obj);
this.accessToken = _accessToken;
};
User.prototype.devices = function() {
var self = this;
Hoek.assert(self.accessToken);
return client.authGet('user/devices', self.accessToken).then(function(resp) {
return {
list: resp.devices.map(function(dev) {
return new client.Device({ id: dev.id, name: dev.name });
})
};
});
};
User.fetch = function(accessToken) {
return client.authGet('user', accessToken).then(function(resp) {
return new User(resp.user, accessToken);
});
};
User.forge = function(accessToken) {
return new User({}, accessToken);
};
return User;
}; |
Fix django-1.7 deprecated mimetype keyword argument
Source: https://docs.djangoproject.com/en/1.5/ref/request-response/#django.http.HttpResponse.__init__ | import json as simplejson
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from atompos.main import settings
from util import get_atom_pos, get_positions_atb
def index(request):
return render(request, 'index.html')
def _get_positions(request, position_function):
if request.method != 'POST':
raise Http404
params = request.POST.dict()
if 'csrfmiddlewaretoken' in params:
params.pop('csrfmiddlewaretoken')
pos = position_function(params)
if "error" in pos:
res = pos
res.update({"version": settings.VERSION})
else:
res = {
"molecule": pos,
"version": settings.VERSION
}
return HttpResponse(
simplejson.dumps(res, indent=2),
content_type="application/json"
)
@csrf_exempt
def generate(request):
return _get_positions(request, get_atom_pos)
@csrf_exempt
def load_atb(request):
return _get_positions(request, get_positions_atb)
| import json as simplejson
from django.http import HttpResponse, Http404
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from atompos.main import settings
from util import get_atom_pos, get_positions_atb
def index(request):
return render(request, 'index.html')
def _get_positions(request, position_function):
if request.method != 'POST':
raise Http404
params = request.POST.dict()
if 'csrfmiddlewaretoken' in params:
params.pop('csrfmiddlewaretoken')
pos = position_function(params)
if "error" in pos:
res = pos
res.update({"version": settings.VERSION})
else:
res = {
"molecule": pos,
"version": settings.VERSION
}
return HttpResponse(
simplejson.dumps(res, indent=2),
mimetype="application/json"
)
@csrf_exempt
def generate(request):
return _get_positions(request, get_atom_pos)
@csrf_exempt
def load_atb(request):
return _get_positions(request, get_positions_atb)
|
Fix the carry over script |
'use strict';
const
Promise = require('bluebird'),
moment = require('moment'),
models = require('../lib/model/db');
const
YEAR_FROM = '2018',
YEAR_TO = '2019';
/*
* 1. Get all users
*
* 2. Iterate through users and:
*
* 3. Calculate remaining days for current year
*
* 4. Put value from step 3 into user_allowance_adjustment.carried_over_allowance
* of next year
*
* */
models.User
.findAll()
.then(users => Promise.map(
users,
user => {
let carryOver;
return Promise.resolve(user.getCompany().then(c => carryOver = c.carry_over))
.then(() => user.reload_with_leave_details({YEAR_FROM}))
.then(user => user.promise_allowance({year:moment.utc(YEAR_FROM, 'YYYY')}))
.then(allowance => {
return user.promise_to_update_carried_over_allowance({
year : YEAR_TO,
carried_over_allowance : Math.min(allowance.number_of_days_available_in_allowance, carryOver),
});
})
.then(() => Promise.resolve(console.log('Done with user ' + user.id)));
},
{concurrency : 1}
));
|
'use strict';
const
Promise = require('bluebird'),
models = require('../lib/model/db');
const
YEAR_FROM = '2017',
YEAR_TO = '2018';
/*
* 1. Get all users
*
* 2. Iterate through users and:
*
* 3. Calculate remaining days for current year
*
* 4. Put value from step 3 into user_allowance_adjustment.carried_over_allowance
* of next year
*
* */
models.User
.findAll()
.then(users => Promise.map(
users,
user => {
return user
.reload_with_leave_details({YEAR_FROM})
.then( user => user.promise_number_of_days_available_in_allowance(YEAR_FROM) )
.then(remainer => {
return user.promise_to_update_carried_over_allowance({
year : YEAR_TO,
carried_over_allowance : remainer,
});
})
.then(() => Promise.resolve(console.log('Done with user ' + user.id)));
},
{concurrency : 1}
));
|
Add assemble to deploy task. | // Configuration
module.exports = function(grunt) {
// include time-grunt
require('time-grunt')(grunt);
// Initialize config
grunt.initConfig({
pkg: '<json:package.json>',
});
// Load required tasks from submodules
grunt.loadTasks('grunt');
// Default
grunt.registerTask('default', [
'connect',
'watch'
]);
// Testing
grunt.registerTask('test', [
'htmlhint',
'jshint',
'scsslint'
]);
// Deployment
grunt.registerTask('deploy', [
'clean:deploy',
'fontello:build',
'assemble:deploy',
'copy:deploy',
'concat',
'sass:deploy',
'uglify',
'imagemin:deploy',
'favicons:deploy',
'modernizr',
'hashres:deploy'
]);
};
| // Configuration
module.exports = function(grunt) {
// include time-grunt
require('time-grunt')(grunt);
// Initialize config
grunt.initConfig({
pkg: '<json:package.json>',
});
// Load required tasks from submodules
grunt.loadTasks('grunt');
// Default
grunt.registerTask('default', [
'connect',
'watch'
]);
// Testing
grunt.registerTask('test', [
'htmlhint',
'jshint',
'scsslint'
]);
// Deployment
grunt.registerTask('deploy', [
'clean:deploy',
'fontello:build',
'copy:deploy',
'concat',
'sass:deploy',
'uglify',
'imagemin:deploy',
'favicons:deploy',
'modernizr',
'hashres:deploy'
]);
};
|
Add configuration for pagaing related properties. | package uk.ac.ebi.quickgo.ontology;
import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig;
import uk.ac.ebi.quickgo.ontology.service.ServiceConfig;
import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Runnable class to start an embedded server to host the defined RESTful components.
*
* Created 16/11/15
* @author Edd
*/
@SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class})
@ComponentScan({
"uk.ac.ebi.quickgo.ontology.controller",
"uk.ac.ebi.quickgo.rest"})
@Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class, OntologyRestConfig.class})
public class OntologyREST {
/**
* Ensures that placeholders are replaced with property values
*/
@Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public static void main(String[] args) {
SpringApplication.run(OntologyREST.class, args);
}
}
| package uk.ac.ebi.quickgo.ontology;
import uk.ac.ebi.quickgo.ontology.coterms.CoTermConfig;
import uk.ac.ebi.quickgo.ontology.service.ServiceConfig;
import uk.ac.ebi.quickgo.rest.controller.SwaggerConfig;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Import;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
/**
* Runnable class to start an embedded server to host the defined RESTful components.
*
* Created 16/11/15
* @author Edd
*/
@SpringBootApplication(exclude = {SolrRepositoriesAutoConfiguration.class})
@ComponentScan({
"uk.ac.ebi.quickgo.ontology.controller",
"uk.ac.ebi.quickgo.rest"})
@Import({ServiceConfig.class, SwaggerConfig.class, CoTermConfig.class})
public class OntologyREST {
/**
* Ensures that placeholders are replaced with property values
*/
@Bean
static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
public static void main(String[] args) {
SpringApplication.run(OntologyREST.class, args);
}
}
|
Update test for named object response | process.env.NODE_ENV = 'test';
var should = require('should'),
request = require('supertest'),
testSetup = require('../util/testSetup'),
url = 'http://localhost:1337';
describe('Controllers/MoviesController', function() {
before(function(done) {
testSetup.before(done);
});
it('index - should return blank array', function(done) {
request(url)
.get('/movies')
.expect(200)
.end(function(err, res) {
var movies = res.body.movies;
should.equal(movies.length,0);
should.not.exist(err);
if (err) { return done(err); }
done();
});
});
after(function(done) {
testSetup.after(done);
});
}); | process.env.NODE_ENV = 'test';
var should = require('should'),
request = require('supertest'),
testSetup = require('../util/testSetup'),
url = 'http://localhost:1337';
describe('Controllers/MoviesController', function() {
before(function(done) {
testSetup.before(done);
});
it('index - should return blank array', function(done) {
request(url)
.get('/movies')
.expect(200)
.end(function(err, res) {
var movies = res.body;
should.equal(movies.length,0);
should.not.exist(err);
if (err) { return done(err); }
done();
});
});
after(function(done) {
testSetup.after(done);
});
}); |
feat: Enforce TEAM_TOKEN setting by defaulting to storing random number in memory | const winston = require('winston');
const fs = require('fs');
const SecurityError = require('./errors/security-error');
const COMMAND_FILE = './commands.json';
const TEAM_TOKEN = process.env.TEAM_TOKEN || Math.random(); // Seriously, you must have it set
var commandLookup = new Promise((resolve, reject) => {
fs.readFile(COMMAND_FILE, 'utf8', (err, contents) => {
if (err) {
return reject(err);
}
resolve(JSON.parse(contents));
});
});
function resolveCommand() {
}
function validateToken(token) {
if (token === TEAM_TOKEN) {
return true;
}
throw new SecurityError('Token does not match team\'s ');
}
module.exports = (req) => {
return new Promise((resolve, reject) => {
validateToken(req.body.token);
winston.info(req.body);
resolve('OK');
});
}
| const winston = require('winston');
const fs = require('fs');
const SecurityError = require('./errors/security-error');
const COMMAND_FILE = './commands.json';
const TEAM_TOKEN = process.env.TEAM_TOKEN;
var commandLookup = new Promise((resolve, reject) => {
fs.readFile(COMMAND_FILE, 'utf8', (err, contents) => {
if (err) {
return reject(err);
}
resolve(JSON.parse(contents));
});
});
function resolveCommand() {
}
function validateToken(token) {
if (token === TEAM_TOKEN) {
return true;
}
throw new SecurityError('Token does not match team\'s ');
}
module.exports = (req) => {
return new Promise((resolve, reject) => {
validateToken(req.body.token);
resolve('OK');
});
}
|
Fix a typo on the clean old spam script | <?php
/**
* Delete spam older than 30 days
*/
if(php_sapi_name() !== 'cli') {
die('CLI only');
}
date_default_timezone_set('Europe/London');
require dirname(__FILE__) . '/../bootstrap.php';
$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");
$values = $manager->values();
if(!$values) {
echo "Nothing to do.\n";
return;
}
$app = \FelixOnline\Core\App::getInstance();
foreach($values as $record) {
$id = $record->getId();
$app['db']->query("DELETE FROM akismet_log WHERE comment_id = ".$id);
$app['db']->query("DELETE FROM comment WHERE id = ".$id);
}
echo "All done.\n";
| <?php
/**
* Delete spam older than 30 days
*/
if(php_sapi_name() !== 'cli') {
die('CLI only');
}
date_default_timezone_set('Europe/London');
require dirname(__FILE__) . '/../bootstrap.php';
$manager = \FelixOnline\Core\BaseManager::build('FelixOnline\Core\Comment', 'comment');
$manager->filter("spam = 1")
->filter("timestamp < DATE_SUB(NOW(), INTERVAL 30 DAY);");
$values = $manager->values();
if(!$values) {
echo "Nothing to do.\n";
return;
}
$app = App::getInstance();
foreach($values as $record) {
$id = $record->getId();
$app['db']->query("DELETE FROM akismet_log WHERE comment_id = ".$id);
$app['db']->query("DELETE FROM comment WHERE id = ".$id);
}
echo "All done.\n";
|
Refactor Vert.x 2 event loop context to store context upon construction in order to prevent issues with calling runOnContext from a non-context thread. | /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kuujo.copycat.vertx;
import org.vertx.java.core.Context;
import org.vertx.java.core.Vertx;
import java.util.concurrent.Executor;
/**
* Vert.x execution context.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class VertxEventLoopExecutor implements Executor {
private final Context context;
public VertxEventLoopExecutor(Vertx vertx) {
this.context = vertx.currentContext();
}
@Override
public void execute(Runnable command) {
context.runOnContext(v -> command.run());
}
}
| /*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kuujo.copycat.vertx;
import org.vertx.java.core.Vertx;
import java.util.concurrent.Executor;
/**
* Vert.x execution context.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class VertxEventLoopExecutor implements Executor {
private final Vertx vertx;
public VertxEventLoopExecutor(Vertx vertx) {
this.vertx = vertx;
}
@Override
public void execute(Runnable command) {
vertx.runOnContext(v -> command.run());
}
}
|
Validate does not need clientToken | <?php
require 'config.php';
$input = file_get_contents('php://input');
$json = json_decode($input, true);
if(isset($json['accessToken'])) {
$mysql = new mysqli($CONFIG['host'], $CONFIG['user'], $CONFIG['pass'], $CONFIG['database']);
$result = $mysql->query('SELECT * FROM ' . $CONFIG['table'] . ' WHERE accesstoken="' . $mysql->real_escape_string($json['accessToken']) . '"');
if($result->num_rows === 1) {
echo json_encode();
}
else if($CONFIG['onlineauth']) {
echo file_get_contents('https://authserver.mojang.com/validate', false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $input
)
)));
}
else {
echo json_encode(array(
'error' => 'ForbiddenOperationException',
'errorMessage' => 'Invalid token.'
));
}
$result->close();
$mysql->close();
}
else {
echo $CONFIG['message'];
}
?>
| <?php
require 'config.php';
$input = file_get_contents('php://input');
$json = json_decode($input, true);
if(isset($json['accessToken']) && isset($json['clientToken'])) {
$mysql = new mysqli($CONFIG['host'], $CONFIG['user'], $CONFIG['pass'], $CONFIG['database']);
$result = $mysql->query('SELECT * FROM ' . $CONFIG['table'] . ' WHERE accesstoken="' . $mysql->real_escape_string($json['accessToken']) . '" AND clientoken="' . $mysql->real_escape_string($json['clientToken']) . '"');
if($result->num_rows === 1) {
echo json_encode();
}
else if($CONFIG['onlineauth']) {
echo file_get_contents('https://authserver.mojang.com/validate', false, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => 'Content-Type: application/json',
'content' => $input
)
)));
}
else {
echo json_encode(array(
'error' => 'ForbiddenOperationException',
'errorMessage' => 'Invalid token.'
));
}
$result->close();
$mysql->close();
}
else {
echo $CONFIG['message'];
}
?>
|
Fix UI when there is not chart maintainer defined | /*
Copyright 2016 ElasticBox All rights reserved.
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.
*/
class ChartController {
constructor($filter, chartsNavigationActionCreator) {
'ngInject';
this.lastModified = $filter('ekHumanizeDate')(this.chart.committed_date, 'epoch');
this._chartsNavigationActionCreator = chartsNavigationActionCreator;
this.maintainer = _.isEmpty(this.chart.maintainers) ? 'Last modified' : _.first(this.chart.maintainers).split('<')[0];
}
deploy() {
this._chartsNavigationActionCreator.deployChart(this.chart);
}
}
export default ChartController;
| /*
Copyright 2016 ElasticBox All rights reserved.
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.
*/
class ChartController {
constructor($filter, chartsNavigationActionCreator) {
'ngInject';
this.lastModified = $filter('ekHumanizeDate')(this.chart.committed_date, 'epoch');
this._chartsNavigationActionCreator = chartsNavigationActionCreator;
this.maintainer = this.chart.maintainers[0].split('<')[0];
}
deploy() {
this._chartsNavigationActionCreator.deployChart(this.chart);
}
}
export default ChartController;
|
Change parameter name and fix comment | package run
import (
"gopkg.in/workanator/go-floc.v2"
)
const locRepeat = "Repeat"
/*
Repeat repeats running the job for N times.
Summary:
- Run jobs in goroutines : NO
- Wait all jobs finish : YES
- Run order : SEQUENCE
Diagram:
NO
+-----------[JOB]<---------+
| |
V | YES
----(ITERATED COUNT TIMES?)--+---->
*/
func Repeat(times int, job floc.Job) floc.Job {
return func(ctx floc.Context, ctrl floc.Control) error {
for n := 1; n <= times; n++ {
// Do not start the job if the execution is finished
if ctrl.IsFinished() {
return nil
}
// Do the job
err := job(ctx, ctrl)
if handledErr := handleResult(ctrl, err, locRepeat); handledErr != nil {
return handledErr
}
}
return nil
}
}
| package run
import (
"gopkg.in/workanator/go-floc.v2"
)
const locRepeat = "Repeat"
/*
Repeat repeats running jobs for N times. Jobs start sequentially.
Summary:
- Run jobs in goroutines : NO
- Wait all jobs finish : YES
- Run order : SEQUENCE
Diagram:
NO
+-----------[JOB]<---------+
| |
V | YES
----(ITERATED COUNT TIMES?)--+---->
*/
func Repeat(count int, job floc.Job) floc.Job {
return func(ctx floc.Context, ctrl floc.Control) error {
for n := 1; n <= count; n++ {
// Do not start the job if the execution is finished
if ctrl.IsFinished() {
return nil
}
// Do the job
err := job(ctx, ctrl)
if handledErr := handleResult(ctrl, err, locRepeat); handledErr != nil {
return handledErr
}
}
return nil
}
}
|
Connect the GoogleAdapter with the EventApi | <?php
/**
* This file is part of the CalendArt package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
namespace CalendArt\Adapter;
use CalendArt\Calendar;
/**
* Handle the dialog with an Adapter
*
* @author Baptiste Clavié <baptiste@wisembly.com>
*/
interface AdapterInterface
{
/**
* Get the Calendar API to use for this adapter
*
* @return CalendarApiInterface
*/
public function getCalendarApi();
/**
* Get the Event API to use for this adapter (scoped to a particular calendar)
*
* @param Calendar $calendar Calendar to scope this api to
*
* @return EventApiInterface
*/
public function getEventApi(Calendar $calendar);
}
| <?php
/**
* This file is part of the CalendArt package
*
* For the full copyright and license information, please view the LICENSE file
* that was distributed with this source code.
*
* @copyright Wisembly
* @license http://www.opensource.org/licenses/MIT-License MIT License
*/
namespace CalendArt\Adapter;
/**
* Handle the dialog with an Adapter
*
* @author Baptiste Clavié <baptiste@wisembly.com>
*/
interface AdapterInterface
{
/**
* Get the Calendar API to use for this adapter
*
* @return CalendarApiInterface
*/
public function getCalendarApi();
/**
* Get the Event API to use for this adapter (scoped to a particular calendar)
*
* @param Calendar $calendar Calendar to scope this api to
*
* @return EventApiInterface
*/
public function getEventApi(Calendar $calendar);
}
|
Fix incorrect use of `_.defaults` | var async = require('async');
var _ = require('lodash');
var readTOML = require('./utils').readTOML;
var fileExists = require('./utils').fileExists;
var defaults = {
account: {
username: 'admin',
password: 'password',
channel: '#riotgames'
},
irc: {
address: '199.9.253.199'
},
server: {
port: 6667
}
};
function Config(options) {
this['account'] = _.defaults(options['account'], defaults['account']);
this['irc'] = _.defaults(options['irc'], defaults['irc']);
this['server'] = _.defaults(options['server'], defaults['server']);
}
Config.fromFile = function(path, callback) {
async.waterfall([
function(cb) {
fileExists(path, function(exists) {
if (exists) {
readTOML(path, cb);
} else {
cb(new Error("Config file at '" + path + "' does not exist."));
}
});
}, function(options, cb) {
var config = new Config(options);
config.__filename = path;
cb(null, config);
}
], callback);
};
module.exports.Config = Config; | var async = require('async');
var _ = require('lodash');
var readTOML = require('./utils').readTOML;
var fileExists = require('./utils').fileExists;
var defaults = {
account: {
username: 'admin',
password: 'password',
channel: '#riotgames'
},
irc: {
address: '199.9.253.199'
},
server: {
port: 6667
}
};
function Config(options) {
this['account'] = _.defaults(defaults['account'], options['account']);
this['irc'] = _.defaults(defaults['irc'], options['irc']);
this['server'] = _.defaults(defaults['server'], options['server']);
}
Config.fromFile = function(path, callback) {
async.waterfall([
function(cb) {
fileExists(path, function(exists) {
if (exists) {
readTOML(path, cb);
} else {
cb(new Error("Config file at '" + path + "' does not exist."));
}
});
}, function(options, cb) {
var config = new Config(options);
config.__filename = path;
cb(null, config);
}
], callback);
};
module.exports.Config = Config; |
Make signout button show/hide on signin or signout | // do not tamper with this code in here, study it, but do not touch
// this Auth controller is responsible for our client side authentication
// in our signup/signin forms using the injected Auth service
angular.module('shortly.auth', [])
.controller('AuthController', function ($scope, $window, $location, $http, Auth) {
$scope.user = {};
$scope.auth = Auth.isAuth();
$scope.signin = function () {
console.log('hit auth controller');
return $http({
method: 'POST',
url: '/auth/local',
data: $scope.user
})
.then(function (resp) {
console.log('resp',resp.config.data.username);
$window.sessionStorage.setItem('user', resp.config.data.username);
$window.location.href = "/";
});
};
$scope.signup = function () {
return $http({
method: 'POST',
url: '/auth/local-signup',
data: $scope.user
})
.then(function (resp) {
console.log('gets to then of signup in client')
$location.path('/links');
});
};
$scope.signout = function(){
$scope.auth = Auth.isAuth();
Auth.signout();
};
});
| // do not tamper with this code in here, study it, but do not touch
// this Auth controller is responsible for our client side authentication
// in our signup/signin forms using the injected Auth service
angular.module('shortly.auth', [])
.controller('AuthController', function ($scope, $window, $location, $http, Auth) {
$scope.user = {};
$scope.auth = Auth.isAuth();
$scope.signin = function () {
console.log('hit auth controller');
return $http({
method: 'POST',
url: '/auth/local',
data: $scope.user
})
.then(function (resp) {
console.log('resp',resp.config.data.username);
$window.sessionStorage.setItem('user', resp.config.data.username);
$location.path('/links');
});
};
$scope.signup = function () {
return $http({
method: 'POST',
url: '/auth/local-signup',
data: $scope.user
})
.then(function (resp) {
console.log('gets to then of signup in client')
$location.path('/links');
});
};
$scope.signout = function(){
$scope.auth = Auth.isAuth();
Auth.signout();
};
});
|
Add setproctitle wrapper so it's optional.
Signed-off-by: Chris Lamb <711c73f64afdce07b7e38039a96d2224209e9a6c@thread.com> | from django.db import models
from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import MiddlewareNotUsed
from django.utils.functional import memoize
from django.utils.module_loading import module_has_submodule
from . import app_settings
def get_path(path):
module_name, attr = path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, attr)
def get_backend():
return get_path(app_settings.BACKEND)()
def get_middleware():
middleware = []
for path in app_settings.MIDDLEWARE:
try:
middleware.append(get_path(path)())
except MiddlewareNotUsed:
pass
return middleware
try:
from setproctitle import setproctitle
except ImportError:
def setproctitle(title):
pass
get_path = memoize(get_path, {}, 1)
get_backend = memoize(get_backend, {}, 0)
get_middleware = memoize(get_middleware, {}, 0)
| from django.db import models
from django.conf import settings
from django.utils.importlib import import_module
from django.core.exceptions import MiddlewareNotUsed
from django.utils.functional import memoize
from django.utils.module_loading import module_has_submodule
from . import app_settings
def get_path(path):
module_name, attr = path.rsplit('.', 1)
module = import_module(module_name)
return getattr(module, attr)
def get_backend():
return get_path(app_settings.BACKEND)()
def get_middleware():
middleware = []
for path in app_settings.MIDDLEWARE:
try:
middleware.append(get_path(path)())
except MiddlewareNotUsed:
pass
return middleware
get_path = memoize(get_path, {}, 1)
get_backend = memoize(get_backend, {}, 0)
get_middleware = memoize(get_middleware, {}, 0)
|
: Create documentation of DataSource Settings
Task-Url: | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs:
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) | ######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
dbs = ['FNOSDS', 'FNGCDDS', 'IBM_FORMS_DATA_SOURCE', 'activities', 'blogs', 'communities', 'dogear', 'files', 'forum', 'homepage', 'metrics', 'mobile', 'news', 'oauth provider', 'profiles', 'search', 'wikis'] # List of all databases to check
for db in dbs.splitlines():
t1 = ibmcnx.functions.getDSId( db )
AdminConfig.list( t1 ) |
Add a test for the AE experiment | # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tiny run of trainer_model_based. Smoke test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
from tensor2tensor.rl import trainer_model_based
import tensorflow as tf
FLAGS = tf.flags.FLAGS
class ModelRLExperimentTest(tf.test.TestCase):
def setUp(self):
super(ModelRLExperimentTest, self).setUp()
FLAGS.output_dir = tf.test.get_temp_dir()
shutil.rmtree(FLAGS.output_dir)
os.mkdir(FLAGS.output_dir)
FLAGS.schedule = "train" # skip evaluation for world model training
def test_basic(self):
FLAGS.loop_hparams_set = "rl_modelrl_tiny"
trainer_model_based.main(None)
def test_ae(self):
FLAGS.loop_hparams_set = "rl_modelrl_ae_tiny"
trainer_model_based.main(None)
if __name__ == "__main__":
tf.test.main()
| # coding=utf-8
# Copyright 2018 The Tensor2Tensor Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tiny run of trainer_model_based. Smoke test."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensor2tensor.rl import trainer_model_based
import tensorflow as tf
FLAGS = tf.flags.FLAGS
class ModelRLExperimentTest(tf.test.TestCase):
def test_basic(self):
FLAGS.output_dir = tf.test.get_temp_dir()
FLAGS.loop_hparams_set = "rl_modelrl_tiny"
FLAGS.schedule = "train" # skip evaluation for world model training
trainer_model_based.main(None)
if __name__ == "__main__":
tf.test.main()
|
Revert "Revert "Testing git commit""
This reverts commit ea3742010d0936fe0053a466064941b7015ac43e. | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.example.android.bluetoothchat;
/**
* Defines several constants used between {@link BluetoothChatService} and the UI.
*/
public interface Constants {
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
//check this code for bluetooth chat application, which is very easy and don't need any network as such
}
| /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.example.android.bluetoothchat;
/**
* Defines several constants used between {@link BluetoothChatService} and the UI.
*/
public interface Constants {
// Message types sent from the BluetoothChatService Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
// Key names received from the BluetoothChatService Handler
public static final String DEVICE_NAME = "device_name";
public static final String TOAST = "toast";
}
|
Update return type to `static` to improve static analysis | <?php
namespace Stripe\ApiOperations;
/**
* Trait for retrievable resources. Adds a `retrieve()` static method to the
* class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Retrieve
{
/**
* @param array|string $id The ID of the API resource to retrieve,
* or an options array containing an `id` key.
* @param array|string|null $opts
*
* @return static
*/
public static function retrieve($id, $opts = null)
{
$opts = \Stripe\Util\RequestOptions::parse($opts);
$instance = new static($id, $opts);
$instance->refresh();
return $instance;
}
}
| <?php
namespace Stripe\ApiOperations;
/**
* Trait for retrievable resources. Adds a `retrieve()` static method to the
* class.
*
* This trait should only be applied to classes that derive from StripeObject.
*/
trait Retrieve
{
/**
* @param array|string $id The ID of the API resource to retrieve,
* or an options array containing an `id` key.
* @param array|string|null $opts
*
* @return \Stripe\StripeObject
*/
public static function retrieve($id, $opts = null)
{
$opts = \Stripe\Util\RequestOptions::parse($opts);
$instance = new static($id, $opts);
$instance->refresh();
return $instance;
}
}
|
Fix service provider factory name. | <?php
namespace Cohensive\Upload;
use Illuminate\Support\ServiceProvider;
use Cohensive\Upload\Sanitizer\LaravelStrSanitizer;
class UploadServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->package('cohensive/upload');
$this->app->bindShared('upload', function($app) {
$options = $app['config']->get('upload::options');
return new LaravelFactory($options);
});
}
public function provides()
{
return ['upload'];
}
}
| <?php
namespace Cohensive\Upload;
use Illuminate\Support\ServiceProvider;
use Cohensive\Upload\Sanitizer\LaravelStrSanitizer;
class UploadServiceProvider extends ServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->package('cohensive/upload');
$this->app->bindShared('upload', function($app) {
$options = $app['config']->get('upload::options');
return new LaraveFactory($options);
});
}
public function provides()
{
return ['upload'];
}
}
|
Update py27 compatibility in print function | # -*- coding: utf-8 -*-
from __future__ import print_function
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
| # -*- coding: utf-8 -*-
from flowgen.graph import Graph
from flowgen.language import Code
from flowgen.options import parser
from pypeg2 import parse
from pypeg2.xmlast import thing2xml
class FlowGen(object):
def __init__(self, args):
self.args = parser.parse_args(args)
def any_output(self):
return any([self.args.dump_source, self.args.dump_xml])
def safe_print(self, *args, **kwargs):
if not self.any_output():
print(*args, **kwargs)
def run(self):
data_input = self.args.infile.read()
tree = parse(data_input, Code)
if self.args.dump_xml:
print(thing2xml(tree, pretty=True).decode())
graph = Graph(tree)
if self.args.dump_source:
print(graph.get_source())
if self.args.preview:
graph.dot.view()
if self.args.outfile:
graph.save(self.args.outfile.name)
self.safe_print("Saved graph to %s successfull" % (self.args.outfile.name))
|
Use vm instead of evals binding | var vm = require('vm');
exports.javascript = function(element, code, filename) {
var document = element.ownerDocument,
window = document.parentWindow;
if (window) {
var ctx = window.__scriptContext;
if (!ctx) {
window.__scriptContext = ctx = vm.createContext({});
ctx.__proto__ = window;
}
var tracelimitbak = Error.stackTraceLimit;
Error.stackTraceLimit = 100;
try {
vm.Script.runInContext(code, ctx, filename);
}
catch(e) {
document.trigger(
'error', 'Running ' + filename + ' failed.',
{error: e, filename: filename}
);
}
Error.stackTraceLimit = tracelimitbak;
}
};
| var Context = process.binding('evals').Context,
// TODO: Remove .Script when bumping req'd node version to >= 5.0
Script = process.binding('evals').NodeScript || process.binding('evals').Script;
exports.javascript = function(element, code, filename) {
var document = element.ownerDocument,
window = document.parentWindow;
if (window) {
var ctx = window.__scriptContext;
if (!ctx) {
window.__scriptContext = ctx = new Context();
ctx.__proto__ = window;
}
var tracelimitbak = Error.stackTraceLimit;
Error.stackTraceLimit = 100;
try {
Script.runInContext(code, ctx, filename);
}
catch(e) {
document.trigger(
'error', 'Running ' + filename + ' failed.',
{error: e, filename: filename}
);
}
Error.stackTraceLimit = tracelimitbak;
}
};
|
Change rel paths into abspaths and use helper module | #!/bin/env python
#
# glidein_top.py
#
# Description:
# Execute a top command on a condor job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>]
#
# Author:
# Igor Sfiligoi (May 2007)
#
# License:
# Fermitools
#
import sys,os.path
sys.path.append(os.path.join(sys.path[0],"lib"))
sys.path.append(os.path.join(sys.path[0],"../lib"))
import glideinCmd
def argv_top(argv):
if len(argv)!=0:
raise RuntimeError, "Unexpected parameters starting with %s found!"%argv[0]
return ['top', '-b', '-n', '1']
glideinCmd.exe_cmd(argv_top)
| #!/bin/env python
#
# glidein_top
#
# Execute a top command in the same glidein as the user job
#
# Usage:
# glidein_top.py <cluster>.<process> [-name <schedd_name>] [-pool <pool_name> ] [-timeout <nr secs>
#
import os
import stat
import sys
sys.path.append("lib")
sys.path.append("../lib")
import glideinMonitor
def createTopMonitorFile(monitor_file_name,monitor_control_relname,
argv,condor_status):
fd=open(monitor_file_name,"w")
try:
fd.write("#!/bin/sh\n")
fd.write("top -b -n 1\n")
fd.write("echo Done > %s\n"%monitor_control_relname)
finally:
fd.close()
os.chmod(monitor_file_name,stat.S_IRWXU)
args=glideinMonitor.parseArgs(sys.argv[1:])
if len(args['argv'])!=0:
raise RuntimeError, "Unexpected parameters starting with %s found!"%args['argv'][0]
glideinMonitor.monitor(args['jid'],args['schedd_name'],args['pool_name'],
args['timeout'],
createTopMonitorFile,args['argv'])
|
Fix object storage apiType for S3 and Swift. | """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageManager(env.client)
accounts = mgr.list_accounts()
table = formatting.Table(['id', 'name', 'apiType'])
table.sortby = 'id'
api_type = None
for account in accounts:
if 'vendorName' in account and account['vendorName'] == 'Swift':
api_type = 'Swift'
elif 'Cleversafe' in account['serviceResource']['name']:
api_type = 'S3'
table.add_row([
account['id'],
account['username'],
api_type,
])
env.fout(table)
| """List Object Storage accounts."""
# :license: MIT, see LICENSE for more details.
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import formatting
@click.command()
@environment.pass_env
def cli(env):
"""List object storage accounts."""
mgr = SoftLayer.ObjectStorageManager(env.client)
accounts = mgr.list_accounts()
table = formatting.Table(['id', 'name', 'apiType'])
table.sortby = 'id'
global api_type
for account in accounts:
if 'vendorName' in account and 'Swift' == account['vendorName']:
api_type = 'Swift'
elif 'Cleversafe' in account['serviceResource']['name']:
api_type = 'S3'
table.add_row([
account['id'],
account['username'],
api_type,
])
env.fout(table)
|
Support .woff2 extension in 05-code-splitting | var path = require('path');
var webpack = require('webpack');
module.exports = {
cache: true,
entry: {
jquery: './app/jquery',
bootstrap: './app/bootstrap'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
// Required for bootstrap fonts
{ test: /\.woff(\d+)?$/, loader: 'url?prefix=font/&limit=5000&mimetype=application/font-woff' },
{ test: /\.ttf$/, loader: 'file?prefix=font/' },
{ test: /\.eot$/, loader: 'file?prefix=font/' },
{ test: /\.svg$/, loader: 'file?prefix=font/' }
]
},
plugins: [
new webpack.ProvidePlugin({
// Automatically inject jQuery
// This is required by many jQuery plugins
jQuery: "jquery",
$: "jquery"
})
]
};
| var path = require('path');
var webpack = require('webpack');
module.exports = {
cache: true,
entry: {
jquery: './app/jquery',
bootstrap: './app/bootstrap'
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: 'dist/',
filename: '[name].js',
chunkFilename: '[chunkhash].js'
},
module: {
loaders: [
{ test: /\.css$/, loader: 'style!css' },
// Required for bootstrap fonts
{ test: /\.woff$/, loader: 'url?prefix=font/&limit=5000&mimetype=application/font-woff' },
{ test: /\.ttf$/, loader: 'file?prefix=font/' },
{ test: /\.eot$/, loader: 'file?prefix=font/' },
{ test: /\.svg$/, loader: 'file?prefix=font/' }
]
},
plugins: [
new webpack.ProvidePlugin({
// Automatically inject jQuery
// This is required by many jQuery plugins
jQuery: "jquery",
$: "jquery"
})
]
};
|
Fix deprecration warnings for pytest | import pytest
from snakeeyes.app import create_app
@pytest.fixture(scope='session')
def app():
"""
Setup our flask test app, this only gets executed once.
:return: Flask app
"""
params = {
'DEBUG': False,
'TESTING': True,
'WTF_CSRF_ENABLED': False
}
_app = create_app(settings_override=params)
# Establish an application context before running the tests.
ctx = _app.app_context()
ctx.push()
yield _app
ctx.pop()
@pytest.fixture(scope='function')
def client(app):
"""
Setup an app client, this gets executed for each test function.
:param app: Pytest fixture
:return: Flask app client
"""
yield app.test_client()
| import pytest
from snakeeyes.app import create_app
@pytest.yield_fixture(scope='session')
def app():
"""
Setup our flask test app, this only gets executed once.
:return: Flask app
"""
params = {
'DEBUG': False,
'TESTING': True,
'WTF_CSRF_ENABLED': False
}
_app = create_app(settings_override=params)
# Establish an application context before running the tests.
ctx = _app.app_context()
ctx.push()
yield _app
ctx.pop()
@pytest.yield_fixture(scope='function')
def client(app):
"""
Setup an app client, this gets executed for each test function.
:param app: Pytest fixture
:return: Flask app client
"""
yield app.test_client()
|
Fix Drag&Drop uploading w/o forward slash at end of URL | window.addEventListener("load", () => {
const SUPPORTED_TYPES = ["Files", "application/x-moz-file"];
let body = document.getElementsByTagName("body")[0];
body.addEventListener("dragover", (ev) => {
if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.contains(el)))
ev.preventDefault();
});
body.addEventListener("drop", (ev) => {
if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.contains(el))) {
ev.preventDefault();
let url = document.URL;
if(url[url.length - 1] != "/")
url += "/";
for(let i = ev.dataTransfer.files.length - 1; i >= 0; --i) {
let file = ev.dataTransfer.files[i];
let request = new XMLHttpRequest();
request.open('PUT', url + file.name);
request.send(file);
}
}
});
});
| window.addEventListener("load", () => {
const SUPPORTED_TYPES = ["Files", "application/x-moz-file"];
let body = document.getElementsByTagName("body")[0];
body.addEventListener("dragover", (ev) => {
if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.includes(el)))
ev.preventDefault();
});
body.addEventListener("drop", (ev) => {
if(SUPPORTED_TYPES.find(el => ev.dataTransfer.types.includes(el))) {
ev.preventDefault();
for(let i = ev.dataTransfer.files.length - 1; i >= 0; --i) {
let file = ev.dataTransfer.files[i];
let request = new XMLHttpRequest();
request.open('PUT', document.URL + file.name);
request.send(file);
}
}
});
});
|
Use custom reports backend for test DB in Jenkins
As Django test runner does not support replica DBs (MIRROR setting
just redirects to use the other connection), change the default
connection to use the custom engine when running in jenkins.
Tests fail during BST due to the connection not being UTC if using
the default postgres engine. | import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'cla_backend.apps.reports.db.backend',
'NAME': os.environ.get('DB_USERNAME', ''),
'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ''),
'USER': os.environ.get('DB_USERNAME', ''),
'PASSWORD': os.environ.get('DB_PASSWORD', ''),
'HOST': os.environ.get('DB_HOST', ''),
'PORT': os.environ.get('DB_PORT', ''),
}
}
JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner'
#HOST_NAME = ""
ALLOWED_HOSTS = [
'*'
]
| import os
from .testing import *
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
('CLA', 'cla-alerts@digital.justice.gov.uk'),
)
MANAGERS = ADMINS
INSTALLED_APPS += ('django_jenkins',)
JENKINS_TASKS = (
'django_jenkins.tasks.with_coverage',
)
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': os.environ.get('DB_USERNAME', ''),
'TEST_NAME': 'test_cla_backend%s' % os.environ.get('BACKEND_TEST_DB_SUFFIX', ''),
'USER': os.environ.get('DB_USERNAME', ''),
'PASSWORD': os.environ.get('DB_PASSWORD', ''),
'HOST': os.environ.get('DB_HOST', ''),
'PORT': os.environ.get('DB_PORT', ''),
}
}
JENKINS_TEST_RUNNER = 'core.testing.CLADiscoverRunner'
#HOST_NAME = ""
ALLOWED_HOSTS = [
'*'
]
|
Reorder error handler and '/' route | const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mojibox');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
const userRoutes = require('./routes/users');
const emoticonRoutes = require('./routes/emoticons');
app.use('/user', userRoutes);
app.use('/user/:username/collection', emoticonRoutes);
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.get('/', function(req, res, next) {
res.redirect('/user');
});
app.listen(3000, function() {
console.log('Server is listening on port 3000');
});
| const express = require('express'),
app = express(),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mojibox');
app.set('view engine', 'pug');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(methodOverride('_method'));
const userRoutes = require('./routes/users');
const emoticonRoutes = require('./routes/emoticons');
app.use('/user', userRoutes);
app.use('/user/:username/collection', emoticonRoutes);
app.get('/', function(req, res, next) {
res.redirect('/user');
});
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
app.listen(3000, function() {
console.log('Server is listening on port 3000');
});
|
Send a 404 if not found. | module.exports = function(req, res, next){
"use strict";
var Strings = require('../../../strings'),
Response = require('../../helpers/response'),
content = require('../../../entities/content'),
strings = new Strings('en'),
response = new Response()
function onGetContent(err, doc){
if(err){
response.write(response.STATUS_CODES.NOT_FOUND, JSON.stringify(err), res);
}
else {
if(doc.node && doc.node._id){
req.parent = doc.node._id.toString();
}
next();
}
}
content.getById(req.params.id, onGetContent);
}; | module.exports = function(req, res, next){
"use strict";
var Strings = require('../../../strings'),
Response = require('../../helpers/response'),
content = require('../../../entities/content'),
strings = new Strings('en'),
response = new Response()
function onGetContent(err, doc){
if(err){
response.write(response.STATUS_CODES.SERVER_ERROR, JSON.stringify(err), res);
}
else {
if(doc.node && doc.node._id){
req.parent = doc.node._id.toString();
}
next();
}
}
content.getById(req.params.id, onGetContent);
}; |
Bump version for v0.7.0 release | # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
| # -*- coding: utf-8 -*-
#
# Author: Taylor Smith <taylor.smith@alkaline-ml.com>
#
# The pyramid module
__version__ = "0.7.0-dev"
try:
# this var is injected in the setup build to enable
# the retrieval of the version number without actually
# importing the un-built submodules.
__PYRAMID_SETUP__
except NameError:
__PYRAMID_SETUP__ = False
if __PYRAMID_SETUP__:
import sys
import os
sys.stderr.write('Partial import of pyramid during the build process.' + os.linesep)
else:
# check that the build completed properly. This prints an informative
# message in the case that any of the C code was not properly compiled.
from . import __check_build
__all__ = [
'arima',
'compat',
'datasets',
'utils'
]
def setup_module(module):
import numpy as np
import random
_random_seed = int(np.random.uniform() * (2 ** 31 - 1))
np.random.seed(_random_seed)
random.seed(_random_seed)
|
Upgrade dependency appdirs to ==1.4.3 | import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.3',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
| import os
from setuptools import setup
from withtool import __version__
def read(fname):
path = os.path.join(os.path.dirname(__file__), fname)
with open(path, encoding='utf-8') as f:
return f.read()
setup(
name='with',
version=__version__,
description='A shell context manager',
long_description=read('README.rst'),
author='Renan Ivo',
author_email='renanivom@gmail.com',
url='https://github.com/renanivo/with',
keywords='context manager shell command line repl',
scripts=['bin/with'],
install_requires=[
'appdirs==1.4.2',
'docopt==0.6.2',
'prompt-toolkit==1.0',
'python-slugify==1.2.1',
],
packages=['withtool'],
classifiers=[
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
Check for night evt type | 'use babel';
import EventEmitter from 'events';
export default class TimeEmitter extends EventEmitter {
constructor(dayTime, nightTime) {
let curTime = new Date();
let msToDay = Math.abs(curTime - dayTime);
let msToNight = Math.abs(curTime - nightTime);
this.dayTimerId = setTimeout(() => this.emit('day'), msToDay);
this.nightTimerId = setTimeout(() => this.emit('night'), msToNight);
}
snooze(evt, interval) {
if (evt === 'day')
this.dayTimerId = setTimeout(() => this.emit('day'), interval);
else if (evt === 'night')
this.nightTimerId = setTimeout(() => this.emit('night'), interval);
}
dispose() {
clearTimeout(this.dayTimerId);
clearTimeout(this.nightTimerId);
}
}
| 'use babel';
import EventEmitter from 'events';
export default class TimeEmitter extends EventEmitter {
constructor(dayTime, nightTime) {
let curTime = new Date();
let msToDay = Math.abs(curTime - dayTime);
let msToNight = Math.abs(curTime - nightTime);
this.dayTimerId = setTimeout(() => this.emit('day'), msToDay);
this.nightTimerId = setTimeout(() => this.emit('night'), msToNight);
}
snooze(evt, interval) {
if (evt === 'day')
this.dayTimerId = setTimeout(() => this.emit('day'), interval);
else
this.nightTimerId = setTimeout(() => this.emit('night'), interval);
}
dispose() {
clearTimeout(this.dayTimerId);
clearTimeout(this.nightTimerId);
}
}
|
Change prefix for alerts api | import { createActionType } from 'ethical-jobs-redux';
import Api from 'ethical-jobs-sdk';
/**
* API prefix for the subscriptions API
*
* @type {string}
*/
const prefix = '/alerts';
/*
|--------------------------------------------------------------------------
| Action Types
|--------------------------------------------------------------------------
*/
export const CREATE = createActionType('SUBSCRIPTIONS/CREATE');
export const FETCH_COLLECTION = createActionType('SUBSCRIPTIONS/FETCH_COLLECTION');
export const FETCH_ENTITY = createActionType('SUBSCRIPTIONS/FETCH_ENTITY');
export const DELETE = createActionType('SUBSCRIPTIONS/DELETE');
export const CONFIRM = createActionType('SUBSCRIPTIONS/CONFIRM');
/*
|--------------------------------------------------------------------------
| Async Actions
|--------------------------------------------------------------------------
*/
export const create = params => ({
type: CREATE,
payload: Api.post(prefix+'/subscriptions', params),
});
export const fetchCollection = params => ({
type: FETCH_COLLECTION,
payload: Api.get(prefix+'/subscriptions', params),
});
export const fetchEntity = id => ({
type: FETCH_ENTITY,
payload: Api.get(prefix+`/subscriptions/${id}`),
});
export const destroy = id => ({
type: DELETE,
payload: Api.delete(prefix+`/subscriptions/${id}`),
});
export const confirm = (id, params) => ({
type: CONFIRM,
payload: Api.put(prefix+`/subscriptions/${id}`, params),
}); | import { createActionType } from 'ethical-jobs-redux';
import Api from 'ethical-jobs-sdk';
/*
|--------------------------------------------------------------------------
| Action Types
|--------------------------------------------------------------------------
*/
export const CREATE = createActionType('SUBSCRIPTIONS/CREATE');
export const FETCH_COLLECTION = createActionType('SUBSCRIPTIONS/FETCH_COLLECTION');
export const FETCH_ENTITY = createActionType('SUBSCRIPTIONS/FETCH_ENTITY');
export const DELETE = createActionType('SUBSCRIPTIONS/DELETE');
export const CONFIRM = createActionType('SUBSCRIPTIONS/CONFIRM');
/*
|--------------------------------------------------------------------------
| Async Actions
|--------------------------------------------------------------------------
*/
export const create = params => ({
type: CREATE,
payload: Api.post('/email/subscriptions', params),
});
export const fetchCollection = params => ({
type: FETCH_COLLECTION,
payload: Api.get('/email/subscriptions', params),
});
export const fetchEntity = id => ({
type: FETCH_ENTITY,
payload: Api.get(`/email/subscriptions/${id}`),
});
export const destroy = id => ({
type: DELETE,
payload: Api.delete(`/email/subscriptions/${id}`),
});
export const update = (id) => ({
type: CONFIRM,
payload: Api.get(`/email/subscriptions/${id}/confirmations`),
}); |
:ambulance: Fix '__construct() cannot declare a return type' | <?php
/*
* This file is part of Laravel Database.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Database.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Database\Migrations;
use BrianFaust\Database\Schema\Blueprint;
abstract class Migration
{
protected $connection;
protected $schema;
public function __construct()
{
$this->schema = \DB::getSchemaBuilder();
$this->schema->blueprintResolver(function ($table, $callback) {
return new Blueprint($table, $callback);
});
}
public function getConnection()
{
return $this->connection;
}
}
| <?php
/*
* This file is part of Laravel Database.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
declare(strict_types=1);
/*
* This file is part of Laravel Database.
*
* (c) Brian Faust <hello@brianfaust.de>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace BrianFaust\Database\Migrations;
use BrianFaust\Database\Schema\Blueprint;
abstract class Migration
{
protected $connection;
protected $schema;
public function __construct(): void
{
$this->schema = \DB::getSchemaBuilder();
$this->schema->blueprintResolver(function ($table, $callback) {
return new Blueprint($table, $callback);
});
}
public function getConnection()
{
return $this->connection;
}
}
|
Debug version to check codeship.
--HG--
branch : schema-templates/fix-codeship-issue | from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .models import SchemaTemplate
models.signals.post_save.connect(signals.create_schema,
sender=SchemaTemplate,
dispatch_uid='create-schema-template')
models.signals.post_delete.connect(signals.drop_schema, sender=SchemaTemplate)
@receiver(signals.schema_aware_operation, weak=False)
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
print schema.schema
print kwargs
function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))
| from django.apps import AppConfig
from django.db import models
from django.dispatch import receiver
from boardinghouse.schema import activate_schema
class BoardingHouseTemplateConfig(AppConfig):
name = 'boardinghouse.contrib.template'
def ready(self):
from boardinghouse import signals
from .models import SchemaTemplate
models.signals.post_save.connect(signals.create_schema,
sender=SchemaTemplate,
dispatch_uid='create-schema-template')
models.signals.post_delete.connect(signals.drop_schema, sender=SchemaTemplate)
@receiver(signals.schema_aware_operation, weak=False)
def execute_on_all_templates(sender, db_table, function, **kwargs):
for schema in SchemaTemplate.objects.all():
activate_schema(schema.schema)
function(*kwargs.get('args', []), **kwargs.get('kwargs', {}))
|
Switch .innerText DOM output to .textContent
.innerText started as an IE-ism, but .textContent is the WC3 standard. Eventually, IE9+ supported textContent, but Firefox stood firm (or "stubborn") on NOT supporting innerText. As stands, innerText will break this example for modern Firefox browsers, and I don't believe that punishing IE8 users is necessarily a bad thing. ;)
Mind, there's ways to normalize use of this property for maximum browser compat, but I believe the spirit of this example is to keep the code as lean as possible. | /* global cloak */
var form = document.querySelector('#input-form');
var input = document.querySelector('#input');
var messages = document.querySelector('#messages');
var counter = document.querySelector('#counter');
cloak.configure({
messages: {
chat: function(msg) {
var message = document.createElement('div');
message.textContent = msg;
message.className = 'msg';
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
},
userCount: function(count) {
counter.textContent = count;
}
},
});
cloak.run('http://localhost:8090');
form.addEventListener('submit', function(e) {
e.preventDefault();
var msg = input.value;
if (msg.length < 1) {
return;
}
cloak.message('chat', msg);
input.value = '';
});
| /* global cloak */
var form = document.querySelector('#input-form');
var input = document.querySelector('#input');
var messages = document.querySelector('#messages');
var counter = document.querySelector('#counter');
cloak.configure({
messages: {
chat: function(msg) {
var message = document.createElement('div');
message.innerText = msg;
message.className = 'msg';
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
},
userCount: function(count) {
counter.innerText = count;
}
},
});
cloak.run('http://localhost:8090');
form.addEventListener('submit', function(e) {
e.preventDefault();
var msg = input.value;
if (msg.length < 1) {
return;
}
cloak.message('chat', msg);
input.value = '';
});
|
Make search field input required | <?php $unique_id = esc_attr(uniqid('search-form-')); ?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url(home_url('/')); ?>">
<label class="sr-only" for="<?php echo $unique_id; ?>"><?php echo _x('Search for:', 'label', 'keitaro'); ?></label>
<div class="input-group">
<input type="search" id="<?php echo $unique_id; ?>" class="form-control search-field" placeholder="<?php echo esc_attr_x('Search …', 'placeholder', 'keitaro'); ?>" required="required" value="<?php echo get_search_query(); ?>" name="s" />
<span class="input-group-btn">
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div>
</form> | <?php $unique_id = esc_attr(uniqid('search-form-')); ?>
<form role="search" method="get" class="search-form" action="<?php echo esc_url(home_url('/')); ?>">
<label class="sr-only" for="<?php echo $unique_id; ?>"><?php echo _x('Search for:', 'label', 'keitaro'); ?></label>
<div class="input-group">
<input type="search" id="<?php echo $unique_id; ?>" class="form-control search-field" placeholder="<?php echo esc_attr_x('Search …', 'placeholder', 'keitaro'); ?>" value="<?php echo get_search_query(); ?>" name="s" />
<span class="input-group-btn">
<button type="submit" class="btn btn-default"><span class="glyphicon glyphicon-search"></span></button>
</span>
</div>
</form> |
Remove the extent in the regions query for DO to get all the available regions without filtering | var BaseCollection = require('./data-observatory-base-collection');
var BaseModel = require('../../components/custom-list/custom-list-item-model');
var REGIONS_QUERY = "SELECT count(*) num_measurements, tag.key region_id, tag.value region_name FROM (SELECT * FROM OBS_GetAvailableNumerators() WHERE jsonb_pretty(numer_tags) LIKE '%subsection/%') numers, Jsonb_Each(numers.numer_tags) tag WHERE tag.key like 'section%' GROUP BY tag.key, tag.value ORDER BY region_name";
module.exports = BaseCollection.extend({
buildQuery: function () {
return REGIONS_QUERY;
},
model: function (attrs, opts) {
// label and val to custom list compatibility
var o = {};
o.val = attrs.region_id;
o.label = attrs.region_name.replace(/["]+/g, '');
o.renderOptions = {
measurements: attrs.num_measurements
};
return new BaseModel(o);
}
});
| var BaseCollection = require('./data-observatory-base-collection');
var BaseModel = require('../../components/custom-list/custom-list-item-model');
var REGIONS_QUERY = "SELECT count(*) num_measurements, tag.key region_id, tag.value region_name FROM (SELECT * FROM OBS_GetAvailableNumerators((SELECT ST_SetSRID(ST_Extent(the_geom), 4326) FROM ({{{ query }}}) q)) WHERE jsonb_pretty(numer_tags) LIKE '%subsection/%') numers, Jsonb_Each(numers.numer_tags) tag WHERE tag.key like 'section%' GROUP BY tag.key, tag.value";
module.exports = BaseCollection.extend({
buildQuery: function () {
return REGIONS_QUERY;
},
model: function (attrs, opts) {
// label and val to custom list compatibility
var o = {};
o.val = attrs.region_id;
o.label = attrs.region_name.replace(/["]+/g, '');
o.renderOptions = {
measurements: attrs.num_measurements
};
return new BaseModel(o);
}
});
|
Remove Todoist from the broken list | package todoist
import (
"fmt"
"golang.org/x/oauth2"
"log"
)
func buildConfig() *oauth2.Config {
// todoist.com requires ClientID and ClientSecret to be set as parameters
// in the POST.
//oauth2.RegisterBrokenAuthHeaderProvider("https://todoist.com")
return &oauth2.Config{
ClientID: Oauth2ClientID,
ClientSecret: Oauth2ClientSecret,
Scopes: []string{"data:read_write,data:delete,project:delete"},
RedirectURL: "https://freyr.erifax.org/tripist/",
Endpoint: oauth2.Endpoint{
AuthURL: "https://todoist.com/oauth/authorize",
TokenURL: "https://todoist.com/oauth/access_token",
},
}
}
func Authorize() *oauth2.Token {
conf := buildConfig()
// state=erifax -- totally a random string.
url := conf.AuthCodeURL("erifax", oauth2.AccessTypeOffline)
fmt.Println("1. Browse to: " + url)
fmt.Println("2. Grant access and copy the 'code' parameter displayed.")
fmt.Print("\nEnter code: ")
code := ""
fmt.Scanln(&code)
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatal(err)
}
return token
}
| package todoist
import (
"fmt"
"golang.org/x/oauth2"
"log"
)
func buildConfig() *oauth2.Config {
// todoist.com requires ClientID and ClientSecret to be set as parameters
// in the POST.
oauth2.RegisterBrokenAuthHeaderProvider("https://todoist.com")
return &oauth2.Config{
ClientID: Oauth2ClientID,
ClientSecret: Oauth2ClientSecret,
Scopes: []string{"data:read_write,data:delete,project:delete"},
RedirectURL: "https://freyr.erifax.org/tripist/",
Endpoint: oauth2.Endpoint{
AuthURL: "https://todoist.com/oauth/authorize",
TokenURL: "https://todoist.com/oauth/access_token",
},
}
}
func Authorize() *oauth2.Token {
conf := buildConfig()
// state=erifax -- totally a random string.
url := conf.AuthCodeURL("erifax", oauth2.AccessTypeOffline)
fmt.Println("1. Browse to: " + url)
fmt.Println("2. Grant access and copy the 'code' parameter displayed.")
fmt.Print("\nEnter code: ")
code := ""
fmt.Scanln(&code)
token, err := conf.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatal(err)
}
return token
}
|
Add index by (gone_status is null) to users table | /**
* The *gone_status* is null for the active users. If it is not null then the
* user shows as deleted in any public contexts. Actual values can be:
* - 1: user is suspended but can be restored
* - 2: user (and their data) is fully deleted
*
* The *gone_at* is null if the *gone_status* is null, otherwise it is the last
* time the gone_status changed.
*/
export const up = (knex) => knex.schema.raw(`do $$begin
alter table users add column gone_status integer;
alter table users add column gone_at timestamptz;
alter table users add constraint users_gone_check
check ((gone_status is null) = (gone_at is null));
create index users_gone_status_not_null_idx on users ((gone_status is null));
-- Update gone status for already gone users
update users set gone_status = 2, gone_at = now()
where hashed_password is null or hashed_password = '';
end$$`);
export const down = (knex) => knex.schema.raw(`do $$begin
alter table users drop constraint users_gone_check;
alter table users drop column gone_status;
alter table users drop column gone_at;
end$$`);
| /**
* The *gone_status* is null for the active users. If it is not null then the
* user shows as deleted in any public contexts. Actual values can be:
* - 1: user is suspended but can be restored
* - 2: user (and their data) is fully deleted
*
* The *gone_at* is null if the *gone_status* is null, otherwise it is the last
* time the gone_status changed.
*/
export const up = (knex) => knex.schema.raw(`do $$begin
alter table users add column gone_status integer;
alter table users add column gone_at timestamptz;
alter table users add constraint users_gone_check
check ((gone_status is null) = (gone_at is null));
-- Update gone status for already gone users
update users set gone_status = 2, gone_at = now()
where hashed_password is null or hashed_password = '';
end$$`);
export const down = (knex) => knex.schema.raw(`do $$begin
alter table users drop constraint users_gone_check;
alter table users drop column gone_status;
alter table users drop column gone_at;
end$$`);
|
Add placeholder text to URL form field | # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
validators.URL(message='A valid URL is required'),
not_blacklisted_nor_spam
],
render_kw={'placeholder': 'Original URL'}
)
recaptcha = RecaptchaField(
validators=[
Recaptcha(
'Please click on the reCAPTCHA field to prove you are a human'
)
]
)
| # -*- coding: utf-8 -*-
from flask_wtf import Form
from flask_wtf.recaptcha import RecaptchaField, Recaptcha
from wtforms import StringField, validators
from .validation import not_blacklisted_nor_spam
class ShortenedURLForm(Form):
url = StringField(
validators=[
validators.DataRequired(),
validators.URL(message='A valid URL is required'),
not_blacklisted_nor_spam
]
)
recaptcha = RecaptchaField(
validators=[
Recaptcha(
'Please click on the reCAPTCHA field to prove you are a human'
)
]
)
|
Fix NPE warning; use locale for toLowerCase | package org.jboss.as.remoting;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jboss.dmr.ModelNode;
/**
* Protocols that can be used for a remoting connection
*
* @author Stuart Douglas
*/
public enum Protocol {
REMOTE("remote"),
HTTP_REMOTING("http-remoting"),
HTTPS_REMOTING("https-remoting");
private static final Map<String, Protocol> MAP;
static {
final Map<String, Protocol> map = new HashMap<String, Protocol>();
for (Protocol value : values()) {
map.put(value.localName, value);
}
MAP = map;
}
public static Protocol forName(String localName) {
final Protocol value = localName != null ? MAP.get(localName.toLowerCase(Locale.ENGLISH)) : null;
return value == null && localName != null ? Protocol.valueOf(localName.toUpperCase(Locale.ENGLISH)) : value;
}
private final String localName;
Protocol(final String localName) {
this.localName = localName;
}
@Override
public String toString() {
return localName;
}
public ModelNode toModelNode() {
return new ModelNode().set(toString());
}
}
| package org.jboss.as.remoting;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.jboss.dmr.ModelNode;
/**
* Protocols that can be used for a remoting connection
*
* @author Stuart Douglas
*/
public enum Protocol {
REMOTE("remote"),
HTTP_REMOTING("http-remoting"),
HTTPS_REMOTING("https-remoting");
private static final Map<String, Protocol> MAP;
static {
final Map<String, Protocol> map = new HashMap<String, Protocol>();
for (Protocol value : values()) {
map.put(value.localName, value);
}
MAP = map;
}
public static Protocol forName(String localName) {
final Protocol value = localName != null ? MAP.get(localName.toLowerCase()) : null;
return value == null ? Protocol.valueOf(localName.toUpperCase(Locale.ENGLISH)) : value;
}
private final String localName;
Protocol(final String localName) {
this.localName = localName;
}
@Override
public String toString() {
return localName;
}
public ModelNode toModelNode() {
return new ModelNode().set(toString());
}
}
|
Enable Shapely speedups when available.
http://toblerity.org/shapely/manual.html#performance | from . import encoder
from . import decoder
# Enable Shapely "speedups" if available
# http://toblerity.org/shapely/manual.html#performance
from shapely import speedups
if speedups.available:
speedups.enable()
def decode(tile, y_coord_down=False):
vector_tile = decoder.TileData()
message = vector_tile.getMessage(tile, y_coord_down)
return message
def encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096,
on_invalid_geometry=None, round_fn=None, check_winding_order=True):
vector_tile = encoder.VectorTile(extents, on_invalid_geometry,
round_fn=round_fn,
check_winding_order=check_winding_order)
if (isinstance(layers, list)):
for layer in layers:
vector_tile.addFeatures(layer['features'], layer['name'],
quantize_bounds, y_coord_down)
else:
vector_tile.addFeatures(layers['features'], layers['name'],
quantize_bounds, y_coord_down)
return vector_tile.tile.SerializeToString()
| from . import encoder
from . import decoder
def decode(tile, y_coord_down=False):
vector_tile = decoder.TileData()
message = vector_tile.getMessage(tile, y_coord_down)
return message
def encode(layers, quantize_bounds=None, y_coord_down=False, extents=4096,
on_invalid_geometry=None, round_fn=None, check_winding_order=True):
vector_tile = encoder.VectorTile(extents, on_invalid_geometry,
round_fn=round_fn,
check_winding_order=check_winding_order)
if (isinstance(layers, list)):
for layer in layers:
vector_tile.addFeatures(layer['features'], layer['name'],
quantize_bounds, y_coord_down)
else:
vector_tile.addFeatures(layers['features'], layers['name'],
quantize_bounds, y_coord_down)
return vector_tile.tile.SerializeToString()
|
Remove reference to old splplash.html | 'use strict';
/**
* Render the main application page
*/
exports.renderIndex = function (req, res) {
res.render('modules/core/server/views/index', {
user: req.user || null
});
};
/**
* Render the server error page
*/
exports.renderServerError = function (req, res) {
res.status(500).render('modules/core/server/views/500', {
error: 'Oops! Something went wrong...'
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function (req, res) {
res.status(404).format({
'text/html': function () {
res.render('modules/core/server/views/404', {
url: req.originalUrl
});
},
'application/json': function () {
res.json({
error: 'Path not found'
});
},
'default': function () {
res.send('Path not found');
}
});
};
| 'use strict';
/**
* Render the splash page of application
*/
exports.renderSplash = function (req,res) {
res.render('modules/core/server/views/splash', {
user: req.user || null
});
};
/**
* Render the main application page
*/
exports.renderIndex = function (req, res) {
res.render('modules/core/server/views/index', {
user: req.user || null
});
};
/**
* Render the server error page
*/
exports.renderServerError = function (req, res) {
res.status(500).render('modules/core/server/views/500', {
error: 'Oops! Something went wrong...'
});
};
/**
* Render the server not found responses
* Performs content-negotiation on the Accept HTTP header
*/
exports.renderNotFound = function (req, res) {
res.status(404).format({
'text/html': function () {
res.render('modules/core/server/views/404', {
url: req.originalUrl
});
},
'application/json': function () {
res.json({
error: 'Path not found'
});
},
'default': function () {
res.send('Path not found');
}
});
};
|
Refactor the ever living hell out of this. | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns[:]
return c
def transform(self, fn):
c = self._clone()
c._transform_fns.append(fn)
return c
def iterator(self):
for item in super(TransformQuerySet, self).iterator()
for func in self._transform_fns:
func(item)
yield item
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
| from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone(klass, setup, **kw)
c._transform_fns = self._transform_fns
return c
def transform(self, fn):
self._transform_fns.append(fn)
return self
def iterator(self):
result_iter = super(TransformQuerySet, self).iterator()
if self._transform_fns:
results = list(result_iter)
for fn in self._transform_fns:
fn(results)
return iter(results)
return result_iter
class TransformManager(models.Manager):
def get_query_set(self):
return TransformQuerySet(self.model)
|
Change index to OpenAddresses schema | import sys
import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Elasticsearch([{'host': ELASTICSEARCH_HOST}], http_auth=ELASTICSEARCH_AUTH)
else:
es = Elasticsearch()
files_given = sys.argv
for file_name in files_given:
if file_name = 'index_addresses.py':
continue
else:
file_path = file_name
print 'adding ' + file_path
with open(file_path, 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
current_row = 0
for row in csv_reader:
current_row += 1
if current_row == 1:
csv_reader.fieldnames = row['undefined-fieldnames']
continue
address = row
es.index(index='addresses', doc_type='address', id=current_row-1, body={'NUMBER': address[' NUMBER'], 'STREET': address[' STREET'], 'ADDRESS': address[' NUMBER'] + ' ' + address[' STREET'], 'X': address['LON'], 'Y': address[' LAT']})
csvfile.close()
| import csv
import re
import os
from urlparse import urlparse
from elasticsearch import Elasticsearch
if os.environ.get('BONSAI_URL'):
url = urlparse(os.environ['BONSAI_URL'])
bonsai_tuple = url.netloc.partition('@')
ELASTICSEARCH_HOST = bonsai_tuple[2]
ELASTICSEARCH_AUTH = bonsai_tuple[0]
es = Elasticsearch([{'host': ELASTICSEARCH_HOST}], http_auth=ELASTICSEARCH_AUTH)
else:
es = Elasticsearch()
with open('data/ParcelCentroids.csv', 'r') as csvfile:
print "open file"
csv_reader = csv.DictReader(csvfile, fieldnames=[], restkey='undefined-fieldnames', delimiter=',')
current_row = 0
for row in csv_reader:
current_row += 1
if current_row == 1:
csv_reader.fieldnames = row['undefined-fieldnames']
continue
address = row
if re.match('\d+', address['PVANUM']):
es.index(index='addresses', doc_type='address', id=address['PVANUM'], body={'PVANUM': address['PVANUM'], 'NUM1': address['NUM1'], 'NAME': address['NAME'], 'TYPE': address['TYPE'], 'ADDRESS': address['ADDRESS'], 'UNIT': address['UNIT'], 'X': address['X'], 'Y': address['Y']})
csvfile.close()
|
Fix build: Set correct error name
Former-commit-id: c3290300916c3c7de9d86b6f02cbb7290fe10123 | export class CompositionError extends Error {
constructor(classInstance, message, component) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Component:', component);
this.name = 'CompositionError';
}
}
export class DependencyError extends Error {
constructor(classInstance, message, activeModule, dependencyModule = false) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Active module:', activeModule);
if (!process && dependencyModule) console.error('Dependency published by module:', dependencyModule);
this.name = 'DependencyError';
}
}
export class ManagerError extends Error {
constructor(classInstance, message, component, activeModule = false) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Component:', dependencyModule);
if (!process && activeModule) console.error('Active module:', activeModule);
this.name = 'ManagerError';
}
}
| export class CompositionError extends Error {
constructor(classInstance, message, component) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Component:', component);
this.name = 'CompositionError';
}
}
export class DependencyError extends Error {
constructor(classInstance, message, activeModule, dependencyModule = false) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Active module:', activeModule);
if (!process && dependencyModule) console.error('Dependency published by module:', dependencyModule);
this.name = 'DependencyError';
}
}
export class ManagerError extends Error {
constructor(classInstance, message, component, activeModule = false) {
super(`@${classInstance}: ${message}`);
const stackArray = this.stack.split('\n');
stackArray.splice(1, 2);
this.stack = stackArray.join('\n');
if (!process) console.error('Component:', dependencyModule);
if (!process && activeModule) console.error('Active module:', activeModule);
this.name = 'DependencyError';
}
}
|
Add convenience method for ContextElements | package slack
// ContextBlock defines data that is used to display message context, which can
// include both images and text.
//
// More Information: https://api.slack.com/reference/messaging/blocks#actions
type ContextBlock struct {
Type MessageBlockType `json:"type"`
BlockID string `json:"block_id,omitempty"`
Elements ContextElements `json:"elements"`
}
// blockType returns the type of the block
func (s ContextBlock) blockType() MessageBlockType {
return s.Type
}
type ContextElements struct {
ImageElements []*ImageBlockElement
TextObjects []*TextBlockObject
}
// NewContextElements is a convenience method for generating ContextElements
func NewContextElements(imageElements []*ImageBlockElement, textObjects []*TextBlockObject) ContextElements {
return ContextElements{
ImageElements: imageElements,
TextObjects: textObjects,
}
}
// NewContextBlock returns a new instance of a context block
func NewContextBlock(blockID string, elements ContextElements) *ContextBlock {
return &ContextBlock{
Type: mbtContext,
BlockID: blockID,
Elements: elements,
}
}
| package slack
// ContextBlock defines data that is used to display message context, which can
// include both images and text.
//
// More Information: https://api.slack.com/reference/messaging/blocks#actions
type ContextBlock struct {
Type MessageBlockType `json:"type"`
BlockID string `json:"block_id,omitempty"`
Elements ContextElements `json:"elements"`
}
// blockType returns the type of the block
func (s ContextBlock) blockType() MessageBlockType {
return s.Type
}
type ContextElements struct {
ImageElements []*ImageBlockElement
TextObjects []*TextBlockObject
}
// NewContextBlock returns a new instance of a context block
func NewContextBlock(blockID string, elements ContextElements) *ContextBlock {
return &ContextBlock{
Type: mbtContext,
BlockID: blockID,
Elements: elements,
}
}
|
Change from Brixton to Camden | /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.cli.compiler;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import org.springframework.boot.cli.compiler.DependencyManagementBomTransformation;
import org.springframework.boot.cli.compiler.GenericBomAstTransformation;
/**
* @author Dave Syer
*
*/
@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
public class SpringCloudBomAstTransformation extends GenericBomAstTransformation {
private static final String SPRING_CLOUD_VERSION = "Camden.BUILD-SNAPSHOT";
@Override
protected String getBomModule() {
return "org.springframework.cloud:spring-cloud-starter-parent:" + SPRING_CLOUD_VERSION;
}
@Override
public int getOrder() {
return DependencyManagementBomTransformation.ORDER - 50;
}
}
| /*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.cloud.cli.compiler;
import org.codehaus.groovy.control.CompilePhase;
import org.codehaus.groovy.transform.GroovyASTTransformation;
import org.springframework.boot.cli.compiler.DependencyManagementBomTransformation;
import org.springframework.boot.cli.compiler.GenericBomAstTransformation;
/**
* @author Dave Syer
*
*/
@GroovyASTTransformation(phase = CompilePhase.CONVERSION)
public class SpringCloudBomAstTransformation extends GenericBomAstTransformation {
private static final String SPRING_CLOUD_VERSION = "Brixton.BUILD-SNAPSHOT";
@Override
protected String getBomModule() {
return "org.springframework.cloud:spring-cloud-starter-parent:" + SPRING_CLOUD_VERSION;
}
@Override
public int getOrder() {
return DependencyManagementBomTransformation.ORDER - 50;
}
}
|
wa: Add ApkWorkload to default imports | from wa.framework import pluginloader, signal
from wa.framework.command import Command, ComplexCommand, SubCommand
from wa.framework.configuration import settings
from wa.framework.configuration.core import Status
from wa.framework.exception import HostError, JobError, InstrumentError, ConfigError
from wa.framework.exception import (ResultProcessorError, ResourceError,
CommandError, ToolError)
from wa.framework.exception import (WAError, NotFoundError, ValidationError,
WorkloadError)
from wa.framework.exception import WorkerThreadError, PluginLoaderError
from wa.framework.instrumentation import (Instrument, very_slow, slow, normal, fast,
very_fast)
from wa.framework.plugin import Plugin, Parameter
from wa.framework.processor import ResultProcessor
from wa.framework.resource import (NO_ONE, JarFile, ApkFile, ReventFile, File,
Executable)
from wa.framework.workload import Workload, ApkWorkload, ApkUiautoWorkload, ReventWorkload
| from wa.framework import pluginloader, signal
from wa.framework.command import Command, ComplexCommand, SubCommand
from wa.framework.configuration import settings
from wa.framework.configuration.core import Status
from wa.framework.exception import HostError, JobError, InstrumentError, ConfigError
from wa.framework.exception import (ResultProcessorError, ResourceError,
CommandError, ToolError)
from wa.framework.exception import (WAError, NotFoundError, ValidationError,
WorkloadError)
from wa.framework.exception import WorkerThreadError, PluginLoaderError
from wa.framework.instrumentation import (Instrument, very_slow, slow, normal, fast,
very_fast)
from wa.framework.plugin import Plugin, Parameter
from wa.framework.processor import ResultProcessor
from wa.framework.resource import (NO_ONE, JarFile, ApkFile, ReventFile, File,
Executable)
from wa.framework.workload import Workload, ApkUiautoWorkload, ReventWorkload
|
Remove admin autodiscovery since Django does that for us now | from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from cbv.views import HomeView, Sitemap
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^projects/', include('cbv.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^sitemap\.xml$', Sitemap.as_view(), name='sitemap'),
url(r'^', include('cbv.shortcut_urls'), {'package': 'Django'}),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^404/$', TemplateView.as_view(template_name='404.html')),
url(r'^500/$', TemplateView.as_view(template_name='500.html')),
]
| from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from cbv.views import HomeView, Sitemap
admin.autodiscover()
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^projects/', include('cbv.urls')),
url(r'^admin/', include(admin.site.urls)),
url(r'^sitemap\.xml$', Sitemap.as_view(), name='sitemap'),
url(r'^', include('cbv.shortcut_urls'), {'package': 'Django'}),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
if settings.DEBUG:
urlpatterns += [
url(r'^404/$', TemplateView.as_view(template_name='404.html')),
url(r'^500/$', TemplateView.as_view(template_name='500.html')),
]
|
Replace execfile with py3 equivalent | # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
exec(compile(open(conf).read(), conf, 'exec'), globs, locs)
prepare(globals(), locals())
| # -*- coding: utf-8 -*-
import os
import stat
from os.path import join, abspath
from subprocess import call
def prepare(globs, locs):
# RTD defaults the current working directory to where conf.py resides.
# In our case, that means <root>/docs/src/.
cwd = os.getcwd()
root = abspath(join(cwd, '..', '..'))
os.chdir(root)
# Download the PHP binary & composer.phar if necessary
base = 'https://github.com/Erebot/Buildenv/releases/download/1.4.0'
for f in ('php', 'composer.phar'):
call(['curl', '-L', '-z', f, '-o', f, '%s/%s' % (base, f)])
# Make sure the PHP interpreter is executable
os.chmod('./php', stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
# Call composer to download/update dependencies as necessary
os.environ['COMPOSER_CACHE_DIR'] = './cache'
call(['./php', 'composer.phar', 'update', '-n', '--ignore-platform-reqs',
'--no-progress'], env=os.environ)
# Load the second-stage configuration file.
os.chdir(cwd)
conf = join(root, 'vendor', 'erebot', 'buildenv', 'sphinx', 'rtd.py')
print "Including the second configuration file (%s)..." % (conf, )
execfile(conf, globs, locs)
prepare(globals(), locals())
|
Add selection to persisted state for subject viewer | var state = require("lib/state"),
User = zooniverse.models.User;
module.exports = {
tool_chain: {
settings : {
project: function() { return state.get('project'); },
title: "Double Click to Edit Title",
annotation : "Double Click to Edit Annotation"
},
persistedState: ['id', 'user', 'project', 'title', 'annotation']
},
table: {
settings: {
currentPage: 0,
sortColumn: 'uid',
sortOrder: 'a'
},
persistedState: ['currentPage', 'sortOrder', 'sortColumn', 'selection']
},
prompt: {
settings: {},
persistedState: ['statements']
},
scatterplot: {
settings: {},
persistedState: ['xAxis', 'yAxis', 'xMin', 'xMax', 'yMin', 'yMax', 'selection']
},
statistics: {
settings: {},
persistedState: ['key']
},
histogram: {
settings: {},
persistedState: ['xAxis', 'xMin', 'xMax', 'selection', 'bins']
},
subject_viewer: {
settings: {currentPage: 0},
persistedState: ['currentPage', 'selection']
}
}
| var state = require("lib/state"),
User = zooniverse.models.User;
module.exports = {
tool_chain: {
settings : {
project: function() { return state.get('project'); },
title: "Double Click to Edit Title",
annotation : "Double Click to Edit Annotation"
},
persistedState: ['id', 'user', 'project', 'title', 'annotation']
},
table: {
settings: {
currentPage: 0,
sortColumn: 'uid',
sortOrder: 'a'
},
persistedState: ['currentPage', 'sortOrder', 'sortColumn', 'selection']
},
prompt: {
settings: {},
persistedState: ['statements']
},
scatterplot: {
settings: {},
persistedState: ['xAxis', 'yAxis', 'xMin', 'xMax', 'yMin', 'yMax', 'selection']
},
statistics: {
settings: {},
persistedState: ['key']
},
histogram: {
settings: {},
persistedState: ['xAxis', 'xMin', 'xMax', 'selection', 'bins']
},
subject_viewer: {
settings: {currentPage: 0},
persistedState: ['currentPage']
}
}
|
Fix webpack regex embed comment termination
Webpack has no protection against inserting */ in the comments it writes when output.pathinfo is true | /* eslint-disable no-param-reassign, max-len */
// Validates and defaults the options
function validateOptions(options) {
// Default options to our preferred value
options.dest = options.dest || 'carte-blanche';
// HACK: Webpack can embed this regex verbatim and the .? makes it not insert a comment terminator
options.filter = options.filter || /([A-Z][a-zA-Z]*.?\/index|[A-Z][a-zA-Z]*)\.(jsx?|es6|react\.jsx?)$/;
// Assert that the componentRoot option was specified
if (!options.componentRoot) {
throw new Error(
'You need to specify where your components are in the "componentRoot" option!\n\n'
);
}
// Assert that the plugins option is an array if specified
if (options.plugins && !Array.isArray(options.plugins)) {
throw new Error('The "plugins" option needs to be an array!\n\n');
}
// Assert that the files option is an array if specified
if (options.files && !Array.isArray(options.files)) {
throw new Error('The "files" option needs to be an array!\n\n');
}
}
export default validateOptions;
| /* eslint-disable no-param-reassign, max-len */
// Validates and defaults the options
function validateOptions(options) {
// Default options to our preferred value
options.dest = options.dest || 'carte-blanche';
options.filter = options.filter || /([A-Z][a-zA-Z]*\/index|[A-Z][a-zA-Z]*)\.(jsx?|es6|react\.jsx?)$/;
// Assert that the componentRoot option was specified
if (!options.componentRoot) {
throw new Error(
'You need to specify where your components are in the "componentRoot" option!\n\n'
);
}
// Assert that the plugins option is an array if specified
if (options.plugins && !Array.isArray(options.plugins)) {
throw new Error('The "plugins" option needs to be an array!\n\n');
}
// Assert that the files option is an array if specified
if (options.files && !Array.isArray(options.files)) {
throw new Error('The "files" option needs to be an array!\n\n');
}
}
export default validateOptions;
|
Update version to revision 2 (also PEP 0440) | from setuptools import setup, find_packages
with open('README.rst') as f:
desc = f.read()
setup(
name = "spdx",
version = "2.3.0b1.post2",
packages = ['spdx'],
package_data = {'spdx': ['data/*.txt', 'data/db.json']},
author = "Brendan Molloy",
author_email = "brendan+pypi@bbqsrc.net",
description = "SPDX license list database",
license = "CC0-1.0",
keywords = ["spdx", "licenses", "database"],
url = "https://github.com/bbqsrc/spdx-python",
long_description=desc,
classifiers=[
"Development Status :: 4 - Beta",
"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5"
]
)
| from setuptools import setup, find_packages
with open('README.rst') as f:
desc = f.read()
setup(
name = "spdx",
version = "2.3.0-beta.1_2",
packages = ['spdx'],
package_data = {'spdx': ['data/*.txt', 'data/db.json']},
author = "Brendan Molloy",
author_email = "brendan+pypi@bbqsrc.net",
description = "SPDX license list database",
license = "CC0-1.0",
keywords = ["spdx", "licenses", "database"],
url = "https://github.com/bbqsrc/spdx-python",
long_description=desc,
classifiers=[
"Development Status :: 4 - Beta",
"License :: CC0 1.0 Universal (CC0 1.0) Public Domain Dedication",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.2",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5"
]
)
|
Make global-bind plugin safe in node envs
When mousetrap loads in a non-dom environment, it bails early and doesn't set the Mousetrap global. Make the global-bind plugin detect that Mousetrap didn't initialize and bail itself. | /**
* adds a bindGlobal method to Mousetrap that allows you to
* bind specific keyboard shortcuts that will still work
* inside a text input field
*
* usage:
* Mousetrap.bindGlobal('ctrl+s', _saveChanges);
*/
/* global Mousetrap:true */
(function(Mousetrap) {
if (! Mousetrap) {
return;
}
var _globalCallbacks = {};
var _originalStopCallback = Mousetrap.prototype.stopCallback;
Mousetrap.prototype.stopCallback = function(e, element, combo, sequence) {
var self = this;
if (self.paused) {
return true;
}
if (_globalCallbacks[combo] || _globalCallbacks[sequence]) {
return false;
}
return _originalStopCallback.call(self, e, element, combo);
};
Mousetrap.prototype.bindGlobal = function(keys, callback, action) {
var self = this;
self.bind(keys, callback, action);
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++) {
_globalCallbacks[keys[i]] = true;
}
return;
}
_globalCallbacks[keys] = true;
};
Mousetrap.init();
}) (Mousetrap);
| /**
* adds a bindGlobal method to Mousetrap that allows you to
* bind specific keyboard shortcuts that will still work
* inside a text input field
*
* usage:
* Mousetrap.bindGlobal('ctrl+s', _saveChanges);
*/
/* global Mousetrap:true */
(function(Mousetrap) {
var _globalCallbacks = {};
var _originalStopCallback = Mousetrap.prototype.stopCallback;
Mousetrap.prototype.stopCallback = function(e, element, combo, sequence) {
var self = this;
if (self.paused) {
return true;
}
if (_globalCallbacks[combo] || _globalCallbacks[sequence]) {
return false;
}
return _originalStopCallback.call(self, e, element, combo);
};
Mousetrap.prototype.bindGlobal = function(keys, callback, action) {
var self = this;
self.bind(keys, callback, action);
if (keys instanceof Array) {
for (var i = 0; i < keys.length; i++) {
_globalCallbacks[keys[i]] = true;
}
return;
}
_globalCallbacks[keys] = true;
};
Mousetrap.init();
}) (Mousetrap);
|
Fix crash on change orientation + back | package fr.masciulli.drinks.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.LiquorDetailFragment;
public class LiquorDetailActivity extends FragmentActivity {
private LiquorDetailFragment mDetailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liquor_detail);
if (savedInstanceState == null) {
mDetailFragment = new LiquorDetailFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.liquor_detail_container, mDetailFragment)
.commit();
} else {
mDetailFragment = (LiquorDetailFragment) getSupportFragmentManager().findFragmentById(R.id.liquor_detail_container);
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void finish() {
super.finish();
// override transitions to skip the standard window animations
overridePendingTransition(0, 0);
}
@Override
public void onBackPressed() {
mDetailFragment.onBackPressed();
}
}
| package fr.masciulli.drinks.activity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import fr.masciulli.drinks.R;
import fr.masciulli.drinks.fragment.LiquorDetailFragment;
public class LiquorDetailActivity extends FragmentActivity {
private LiquorDetailFragment mDetailFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_liquor_detail);
if (savedInstanceState == null) {
mDetailFragment = new LiquorDetailFragment();
getSupportFragmentManager().beginTransaction()
.add(R.id.liquor_detail_container, mDetailFragment)
.commit();
} else {
mDetailFragment = (LiquorDetailFragment) getSupportFragmentManager().findFragmentById(R.id.drink_detail_container);
}
getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void finish() {
super.finish();
// override transitions to skip the standard window animations
overridePendingTransition(0, 0);
}
@Override
public void onBackPressed() {
mDetailFragment.onBackPressed();
}
}
|
Remove method that was removed from interface
See https://github.com/facebook/react-native/commit/ce6fb337a146e6f261f2afb564aa19363774a7a8#diff-63e621165603dc1a84832d6c400fae31 | package com.smooch.rnsmooch;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReactNativeSmoochPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ReactNativeSmooch(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>();
}
}
| package com.smooch.rnsmooch;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.JavaScriptModule;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ReactNativeSmoochPackage implements ReactPackage {
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ReactNativeSmooch(reactContext));
return modules;
}
@Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return new ArrayList<>();
}
}
|
Revert "safari faq bug test"
This reverts commit face5c813634c1a5b0469943492f7ed16f1061c6. | $("body").backstretch("assets/img/background1.png");
$(document).ready(function() {
$('.faqelem').click(function() {
var faqElement = $(this);
var question = faqElement.find('.question');
var answer = faqElement.find('.answer');
if (!answer.hasClass('activeanswer')) {
question.addClass('flipButton');
answer.css('max-height', 'none');
answer.css('max-height', answer.height());
answer.addClass('activeanswer');
}
else if (answer.hasClass('activeanswer')) {
question.removeClass('flipButton');
answer.css('max-height', 0);
answer.removeClass('activeanswer');
}
});
});
// Initialize Firebase
/*
*/
var config = {
apiKey: "AIzaSyAfRJWCG5g0EFpYsA3gX2NQIK_jRYttaFY",
authDomain: "hacktech-pre-registration.firebaseapp.com",
databaseURL: "https://hacktech-pre-registration.firebaseio.com",
storageBucket: "hacktech-pre-registration.appspot.com",
};
firebase.initializeApp(config);
function save() {
var eID = document.getElementById("hackerEmail").value;
firebase.database().ref().push({email: eID});
document.getElementById("hackerEmail").value = "Confirmed!";
};
| $("body").backstretch("assets/img/background1.png");
$(document).ready(function() {
$('.faqelem').click(function() {
var faqElement = $(this);
var question = faqElement.find('.question');
var answer = faqElement.find('.answer');
if (!answer.hasClass('activeanswer')) {
question.addClass('flipButton');
answer.css('max-height', answer.height());
answer.addClass('activeanswer');
}
else if (answer.hasClass('activeanswer')) {
question.removeClass('flipButton');
answer.css('max-height', 0);
answer.removeClass('activeanswer');
}
});
});
// Initialize Firebase
/*
*/
var config = {
apiKey: "AIzaSyAfRJWCG5g0EFpYsA3gX2NQIK_jRYttaFY",
authDomain: "hacktech-pre-registration.firebaseapp.com",
databaseURL: "https://hacktech-pre-registration.firebaseio.com",
storageBucket: "hacktech-pre-registration.appspot.com",
};
firebase.initializeApp(config);
function save() {
var eID = document.getElementById("hackerEmail").value;
firebase.database().ref().push({email: eID});
document.getElementById("hackerEmail").value = "Confirmed!";
};
|
Change error message to loss | import torch
def mean_squared_error(true, pred):
return ((true - pred)**2).mean()
def binary_crossentropy(true, pred, eps=1e-9):
p1 = true * torch.log(pred + eps)
p2 = (1 - true) * torch.log(1 - pred + eps)
return torch.mean(-(p1 + p2))
def categorical_crossentropy(true, pred, eps=1e-9):
return torch.mean(-torch.sum(true * torch.log(pred + eps), dim=1))
# aliases short names
mse = mean_squared_error
def get(obj):
if callable(obj):
return obj
elif type(obj) is str:
if obj in globals():
return globals()[obj]
else:
raise Exception(f'Unknown loss: {obj}')
else:
raise Exception('Loss must be a callable or str')
| import torch
def mean_squared_error(true, pred):
return torch.mean((true - pred)**2)
def binary_crossentropy(true, pred, eps=1e-9):
p1 = true * torch.log(pred + eps)
p2 = (1 - true) * torch.log(1 - pred + eps)
return torch.mean(-(p1 + p2))
def categorical_crossentropy(true, pred, eps=1e-9):
return torch.mean(-torch.sum(true * torch.log(pred + eps), dim=1))
# aliases short names
mse = mean_squared_error
def get(obj):
if callable(obj):
return obj
elif type(obj) is str:
if obj in globals():
return globals()[obj]
else:
raise Exception(f'Unknown objective: {obj}')
else:
raise Exception('Objective must be a callable or str')
|
Change header for delete method. | package org.restler.spring.data.methods;
import com.google.common.collect.ImmutableMultimap;
import org.restler.client.Call;
import org.restler.http.HttpMethod;
import org.restler.spring.data.proxy.ResourceProxy;
import java.lang.reflect.Method;
public class DeleteCrudMethod implements CrudMethod {
@Override
public boolean isCrudMethod(Method method) {
return "delete".equals(method.getName());
}
@Override
public Call getCall(Object[] args) {
return null;
}
@Override
public Object getRequestBody(Object[] args) {
return null;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.DELETE;
}
@Override
public String getPathPart(Object[] args) {
Object arg;
if(args.length == 1 && (arg = args[0]) instanceof ResourceProxy) {
ResourceProxy resourceProxy = (ResourceProxy)arg;
return resourceProxy.getResourceId().toString();
}
return "{id}";
}
@Override
public ImmutableMultimap<String, String> getHeader() {
return ImmutableMultimap.of("Content-Type", "application/json");
}
}
| package org.restler.spring.data.methods;
import com.google.common.collect.ImmutableMultimap;
import org.restler.client.Call;
import org.restler.http.HttpMethod;
import org.restler.spring.data.proxy.ResourceProxy;
import java.lang.reflect.Method;
public class DeleteCrudMethod implements CrudMethod {
@Override
public boolean isCrudMethod(Method method) {
return "delete".equals(method.getName());
}
@Override
public Call getCall(Object[] args) {
return null;
}
@Override
public Object getRequestBody(Object[] args) {
return null;
}
@Override
public HttpMethod getHttpMethod() {
return HttpMethod.DELETE;
}
@Override
public String getPathPart(Object[] args) {
Object arg;
if(args.length == 1 && (arg = args[0]) instanceof ResourceProxy) {
ResourceProxy resourceProxy = (ResourceProxy)arg;
return resourceProxy.getResourceId().toString();
}
return "{id}";
}
@Override
public ImmutableMultimap<String, String> getHeader() {
return ImmutableMultimap.of();
}
}
|
Use render.page for full-page reload | 'use strict';
/**
* client
**/
/**
* client.common
**/
/**
* client.common.auth
**/
/**
* client.common.auth.register
**/
/*global $, _, nodeca, window*/
/**
* client.common.auth.register.exec($form, event)
*
* send registration data on server
**/
module.exports = function ($form, event) {
var params = nodeca.client.common.form.getData($form);
nodeca.server.users.auth.register.exec(params, function(err){
var message;
if (err) {
if (err.statusCode === 409) {
// clear pass
params.pass = '';
// add errors
params.errors = err.message;
nodeca.client.common.render.page('users.auth.register.view', params);
return;
}
message = nodeca.runtime.t('common.error.server_internal');
nodeca.client.common.notice('error', message);
return;
}
nodeca.client.common.render.page('users.auth.register.success');
});
// Disable regular click
return false;
};
| 'use strict';
/**
* client
**/
/**
* client.common
**/
/**
* client.common.auth
**/
/**
* client.common.auth.register
**/
/*global $, _, nodeca, window*/
/**
* client.common.auth.register.exec($form, event)
*
* send registration data on server
**/
module.exports = function ($form, event) {
var params = nodeca.client.common.form.getData($form);
nodeca.server.users.auth.register.exec(params, function(err){
var message;
if (err) {
if (err.statusCode === 409) {
// clear pass
params.pass = '';
// add errors
params.errors = err.message;
$form.replaceWith(
nodeca.client.common.render('users.auth.register.view', params)
).fadeIn();
return;
}
message = nodeca.runtime.t('common.error.server_internal');
nodeca.client.common.notice('error', message);
return;
}
$form.replaceWith(
nodeca.client.common.render('users.auth.register.success')
).fadeIn();
});
// Disable regular click
return false;
};
|
Change method signature to accept any interface implementation | package com.mercateo.common.rest.schemagen.link;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.ws.rs.core.Link;
import com.mercateo.common.rest.schemagen.JerseyResource;
import com.mercateo.common.rest.schemagen.link.helper.MethodInvocation;
import com.mercateo.common.rest.schemagen.link.relation.RelationContainer;
public class SchemaGenerator<T extends JerseyResource> {
private LinkFactory<T> linkFactory;
private final List<Optional<Link>> links;
public static <T extends JerseyResource> SchemaGenerator<T> builder(
LinkFactory<T> linkFactory) {
return new SchemaGenerator<T>(linkFactory, new ArrayList<>());
}
public SchemaGenerator(
LinkFactory<T> linkFactory, List<Optional<Link>> links) {
this.linkFactory = linkFactory;
this.links = links;
}
public SchemaGenerator<T> withLink(RelationContainer rel,
MethodInvocation<T> methodInvocation) {
links.add(linkFactory.forCall(rel, methodInvocation));
return this;
}
public <V extends JerseyResource> SchemaGenerator<V> withFactory(LinkFactory<V> linkFactory) {
return new SchemaGenerator<V>(linkFactory, links);
}
public List<Optional<Link>> build() {
return links;
}
} | package com.mercateo.common.rest.schemagen.link;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.ws.rs.core.Link;
import com.mercateo.common.rest.schemagen.JerseyResource;
import com.mercateo.common.rest.schemagen.link.helper.MethodInvocation;
import com.mercateo.common.rest.schemagen.link.relation.Rel;
public class SchemaGenerator<T extends JerseyResource> {
private LinkFactory<T> linkFactory;
private final List<Optional<Link>> links;
public static <T extends JerseyResource> SchemaGenerator<T> builder(
LinkFactory<T> linkFactory) {
return new SchemaGenerator<T>(linkFactory, new ArrayList<>());
}
public SchemaGenerator(
LinkFactory<T> linkFactory, List<Optional<Link>> links) {
this.linkFactory = linkFactory;
this.links = links;
}
public SchemaGenerator<T> withLink(Rel rel, MethodInvocation<T> methodInvocation) {
links.add(linkFactory.forCall(rel, methodInvocation));
return this;
}
public <V extends JerseyResource> SchemaGenerator<V> withFactory(LinkFactory<V> linkFactory) {
return new SchemaGenerator<V>(linkFactory, links);
}
public List<Optional<Link>> build() {
return links;
}
} |
Fix last code quality issues | """ Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')
@patch('app.views.is_valid_pull_request')
def test_valid_pull_request(self, validator, notifier):
""" Should notify upon a valid pull request. """
validator.return_value = True
notifier.return_value = True
result = views.pull_request({}, None)
self.assertEqual(result, 'Recipient Notified')
@patch('app.views.is_valid_pull_request')
def test_invalid_pull_request(self, validator):
""" Should ignore an invalid pull request. """
validator.return_value = False
result = views.pull_request({}, None)
self.assertRegex(result, 'ignored')
| """ Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')
@patch('app.views.is_valid_pull_request')
def test_valid_pull_request(self, validator, notifier):
validator.return_value = True
notifier.return_value = True
result = views.pull_request({}, None)
self.assertEqual(result, 'Recipient Notified')
@patch('app.views.is_valid_pull_request')
def test_invalid_pull_request(self, validator):
validator.return_value = False
result = views.pull_request({}, None)
self.assertRegex(result, 'ignored')
|
Move variable declarations and add section headers | 'use strict';
// TODO: clean-up
// MODULES //
var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var acosh = require( './../lib' );
// FIXTURES //
var data = require( './fixtures/julia/data.json' );
// MAIN //
var customErrs;
var nativeErrs;
var yexpected;
var ynative;
var ycustom;
var x;
var i;
x = data.x;
yexpected = data.expected;
ycustom = new Array( x.length );
ynative = new Array( x.length );
for ( i = 0; i < x.length; i++ ) {
if ( yexpected[ i ] === 0.0 ) {
yexpected[ i ] += 1e-16;
}
ycustom[ i ] = acosh( x[ i ] );
ynative[ i ] = Math.acosh( x[ i ] );
}
customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );
console.log( 'The mean relative error of Math.acosh compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
| 'use strict';
// TODO: clean-up
var abs = require( '@stdlib/math/base/special/abs' );
var divide = require( 'compute-divide' );
var mean = require( 'compute-mean' );
var subtract = require( 'compute-subtract' );
var acosh = require( './../lib' );
var data = require( './fixtures/julia/data.json' );
var x = data.x;
var yexpected = data.expected;
var ycustom = new Array( x.length );
var ynative = new Array( x.length );
for ( var i = 0; i < x.length; i++ ) {
if ( yexpected[ i ] === 0.0 ) {
yexpected[ i ] += 1e-16;
}
ycustom[ i ] = acosh( x[ i ] );
ynative[ i ] = Math.acosh( x[ i ] );
}
var customErrs = abs( divide( subtract( ycustom, yexpected ), yexpected ) );
var nativeErrs = abs( divide( subtract( ynative, yexpected ), yexpected ) );
console.log( 'The mean relative error of Math.acosh compared to Julia is %d', mean( nativeErrs ) );
console.log( 'The mean relative error of this module compared to Julia is %d', mean( customErrs ) );
|
aetest: Fix example code use of aetest.NewContext.
Change-Id: I34d58da17a17d89affa9c0b1e1b9c727b4bfb098 | /*
Package aetest provides an API for running dev_appserver for use in tests.
An example test file:
package foo_test
import (
"testing"
"google.golang.org/appengine/memcache"
"google.golang.org/appengine/aetest"
)
func TestFoo(t *testing.T) {
ctx, done, err := aetest.NewContext()
if err != nil {
t.Fatal(err)
}
defer done()
it := &memcache.Item{
Key: "some-key",
Value: []byte("some-value"),
}
err = memcache.Set(ctx, it)
if err != nil {
t.Fatalf("Set err: %v", err)
}
it, err = memcache.Get(ctx, "some-key")
if err != nil {
t.Fatalf("Get err: %v; want no error", err)
}
if g, w := string(it.Value), "some-value" ; g != w {
t.Errorf("retrieved Item.Value = %q, want %q", g, w)
}
}
The environment variable APPENGINE_DEV_APPSERVER specifies the location of the
dev_appserver.py executable to use. If unset, the system PATH is consulted.
*/
package aetest
| /*
Package aetest provides an API for running dev_appserver for use in tests.
An example test file:
package foo_test
import (
"testing"
"google.golang.org/appengine/memcache"
"google.golang.org/appengine/aetest"
)
func TestFoo(t *testing.T) {
ctx, done, err := aetest.NewContext(nil)
if err != nil {
t.Fatal(err)
}
defer done()
it := &memcache.Item{
Key: "some-key",
Value: []byte("some-value"),
}
err = memcache.Set(ctx, it)
if err != nil {
t.Fatalf("Set err: %v", err)
}
it, err = memcache.Get(ctx, "some-key")
if err != nil {
t.Fatalf("Get err: %v; want no error", err)
}
if g, w := string(it.Value), "some-value" ; g != w {
t.Errorf("retrieved Item.Value = %q, want %q", g, w)
}
}
The environment variable APPENGINE_DEV_APPSERVER specifies the location of the
dev_appserver.py executable to use. If unset, the system PATH is consulted.
*/
package aetest
|
Update Rx require to point to local utility version | /*globals describe, it*/
var Record = require('../../lib/model/record'),
Rx = require('../../lib/util/rx');
require('should');
describe('Record', function () {
describe('#has(key)', function () {
var r = new Record({ foo: 'foo' });
it('should return true if record has the property', function () {
r.has('foo').should.be.true;
});
it('should return false if record does not have the property', function () {
r.has('bar').should.be.false;
});
});
describe('#get([key]', function () {
var r = new Record({ foo: 'foo', bar: 'bar' });
it('should return an Observable', function () {
r.get('foo').should.be.instanceOf(Rx.Observable);
r.get('baz').should.be.instanceOf(Rx.Observable);
// r.get().should.be.instanceOf(Rx.Observable);
});
});
});
| /*globals describe, it*/
var Record = require('../../lib/model/record'),
Rx = require('rx');
require('should');
describe('Record', function () {
describe('#has(key)', function () {
var r = new Record({ foo: 'foo' });
it('should return true if record has the property', function () {
r.has('foo').should.be.true;
});
it('should return false if record does not have the property', function () {
r.has('bar').should.be.false;
});
});
describe('#get([key]', function () {
var r = new Record({ foo: 'foo', bar: 'bar' });
it('should return an Observable', function () {
r.get('foo').should.be.instanceOf(Rx.Observable);
r.get('baz').should.be.instanceOf(Rx.Observable);
// r.get().should.be.instanceOf(Rx.Observable);
});
});
});
|
Fix an error of passing unicode literals to cupy | # This caused an error in py2 because cupy expect non-unicode str
# from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
from chainer import cuda
class NonbiasWeightDecay(object):
"""Optimizer hook function for weight decay regularization.
"""
name = 'NonbiasWeightDecay'
def __init__(self, rate):
self.rate = rate
def __call__(self, opt):
if cuda.available:
kernel = cuda.elementwise(
'T p, T decay', 'T g', 'g += decay * p', 'weight_decay')
rate = self.rate
for name, param in opt.target.namedparams():
if name == 'b' or name.endswith('/b'):
continue
p, g = param.data, param.grad
with cuda.get_device(p) as dev:
if int(dev) == -1:
g += rate * p
else:
kernel(p, rate, g)
| from __future__ import unicode_literals
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from builtins import int
from future import standard_library
standard_library.install_aliases()
from chainer import cuda
class NonbiasWeightDecay(object):
"""Optimizer hook function for weight decay regularization.
"""
name = 'NonbiasWeightDecay'
def __init__(self, rate):
self.rate = rate
def __call__(self, opt):
if cuda.available:
kernel = cuda.elementwise(
'T p, T decay', 'T g', 'g += decay * p', 'weight_decay')
rate = self.rate
for name, param in opt.target.namedparams():
if name == 'b' or name.endswith('/b'):
continue
p, g = param.data, param.grad
with cuda.get_device(p) as dev:
if int(dev) == -1:
g += rate * p
else:
kernel(p, rate, g)
|
Add a newline to a long error message | package beaform.commands;
import org.neo4j.graphdb.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import beaform.dao.FormulaDAO;
import beaform.entities.Formula;
import beaform.utilities.ErrorDisplay;
public class CreateNewFormulaCommand implements Command {
private static final Logger LOG = LoggerFactory.getLogger(CreateNewFormulaCommand.class);
private final Formula formula;
private final ErrorDisplay errorDisplay;
public CreateNewFormulaCommand(Formula formula, ErrorDisplay errorDisplay) {
this.formula = formula;
this.errorDisplay = errorDisplay;
}
@Override
public void execute() {
try {
FormulaDAO.addFormula(this.formula);
}
catch (ConstraintViolationException cve) {
if (LOG.isDebugEnabled()) {
LOG.debug("The formula already exists", cve);
}
displayError(cve);
}
}
private void displayError(Exception e) {
String formulaName = this.formula.getName();
String errorMessageFormat = "A formula with the name %s already seems to exist:%n%s";
String errorMessage = String.format(errorMessageFormat, formulaName, e.getMessage());
this.errorDisplay.displayError(errorMessage);
}
}
| package beaform.commands;
import org.neo4j.graphdb.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import beaform.dao.FormulaDAO;
import beaform.entities.Formula;
import beaform.utilities.ErrorDisplay;
public class CreateNewFormulaCommand implements Command {
private static final Logger LOG = LoggerFactory.getLogger(CreateNewFormulaCommand.class);
private final Formula formula;
private final ErrorDisplay errorDisplay;
public CreateNewFormulaCommand(Formula formula, ErrorDisplay errorDisplay) {
this.formula = formula;
this.errorDisplay = errorDisplay;
}
@Override
public void execute() {
try {
FormulaDAO.addFormula(this.formula);
}
catch (ConstraintViolationException cve) {
if (LOG.isDebugEnabled()) {
LOG.debug("The formula already exists", cve);
}
displayError(cve);
}
}
private void displayError(Exception e) {
String formulaName = this.formula.getName();
String errorMessageFormat = "A formula with the name %s already seems to exist: %s";
String errorMessage = String.format(errorMessageFormat, formulaName, e.getMessage());
this.errorDisplay.displayError(errorMessage);
}
}
|
Load only active features from local db | /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.android.gnd.persistence.local.room.dao;
import androidx.room.Dao;
import androidx.room.Query;
import com.google.android.gnd.persistence.local.room.entity.FeatureEntity;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import java.util.List;
/** Provides low-level read/write operations of {@link FeatureEntity} to/from the local db. */
@Dao
public interface FeatureDao extends BaseDao<FeatureEntity> {
@Query("SELECT * FROM feature WHERE project_id = :projectId AND state = 1")
Flowable<List<FeatureEntity>> findByProjectIdStream(String projectId);
@Query("SELECT * FROM feature WHERE id = :id")
Maybe<FeatureEntity> findById(String id);
}
| /*
* Copyright 2019 Google LLC
*
* 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
*
* https://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.google.android.gnd.persistence.local.room.dao;
import androidx.room.Dao;
import androidx.room.Query;
import com.google.android.gnd.persistence.local.room.entity.FeatureEntity;
import io.reactivex.Flowable;
import io.reactivex.Maybe;
import java.util.List;
/** Provides low-level read/write operations of {@link FeatureEntity} to/from the local db. */
@Dao
public interface FeatureDao extends BaseDao<FeatureEntity> {
@Query("SELECT * FROM feature WHERE project_id = :projectId")
Flowable<List<FeatureEntity>> findByProjectIdStream(String projectId);
@Query("SELECT * FROM feature WHERE id = :id")
Maybe<FeatureEntity> findById(String id);
}
|
Remove public from MPI test interface
git-svn-id: 6cb0c57df7a4a7d32342646683f5f1b5f4d88845@2773 9ab3861e-6c05-4e1b-b5ef-99af60850597 | package testMPI;
import integratedtoolkit.types.annotations.Constraints;
import integratedtoolkit.types.annotations.Parameter;
import integratedtoolkit.types.annotations.parameter.Direction;
import integratedtoolkit.types.annotations.parameter.Stream;
import integratedtoolkit.types.annotations.parameter.Type;
import integratedtoolkit.types.annotations.task.MPI;
public interface MainItf {
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "1")
@Constraints(computingUnits = "4")
int taskSingleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "2")
@Constraints(computingUnits = "4")
Integer taskMultipleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "2")
@Constraints(computingUnits = "2")
Integer taskConcurrentMultipleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
}
| package testMPI;
import integratedtoolkit.types.annotations.Constraints;
import integratedtoolkit.types.annotations.Parameter;
import integratedtoolkit.types.annotations.parameter.Direction;
import integratedtoolkit.types.annotations.parameter.Stream;
import integratedtoolkit.types.annotations.parameter.Type;
import integratedtoolkit.types.annotations.task.MPI;
public interface MainItf {
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "1")
@Constraints(computingUnits = "4")
public int taskSingleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "2")
@Constraints(computingUnits = "4")
public Integer taskMultipleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
@MPI(binary = "${VEC_SUM_MPI_BINARY}", mpiRunner = "mpirun", computingNodes = "2")
@Constraints(computingUnits = "2")
public Integer taskConcurrentMultipleMPI(
@Parameter(type = Type.OBJECT, direction = Direction.IN) int[] data,
@Parameter(type = Type.FILE, direction = Direction.OUT, stream = Stream.STDOUT) String fileOut
);
}
|
Improve error reporting in client. | package client
import (
"github.com/ibrt/go-oauto/oauto/api"
"net/http"
"fmt"
"encoding/json"
"github.com/go-errors/errors"
"bytes"
)
func Authenticate(baseURL string, request *api.AuthenticateRequest) (*api.AuthenticateResponse, error) {
body, err := json.Marshal(request)
if err != nil {
return nil, errors.Wrap(err, 0)
}
resp, err := http.Post(fmt.Sprintf("%v/api/authenticate", baseURL), "application/json", bytes.NewBuffer(body))
if err != nil {
return nil, errors.Wrap(err, 0)
}
authResp := &api.AuthenticateResponse{}
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return nil, errors.Wrap(err, 0)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("Authenticate request failed with status %v: '%+v'.", resp.StatusCode, authResp)
}
return authResp, nil
}
| package client
import (
"github.com/ibrt/go-oauto/oauto/api"
"net/http"
"fmt"
"encoding/json"
"github.com/go-errors/errors"
"bytes"
)
func Authenticate(baseURL string, request *api.AuthenticateRequest) (*api.AuthenticateResponse, error) {
body, err := json.Marshal(request)
if err != nil {
return nil, errors.Wrap(err, 0)
}
resp, err := http.Post(fmt.Sprintf("%v/api/authenticate", baseURL), "application/json", bytes.NewBuffer(body))
if err != nil {
return nil, errors.Wrap(err, 0)
}
if resp.StatusCode != http.StatusOK {
return nil, errors.Errorf("Authenticate request failed with status %v.", resp.StatusCode)
}
authResp := &api.AuthenticateResponse{}
if err := json.NewDecoder(resp.Body).Decode(&authResp); err != nil {
return nil, errors.Wrap(err, 0)
}
return authResp, nil
}
|
Add tooltip to delete button in form group containers
Fixes DCOS-13199 | import React from 'react';
import {Tooltip} from 'reactjs-components';
import Icon from '../Icon';
const FormGroupContainer = (props) => {
let removeButton = null;
if (props.onRemove != null) {
removeButton = (
<div className="form-group-container-action-button-group">
<Tooltip content="Delete"
interactive={true}
maxWidth={300}
scrollContainer=".gm-scroll-view"
wrapText={true}>
<a className="button button-primary-link"
onClick={props.onRemove}>
<Icon id="close" color="grey" size="tiny" family="tiny"/>
</a>
</Tooltip>
</div>
);
}
return (
<div className="panel pod-short">
<div className="pod-narrow pod-short">
{removeButton}
{props.children}
</div>
</div>
);
};
FormGroupContainer.defaultProps = {
onRemove: null
};
FormGroupContainer.propTypes = {
children: React.PropTypes.node,
onRemove: React.PropTypes.func
};
module.exports = FormGroupContainer;
| import React from 'react';
import Icon from '../Icon';
const FormGroupContainer = (props) => {
let removeButton = null;
if (props.onRemove != null) {
removeButton = (
<div className="form-group-container-action-button-group">
<a className="button button-primary-link"
onClick={props.onRemove}>
<Icon id="close" color="grey" size="tiny" family="tiny"/>
</a>
</div>
);
}
return (
<div className="panel pod-short">
<div className="pod-narrow pod-short">
{removeButton}
{props.children}
</div>
</div>
);
};
FormGroupContainer.defaultProps = {
onRemove: null
};
FormGroupContainer.propTypes = {
children: React.PropTypes.node,
onRemove: React.PropTypes.func
};
module.exports = FormGroupContainer;
|
Fix python library problem due to ABI tagged .so files | #!/usr/bin/env python
"""
setup.py file for compiling Infomap module
"""
from distutils.core import setup, Extension
from distutils.file_util import copy_file
import sysconfig
import fnmatch
import os
import re
cppSources = []
for root, dirnames, filenames in os.walk('.'):
if root == 'src': cppSources.append(os.path.join(root, 'Infomap.cpp'))
else:
for filename in fnmatch.filter(filenames, '*.cpp'):
cppSources.append(os.path.join(root, filename))
# Extract Infomap version
infomapVersion = ''
with open(os.path.join('src', 'io', 'version.cpp')) as f:
for line in f:
m = re.match( r'.+INFOMAP_VERSION = \"(.+)\"', line)
if m: infomapVersion = m.groups()[0]
infomap_module = Extension('_infomap',
sources=cppSources,
extra_compile_args=['-DAS_LIB']
)
setup (name = 'infomap',
version = infomapVersion,
author = "Team at mapequation.org",
description = """Infomap clustering algorithm""",
url = "www.mapequation.org",
ext_modules = [infomap_module],
py_modules = ["infomap"],
)
# Clean ABI Version Tagged .so Files
libFilename = '_infomap{}'.format(sysconfig.get_config_var('EXT_SUFFIX'))
copy_file(libFilename, '_infomap.so') | #!/usr/bin/env python
"""
setup.py file for compiling Infomap module
"""
from distutils.core import setup, Extension
import fnmatch
import os
import re
cppSources = []
for root, dirnames, filenames in os.walk('.'):
if root == 'src': cppSources.append(os.path.join(root, 'Infomap.cpp'))
else:
for filename in fnmatch.filter(filenames, '*.cpp'):
cppSources.append(os.path.join(root, filename))
# Extract Infomap version
infomapVersion = ''
with open(os.path.join('src', 'io', 'version.cpp')) as f:
for line in f:
m = re.match( r'.+INFOMAP_VERSION = \"(.+)\"', line)
if m: infomapVersion = m.groups()[0]
infomap_module = Extension('_infomap',
sources=cppSources,
extra_compile_args=['-DAS_LIB']
)
setup (name = 'infomap',
version = infomapVersion,
author = "Team at mapequation.org",
description = """Infomap clustering algorithm""",
url = "www.mapequation.org",
ext_modules = [infomap_module],
py_modules = ["infomap"],
) |
Set the start date for the new rate as July 1 | """mmg rates now set to 1.65 pence per sms
Revision ID: 0040_adjust_mmg_provider_rate
Revises: 0039_fix_notifications
Create Date: 2016-07-06 15:19:23.124212
"""
# revision identifiers, used by Alembic.
revision = '0040_adjust_mmg_provider_rate'
down_revision = '0039_fix_notifications'
import uuid
from datetime import datetime
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
conn.execute(
sa.sql.text(("INSERT INTO provider_rates (id, valid_from, rate, provider_id) "
"VALUES (:id, :valid_from, :rate, (SELECT id FROM provider_details WHERE identifier = 'mmg'))")),
id=uuid.uuid4(),
valid_from=datetime(2016, 7, 1),
rate=1.65
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
conn.execute(("DELETE FROM provider_rates "
"WHERE provider_id = (SELECT id FROM provider_details WHERE identifier = 'mmg') "
"AND rate = 1.65"))
### end Alembic commands ###
| """mmg rates now set to 1.65 pence per sms
Revision ID: 0040_adjust_mmg_provider_rate
Revises: 0039_fix_notifications
Create Date: 2016-07-06 15:19:23.124212
"""
# revision identifiers, used by Alembic.
revision = '0040_adjust_mmg_provider_rate'
down_revision = '0039_fix_notifications'
import uuid
from datetime import datetime
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
conn.execute(
sa.sql.text(("INSERT INTO provider_rates (id, valid_from, rate, provider_id) "
"VALUES (:id, :valid_from, :rate, (SELECT id FROM provider_details WHERE identifier = 'mmg'))")),
id=uuid.uuid4(),
valid_from=datetime.utcnow(),
rate=1.65
)
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
conn = op.get_bind()
conn.execute(("DELETE FROM provider_rates "
"WHERE provider_id = (SELECT id FROM provider_details WHERE identifier = 'mmg') "
"AND rate = 1.65"))
### end Alembic commands ###
|
Allow DebuggerComponent to take external props | /** @babel */
/** @jsx etch.dom */
import etch from 'etch'
const defaultStyle = {
position: 'fixed',
zIndex: 100000000,
backgroundColor: 'white',
minWidth: '100px',
minHeight: '100px',
top: '200px',
left: '200px',
maxWidth: '800px',
maxHeight: '400px',
overflow: 'auto',
whiteSpace: 'pre',
fontFamily: 'monospace',
border: '3px solid black'
}
export default class DebuggerComponent {
constructor (props) {
this.props = props
etch.initialize(this)
}
update (props) {
this.props = props
etch.update(this)
}
render () {
const {data, style, ...others} = this.props
const finalStyle = {
...defaultStyle,
...style
}
return <div style={finalStyle} {...others}>{JSON.stringify(data, null, ' ')}</div>
}
}
| /** @babel */
/** @jsx etch.dom */
import etch from 'etch'
const style = {
position: 'fixed',
zIndex: 100000000,
backgroundColor: 'white',
minWidth: '100px',
minHeight: '100px',
top: '200px',
left: '200px',
maxWidth: '800px',
maxHeight: '400px',
overflow: 'auto',
whiteSpace: 'pre',
fontFamily: 'monospace',
border: '3px solid black'
}
export default class DebuggerComponent {
constructor ({data}) {
this.data = data
etch.initialize(this)
}
update ({data}) {
this.data = data
etch.update(this)
}
render () {
return (
<div style={style}> {JSON.stringify(this.data, null, ' ')}
</div>)
}
}
|
Fix CMS Service Provider Routes | <?php
namespace LaravelFlare\Cms;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
class CmsServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*/
public function boot(Router $router)
{
$router->middleware('checkslugexists', 'LaravelFlare\Cms\Http\Middleware\CheckSlugExists');
$this->publishes([
__DIR__.'/Database/Migrations' => base_path('database/migrations'),
]);
// Views
$this->loadViewsFrom(__DIR__.'/../resources/views', 'flare');
$this->publishes([
__DIR__.'/../resources/views' => base_path('resources/views/vendor/flare'),
]);
}
/**
* Register any package services.
*/
public function register()
{
// Routes
if (!$this->app->routesAreCached()) {
require __DIR__.'/Http/routes.php';
}
}
/**
* Register Service Providers.
*/
protected function registerServiceProviders()
{
}
/**
* Register Blade Operators.
*/
protected function registerBladeOperators()
{
}
}
| <?php
namespace LaravelFlare\Cms;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
class CmsServiceProvider extends ServiceProvider
{
/**
* Perform post-registration booting of services.
*/
public function boot(Router $router)
{
$router->middleware('checkslugexists', 'LaravelFlare\Cms\Http\Middleware\CheckSlugExists');
$this->publishes([
__DIR__.'/Database/Migrations' => base_path('database/migrations'),
]);
// Routes
if (!$this->app->routesAreCached()) {
require __DIR__.'/Http/routes.php';
}
// Views
$this->loadViewsFrom(__DIR__.'/../resources/views', 'flare');
$this->publishes([
__DIR__.'/../resources/views' => base_path('resources/views/vendor/flare'),
]);
}
/**
* Register any package services.
*/
public function register()
{
}
/**
* Register Service Providers.
*/
protected function registerServiceProviders()
{
}
/**
* Register Blade Operators.
*/
protected function registerBladeOperators()
{
}
}
|
Add tests module to packaging list | #!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
'deflect.tests',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
| #!/usr/bin/env python
from distutils.core import setup
import os
from deflect import __version__ as version
def read_file(filename):
"""
Utility function to read a provided filename.
"""
return open(os.path.join(os.path.dirname(__file__), filename)).read()
packages = [
'deflect',
]
package_data = {
'': ['LICENSE', 'README.rst'],
}
setup(
name='django-deflect',
version=version,
description='A Django short URL redirection application',
long_description=read_file('README.rst'),
author='Jason Bittel',
author_email='jason.bittel@gmail.com',
url='https://github.com/jbittel/django-deflect',
download_url='https://github.com/jbittel/django-deflect/downloads',
package_dir={'deflect': 'deflect'},
packages=packages,
package_data=package_data,
license='BSD',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Web Environment',
'Programming Language :: Python',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries :: Python Modules',
],
keywords=['django'],
)
|
Add sso id to user info | <?php
namespace Da\OAuthServerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* @Template()
*/
class InfoController extends Controller
{
/**
* @Route("/infos", defaults={"_format"="json"})
*/
public function getUserInfoAction()
{
$user = $this->get('security.context')->getToken()->getUser();
return array(
'id' => $user->getId(),
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'roles' => json_encode($user->getRoles()),
'raw' => $user->getRaw()
);
}
}
| <?php
namespace Da\OAuthServerBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
/**
* @Template()
*/
class InfoController extends Controller
{
/**
* @Route("/infos", defaults={"_format"="json"})
*/
public function getUserInfoAction()
{
$user = $this->get('security.context')->getToken()->getUser();
return array(
'username' => $user->getUsername(),
'email' => $user->getEmail(),
'roles' => json_encode($user->getRoles()),
'raw' => $user->getRaw()
);
}
}
|
Revert "Fix order of eslint-loader"
This reverts commit 58b53a99e486c39ad1b8d44bb8a3de82764c659e. | const ExtractTextPlugin = require('extract-text-webpack-plugin')
const externals = require('webpack-node-externals')
const path = require('path')
const eslintRule = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}
module.exports = [
{
entry: './client',
output: {
path: path.resolve('dist'),
filename: 'client.js'
},
devtool: 'cheap-source-map',
module: {
rules: [
eslintRule,
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'less-loader']
})
}
]
},
plugins: [
new ExtractTextPlugin('client.css')
]
},
{
entry: {
server: './server',
loader: './server/loader'
},
output: {
path: path.resolve('dist'),
filename: '[name].js'
},
devtool: 'cheap-source-map',
module: {
rules: [
eslintRule
]
},
target: 'node',
externals: externals(),
node: false
}
]
| const ExtractTextPlugin = require('extract-text-webpack-plugin')
const externals = require('webpack-node-externals')
const path = require('path')
const eslintRule = {
test: /\.js$/,
exclude: /node_modules/,
loader: 'eslint-loader'
}
module.exports = [
{
entry: './client',
output: {
path: path.resolve('dist'),
filename: 'client.js'
},
devtool: 'cheap-source-map',
module: {
rules: [
{
test: /\.less$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', 'less-loader']
})
},
eslintRule
]
},
plugins: [
new ExtractTextPlugin('client.css')
]
},
{
entry: {
server: './server',
loader: './server/loader'
},
output: {
path: path.resolve('dist'),
filename: '[name].js'
},
devtool: 'cheap-source-map',
module: {
rules: [
eslintRule
]
},
target: 'node',
externals: externals(),
node: false
}
]
|
Check that start building can recruit something. | """Check for inconsistancies in the database."""
from server.db import (
BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType, setup,
options
)
def main():
load()
setup()
for name in UnitType.resource_names():
if UnitType.count(getattr(UnitType, name) >= 1):
continue
else:
print(f'There is no unit that can gather {name}.')
for bt in BuildingType.all():
if not BuildingBuilder.count(building_type_id=bt.id):
print(f'There is no way to build {bt.name}.')
for ut in UnitType.all():
if not BuildingRecruit.count(unit_type_id=ut.id):
print(f'There is no way to recruit {ut.get_name()}.')
sb = options.start_building
if not sb.recruits:
print(f'Start building {sb.get_name()} cannot recruit anything.')
if __name__ == '__main__':
try:
main()
except FileNotFoundError:
print('No database file exists.')
| """Check for inconsistancies in the database."""
from server.db import (
BuildingBuilder, BuildingRecruit, BuildingType, load, UnitType
)
def main():
load()
for name in UnitType.resource_names():
if UnitType.count(getattr(UnitType, name) >= 1):
continue
else:
print(f'There is no unit that can gather {name}.')
for bt in BuildingType.all():
if not BuildingBuilder.count(building_type_id=bt.id):
print(f'There is no way to build {bt.name}.')
for ut in UnitType.all():
if not BuildingRecruit.count(unit_type_id=ut.id):
print(f'There is no way to recruit {ut.get_name()}.')
if __name__ == '__main__':
try:
main()
except FileNotFoundError:
print('No database file exists.')
|
Add more methods and Refactor code
Constructor now accept first argument as paragraph parent. Also create a reference from its parent.
parseWords now pass a sentence rather than sentenceId.
parent() method get paragraph parent from a sentence.
This commit also introduce lookup methods, they are:
- findWordById = find a word by its id
- findWordByIndex = find a word by its index
Sentence has navigate method too:
- next() is for navigating to the next sentence in a paragraph context.
- prev() is for navigating to the previous sentence in a paragraph context. | const uuidV4 = require('uuid/v4');
const _ = require('lodash');
const Word = require('./word');
let words = new WeakMap();
let parent = new WeakMap();
class Sentence {
constructor(paragraph, text, index) {
parent.set(this, paragraph);
this.id = uuidV4();
this.index = index;
this.paragraphId = paragraph.id;
this.text = text;
this.parseWords();
return this;
}
parent() {
return parent.get(this);
}
findWordById(id) {
return _.find(this.wordsCollection, {id});
}
findWordByIndex(index) {
return _.find(this.wordsCollection, {index});
}
next() {
let index = this.index;
return this.parent().findSentenceByIndex(index + 1);
}
prev() {
let index = this.index;
return this.parent().findSentenceByIndex(index - 1);
}
get words() {
return _.map(words.get(this), 'id');
}
set words(w) {
words.set(this, w);
}
get wordsCollection() {
return words.get(this);
}
parseWords() {
let sentence = this;
let {text} = sentence;
this.words = _.chain(text).split(/\s{1,}/ig)
.map((text, index) => new Word(sentence, index, text)).value();
}
}
module.exports = Sentence;
| const uuidV4 = require('uuid/v4');
const _ = require('lodash');
const Word = require('./word');
let words = new WeakMap();
class Sentence {
constructor(paragraphId, text, index) {
this.id = uuidV4();
this.index = index;
this.paragraphId = paragraphId;
this.text = text;
this.parseWords();
return this;
}
get words() {
return _.map(words.get(this), 'id');
}
set words(w) {
words.set(this, w);
}
get wordsObject() {
return words.get(this);
}
parseWords() {
let {id: sentenceId, text} = this;
this.words = _.chain(text).split(/\s{1,}/ig)
.map((text, index) => new Word(sentenceId, index, text)).value();
}
}
module.exports = Sentence;
|
Add flags for input and output image. | package main
import (
"flag"
"image"
"image/color"
"image/png"
"os"
)
func main() {
input_img_ptr := flag.String("i", "input.png", "Input PNG image.")
output_img_ptr := flag.String("o", "output.png", "Output PNG image.")
flag.Parse()
// load file
input_img_raw, _ := os.Open(*input_img_ptr)
// decode png image
input_img, _ := png.Decode(input_img_raw)
// get image bounds
rectangle := input_img.Bounds()
// create output file
output_img_raw, _ := os.Create(*output_img_ptr)
// create output image
output_img := image.NewGray(rectangle)
for y := rectangle.Min.Y; y < rectangle.Max.Y; y++ {
for x := rectangle.Min.X; x < rectangle.Max.X; x++ {
c := color.GrayModel.Convert(input_img.At(x, y)).(color.Gray)
output_img.Set(x, y, c)
}
}
png.Encode(output_img_raw, output_img)
}
| package main
import (
"image"
"image/color"
"image/png"
"os"
)
func main() {
// load file
old_img_raw, _ := os.Open("img.png")
// decode png image
old_img, _ := png.Decode(old_img_raw)
// get image bounds
rectangle := old_img.Bounds()
// create new file
new_img_raw, _ := os.Create("new.png")
// create new image
new_img := image.NewGray(rectangle)
for y := rectangle.Min.Y; y < rectangle.Max.Y; y++ {
for x := rectangle.Min.X; x < rectangle.Max.X; x++ {
c := color.GrayModel.Convert(old_img.At(x, y)).(color.Gray)
new_img.Set(x, y, c)
}
}
png.Encode(new_img_raw, new_img)
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.