text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Exclude node modules from webpack using dir name | var webpack = require('webpack')
var path = require('path');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'test/**/*.js'
],
preprocessors: {
// add webpack as preprocessor
'src/**/*.js': ['webpack', 'sourcemap'],
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: { //kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
exclude: path.resolve(__dirname, 'node_modules'),
query: {
presets: ['airbnb']
}
},
{
test: /\.json$/,
loader: 'json',
},
]
},
externals: {
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
},
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-chrome-launcher',
'karma-phantomjs-launcher'
],
babelPreprocessor: {
options: {
presets: ['airbnb']
}
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
})
};
| var webpack = require('webpack')
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['jasmine'],
files: [
'test/**/*.js'
],
preprocessors: {
// add webpack as preprocessor
'src/**/*.js': ['webpack', 'sourcemap'],
'test/**/*.js': ['webpack', 'sourcemap']
},
webpack: { //kind of a copy of your webpack config
devtool: 'inline-source-map', //just do inline source maps instead of the default
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel',
query: {
presets: ['airbnb']
}
},
{
test: /\.json$/,
loader: 'json',
},
]
},
externals: {
'react/lib/ExecutionEnvironment': true,
'react/lib/ReactContext': true
}
},
webpackServer: {
noInfo: true //please don't spam the console when running in karma!
},
plugins: [
'karma-webpack',
'karma-jasmine',
'karma-sourcemap-loader',
'karma-chrome-launcher',
'karma-phantomjs-launcher'
],
babelPreprocessor: {
options: {
presets: ['airbnb']
}
},
reporters: ['progress'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false,
})
};
|
Read More module: changes to filter logic
Absence of a post indicates we are previewing content. | <?php
class ReadMore extends Modules {
public function __init() {
# Replace comment codes before markup modules filters them.
$this->setPriority("markup_post_text", 4);
}
public function markup_post_text($text, $post = null) {
if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches))
return $text;
$route = Route::current();
$controller = $route->controller;
if (!isset($post) or $route->action == "view" or ($controller instanceof MainController and $controller->feed))
return preg_replace("/<!-- *more(.+?)?-->/i", "", $text);
$more = oneof(trim(fallback($matches[1])), __("…more", "read_more"));
$url = (!$post->no_results) ? $post->url() : "#" ;
$split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY);
return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>';
}
public function title_from_excerpt($text) {
$split = preg_split('/<a class="read_more"/', $text);
return $split[0];
}
}
| <?php
class ReadMore extends Modules {
public function __init() {
# Replace comment codes before markup modules filters them.
$this->setPriority("markup_post_text", 4);
}
public function markup_post_text($text, $post = null) {
if (!is_string($text) or !preg_match("/<!-- *more(.+?)?-->/i", $text, $matches))
return $text;
$route = Route::current();
$controller = $route->controller;
if ($route->action == "view" or ($controller instanceof MainController and $controller->feed))
return preg_replace("/<!-- *more(.+?)?-->/i", "", $text);
$more = oneof(trim(fallback($matches[1])), __("…more", "read_more"));
$url = (isset($post) and !$post->no_results) ? $post->url() : "#" ;
$split = preg_split("/<!-- *more(.+?)?-->/i", $text, -1, PREG_SPLIT_NO_EMPTY);
return $split[0].'<a class="read_more" href="'.$url.'">'.$more.'</a>';
}
public function title_from_excerpt($text) {
$split = preg_split('/<a class="read_more"/', $text);
return $split[0];
}
}
|
Delete data check in __construct() | <?php
namespace ApiAi\Model;
/**
* Class Base
*
* @package ApiAi\Model
*/
class Base implements \JsonSerializable
{
/**
* @var array
*/
private $data;
/**
* Base constructor.
*
* @param array $data
*/
public function __construct($data = [])
{
$this->data = $data;
}
/**
* @return array
*/
public function jsonSerialize()
{
return $this->data;
}
/**
* @param string $name
*
* @return bool
*/
public function has($name)
{
return isset($this->data[$name]);
}
/**
* @param string $name
* @param mixed $default
*
* @return mixed
*/
public function get($name, $default = null)
{
return $this->getField($name, $default);
}
/**
* @param string $name
* @param mixed $value
*/
public function add($name, $value)
{
$this->data[$name] = $value;
}
/**
* @param string $name
*/
public function remove($name)
{
unset($this->data[$name]);
}
/**
* @param string $name
* @param mixed $default
*
* @return mixed
*/
private function getField($name, $default = null)
{
return $this->has($name) ? $this->data[$name] : $default;
}
}
| <?php
namespace ApiAi\Model;
/**
* Class Base
*
* @package ApiAi\Model
*/
class Base implements \JsonSerializable
{
/**
* @var array
*/
private $data;
/**
* Base constructor.
*
* @param array $data
*/
public function __construct($data = [])
{
if (empty($data)) {
throw new \InvalidArgumentException('__construct() $data must be defined');
}
$this->data = $data;
}
/**
* @return array
*/
public function jsonSerialize()
{
return $this->data;
}
/**
* @param string $name
*
* @return bool
*/
public function has($name)
{
return isset($this->data[$name]);
}
/**
* @param string $name
* @param mixed $default
*
* @return mixed
*/
public function get($name, $default = null)
{
return $this->getField($name, $default);
}
/**
* @param string $name
* @param mixed $value
*/
public function add($name, $value)
{
$this->data[$name] = $value;
}
/**
* @param string $name
*/
public function remove($name)
{
unset($this->data[$name]);
}
/**
* @param string $name
* @param mixed $default
*
* @return mixed
*/
private function getField($name, $default = null)
{
return $this->has($name) ? $this->data[$name] : $default;
}
}
|
Fix cityInfo tab not loading data after user completes form | 'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const models = require('../../db/models');
module.exports.getAll = (req, res) => {
models.User.where({ email: req.user.email}).fetch()
.then((result) => {
models.Stats.where({city: result.attributes.destination}).fetchAll()
.then(data => {
if (data.length === 0) {
request
.get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`,
(error, response, stats) => {
if (error) {
console.error(err);
}
models.Stats.forge({ city: result.attributes.destination, city_stats: stats })
.save()
.then(data => {
res.status(201).send(data.attributes.city_stats);
})
.catch(err => {
res.status(500).send(err);
});
})
.on('error', (err) => {
console.log(err);
res.status(500).send(err);
});
} else {
res.status(200).send(data.attributes.city_stats);
}
})
.catch(err => {
res.status(503).send(err);
});
})
.catch(err => {
res.status(503).send(err);
});
};
| 'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require('body-parser');
const request = require('request');
const models = require('../../db/models');
module.exports.getAll = (req, res) => {
models.User.where({ email: req.user.email}).fetch()
.then((result) => {
models.Stats.where({city: result.attributes.destination}).fetchAll()
.then(data => {
if (data.length === 0) {
request
.get(`https://api.teleport.org/api/urban_areas/slug:${result.attributes.destination}/scores/`,
(error, response, stats) => {
if (error) {
console.error(err);
}
models.Stats.forge({ city: result.attributes.destination, city_stats: stats })
.save()
.then(data => {
res.status(201).send(data.attributes.city_stats);
})
.catch(err => {
res.status(500).send(err);
});
})
.on('error', (err) => {
console.log(err);
res.status(500).send(err);
});
} else {
res.status(200).send(data.models[0].attributes.city_stats);
}
})
.catch(err => {
res.status(503).send(err);
});
})
.catch(err => {
res.status(503).send(err);
});
}; |
Change fov scaling to "Hor+". | #!/usr/bin/env python2
import math
import sys
from direct.showbase.ShowBase import ShowBase
import panda3d.core as p3d
import ecs
from player import PlayerController
class NodePathComponent(ecs.Component):
__slots__ = [
"nodepath",
]
def __init__(self, modelpath=None):
if modelpath is not None:
self.nodepath = base.loader.loadModel(modelpath)
else:
self.nodepath = p3d.NodePath(p3d.PandaNode('node'))
class Sigurd(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.disableMouse()
self.ecsmanager = ecs.ECSManager()
def run_ecs(task):
self.ecsmanager.update(0)
task.cont
self.taskMgr.add(run_ecs, 'ECS')
level = ecs.Entity()
np_component = NodePathComponent('models/level')
np_component.nodepath.reparent_to(base.render)
self.ecsmanager.add_entity(level)
PlayerController(self.camera)
self.accept('escape-up', sys.exit)
self.accept('aspectRatioChanged', self.cb_resize)
def cb_resize(self):
vfov = 70
aspect = self.camLens.get_aspect_ratio()
hfov = math.degrees(2 * math.atan(math.tan(math.radians(vfov)/2.0) * aspect))
print(hfov)
self.camLens.setFov(hfov, vfov)
if __name__ == '__main__':
app = Sigurd()
app.run()
| #!/usr/bin/env python2
import sys
from direct.showbase.ShowBase import ShowBase
import panda3d.core as p3d
import ecs
from player import PlayerController
class NodePathComponent(ecs.Component):
__slots__ = [
"nodepath",
]
def __init__(self, modelpath=None):
if modelpath is not None:
self.nodepath = base.loader.loadModel(modelpath)
else:
self.nodepath = p3d.NodePath(p3d.PandaNode('node'))
class Sigurd(ShowBase):
def __init__(self):
ShowBase.__init__(self)
self.disableMouse()
self.ecsmanager = ecs.ECSManager()
def run_ecs(task):
self.ecsmanager.update(0)
task.cont
self.taskMgr.add(run_ecs, 'ECS')
level = ecs.Entity()
np_component = NodePathComponent('models/level')
np_component.nodepath.reparent_to(base.render)
self.ecsmanager.add_entity(level)
PlayerController(self.camera)
self.camLens.setFov(90)
self.accept('escape-up', sys.exit)
if __name__ == '__main__':
app = Sigurd()
app.run()
|
Update error handler test for php52 | <?php
class ClientTest extends PHPUnit_Framework_TestCase {
protected $client;
protected function setUp(){
// Mock the notify function
$this->client = $this->getMockBuilder('Bugsnag_Client')
->setMethods(array('notify'))
->setConstructorArgs(array('6015a72ff14038114c3d12623dfb018f'))
->getMock();
// Activate the Bugsnag handlers
set_error_handler(array($this->client, "errorHandler"));
set_exception_handler(array($this->client, "exceptionHandler"));
}
protected function tearDown() {
// Remove the Bugsnag handlers
restore_error_handler();
restore_exception_handler();
}
public function testErrorHandler() {
$this->client->expects($this->once())
->method('notify');
$this->client->errorHandler(E_NOTICE, "Something broke", "somefile.php", 123);
}
public function testExceptionHandler() {
$this->client->expects($this->once())
->method('notify');
$this->client->exceptionHandler(new Exception("Something broke"));
}
public function testManualErrorNotification() {
$this->client->expects($this->once())
->method('notify');
$this->client->notifyError("SomeError", "Some message");
}
public function testManualExceptionNotification() {
$this->client->expects($this->once())
->method('notify');
$this->client->notifyException(new Exception("Something broke"));
}
}
?> | <?php
class ClientTest extends PHPUnit_Framework_TestCase {
protected $client;
protected function setUp(){
// Mock the notify function
$this->client = $this->getMockBuilder('Bugsnag_Client')
->setMethods(array('notify'))
->setConstructorArgs(array('6015a72ff14038114c3d12623dfb018f'))
->getMock();
// Activate the Bugsnag handlers
set_error_handler(array($this->client, "errorHandler"));
set_exception_handler(array($this->client, "exceptionHandler"));
}
protected function tearDown() {
// Remove the Bugsnag handlers
restore_error_handler();
restore_exception_handler();
}
public function testErrorHandler() {
$this->client->expects($this->once())
->method('notify');
// Triggers a E_NOTICE, which should be handled by our errorHandler
$foo = $bar;
}
public function testExceptionHandler() {
$this->client->expects($this->once())
->method('notify');
$this->client->exceptionHandler(new Exception("Something broke"));
}
public function testManualErrorNotification() {
$this->client->expects($this->once())
->method('notify');
$this->client->notifyError("SomeError", "Some message");
}
public function testManualExceptionNotification() {
$this->client->expects($this->once())
->method('notify');
$this->client->notifyException(new Exception("Something broke"));
}
}
?> |
Update GLPI to 0.91 in unit tests | <?php
require_once('commonfunction.php');
include_once (GLPI_ROOT . "/config/based_config.php");
include_once (GLPI_ROOT . "/inc/dbmysql.class.php");
include_once (GLPI_CONFIG_DIR . "/config_db.php");
class GLPIInstallTest extends PHPUnit_Framework_TestCase {
/**
* @test
*/
public function installDatabase() {
$DBvars = get_class_vars('DB');
drop_database(
$DBvars['dbuser'],
$DBvars['dbhost'],
$DBvars['dbdefault'],
$DBvars['dbpassword']
);
$result = load_mysql_file(
$DBvars['dbuser'],
$DBvars['dbhost'],
$DBvars['dbdefault'],
$DBvars['dbpassword'],
GLPI_ROOT ."/install/mysql/glpi-0.91-empty.sql"
);
$output = array();
$returncode = 0;
exec(
"php -f ".GLPI_ROOT. "/tools/cliupdate.php -- --upgrade",
$output, $returncode
);
$this->assertEquals(0,$returncode,
"Error when update GLPI in CLI mode\n".
implode("\n",$output)
);
$this->assertEquals( 0, $result['returncode'],
"Failed to install GLPI database:\n".
implode("\n", $result['output'])
);
}
}
| <?php
require_once('commonfunction.php');
include_once (GLPI_ROOT . "/config/based_config.php");
include_once (GLPI_ROOT . "/inc/dbmysql.class.php");
include_once (GLPI_CONFIG_DIR . "/config_db.php");
class GLPIInstallTest extends PHPUnit_Framework_TestCase {
/**
* @test
*/
public function installDatabase() {
$DBvars = get_class_vars('DB');
drop_database(
$DBvars['dbuser'],
$DBvars['dbhost'],
$DBvars['dbdefault'],
$DBvars['dbpassword']
);
$result = load_mysql_file(
$DBvars['dbuser'],
$DBvars['dbhost'],
$DBvars['dbdefault'],
$DBvars['dbpassword'],
GLPI_ROOT ."/install/mysql/glpi-0.90-empty.sql"
);
$output = array();
$returncode = 0;
exec(
"php -f ".GLPI_ROOT. "/tools/cliupdate.php -- --upgrade",
$output, $returncode
);
$this->assertEquals(0,$returncode,
"Error when update GLPI in CLI mode\n".
implode("\n",$output)
);
$this->assertEquals( 0, $result['returncode'],
"Failed to install GLPI database:\n".
implode("\n", $result['output'])
);
}
}
|
Fix broken code, comment out sun.awt.X11.XLayerProtocol | package dr.inference.model;
import dr.xml.*;
//import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
public static String SELECTOR = "selector";
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);
if( pool.getSize() != selector.getSize() ) {
throw new XMLParseException("variable Pool and selector must have equal length.");
}
return new ValuesPool(pool, selector);
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[] {
new ElementRule(VALUES, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) }),
new ElementRule(SELECTOR, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) })
};
}
public String getParserDescription() {
return "";
}
public Class getReturnType() {
return ValuesPool.class;
}
public String getParserName() {
return VALUES_POOL;
}
}
| package dr.inference.model;
import dr.xml.*;
import sun.awt.X11.XLayerProtocol;
/**
* @author Joseph Heled
* Date: 4/09/2009
*/
public class ValuesPoolParser extends dr.xml.AbstractXMLObjectParser {
public static String VALUES_POOL = "valuesPool";
public static String VALUES = "values";
public static String SELECTOR = "selector";
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final Variable pool = (Variable)xo.getElementFirstChild(VALUES);
final Variable selector = (Variable)xo.getElementFirstChild(SELECTOR);
if( pool.getSize() != selector.getSize() ) {
throw new XMLParseException("variable Pool and selector must have equal length.");
}
return new ValuesPool(pool, selector);
}
public XMLSyntaxRule[] getSyntaxRules() {
return new XMLSyntaxRule[] {
new ElementRule(VALUES, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) }),
new ElementRule(SELECTOR, new XMLSyntaxRule[]{
new ElementRule(Variable.class,1,1) })
};
}
public String getParserDescription() {
return "";
}
public Class getReturnType() {
return ValuesPool.class;
}
public String getParserName() {
return VALUES_POOL;
}
}
|
Correct header params on adapter | # coding: utf-8
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter):
resource_mapping = RESOURCE_MAPPING
api_root = 'https://api.harvestapp.com/v2/'
def get_request_kwargs(self, api_params, *args, **kwargs):
params = super(HarvestClientAdapter, self).get_request_kwargs(
api_params, *args, **kwargs)
params.setdefault('headers', {}).update({
'Authorization': 'Bearer %s' % api_params.get('token', ''),
'Harvest-Account-Id': api_params.get('account_id', ''),
'User-Agent': api_params.get('user_agent', '')
})
return params
def get_iterator_list(self, response_data):
return response_data
def get_iterator_next_request_kwargs(self, iterator_request_kwargs,
response_data, response):
pass
def response_to_native(self, response):
if response.content.strip():
return super(HarvestClientAdapter, self).response_to_native(response)
Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
| # coding: utf-8
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from requests.auth import HTTPBasicAuth
from .resource_mapping import RESOURCE_MAPPING
class HarvestClientAdapter(JSONAdapterMixin, TapiocaAdapter):
resource_mapping = RESOURCE_MAPPING
api_root = 'https://api.harvestapp.com/v2/'
def get_request_kwargs(self, api_params, *args, **kwargs):
params = super(HarvestClientAdapter, self).get_request_kwargs(
api_params, *args, **kwargs)
headers = {
'Authorization': 'Bearer %s' % params.get('token', ''),
'Harvest-Account-Id': params.get('account_id', ''),
'User-Agent': params.get('user_agent', '')
}
params['headers'] = params.get('headers', headers)
params['headers']['Accept'] = 'application/json'
return params
def get_iterator_list(self, response_data):
return response_data
def get_iterator_next_request_kwargs(self, iterator_request_kwargs,
response_data, response):
pass
def response_to_native(self, response):
if response.content.strip():
return super(HarvestClientAdapter, self).response_to_native(response)
Harvest = generate_wrapper_from_adapter(HarvestClientAdapter)
|
Set controller without __invoke method from invokable class | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Routing;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Route;
/**
* AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader
* that sets the '_controller' default based on the class and method names.
*
* @author Fabien Potencier <[email protected]>
*/
class AnnotatedRouteControllerLoader extends AnnotationClassLoader
{
/**
* Configures the _controller default parameter of a given Route instance.
*
* @param mixed $annot The annotation class instance
*/
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
{
if ('__invoke' === $method->getName()) {
$route->setDefault('_controller', $class->getName());
} else {
$route->setDefault('_controller', $class->getName().'::'.$method->getName());
}
}
/**
* Makes the default route name more sane by removing common keywords.
*
* @return string
*/
protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
{
return preg_replace(array(
'/(bundle|controller)_/',
'/action(_\d+)?$/',
'/__/',
), array(
'_',
'\\1',
'_',
), parent::getDefaultRouteName($class, $method));
}
}
| <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Routing;
use Symfony\Component\Routing\Loader\AnnotationClassLoader;
use Symfony\Component\Routing\Route;
/**
* AnnotatedRouteControllerLoader is an implementation of AnnotationClassLoader
* that sets the '_controller' default based on the class and method names.
*
* @author Fabien Potencier <[email protected]>
*/
class AnnotatedRouteControllerLoader extends AnnotationClassLoader
{
/**
* Configures the _controller default parameter of a given Route instance.
*
* @param mixed $annot The annotation class instance
*/
protected function configureRoute(Route $route, \ReflectionClass $class, \ReflectionMethod $method, $annot)
{
$route->setDefault('_controller', $class->getName().'::'.$method->getName());
}
/**
* Makes the default route name more sane by removing common keywords.
*
* @return string
*/
protected function getDefaultRouteName(\ReflectionClass $class, \ReflectionMethod $method)
{
return preg_replace(array(
'/(bundle|controller)_/',
'/action(_\d+)?$/',
'/__/',
), array(
'_',
'\\1',
'_',
), parent::getDefaultRouteName($class, $method));
}
}
|
Support for value of None in MoneyField.compress.
Leaving a MoneyField blank in the Django admin site caused an issue when
attempting to save an exception was raised since Money was getting an
argument list of None. | from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES,
max_value=None, min_value=None,
max_digits=None, decimal_places=None, *args, **kwargs):
if currency_choices != CURRENCY_CHOICES:
warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning)
choices = currency_choices
decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs)
choice_field = ChoiceField(choices=currency_choices)
self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget,
currency_widget=choice_field.widget)
fields = (decimal_field, choice_field)
super(MoneyField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
try:
if data_list[0] is None:
return None
except IndexError:
return None
return Money(*data_list[:2])
| from __future__ import unicode_literals
from warnings import warn
from django.forms import MultiValueField, DecimalField, ChoiceField
from moneyed.classes import Money
from .widgets import MoneyWidget, CURRENCY_CHOICES
__all__ = ('MoneyField',)
class MoneyField(MultiValueField):
def __init__(self, currency_widget=None, currency_choices=CURRENCY_CHOICES, choices=CURRENCY_CHOICES,
max_value=None, min_value=None,
max_digits=None, decimal_places=None, *args, **kwargs):
if currency_choices != CURRENCY_CHOICES:
warn('currency_choices will be deprecated in favor of choices', PendingDeprecationWarning)
choices = currency_choices
decimal_field = DecimalField(max_value, min_value, max_digits, decimal_places, *args, **kwargs)
choice_field = ChoiceField(choices=currency_choices)
self.widget = currency_widget if currency_widget else MoneyWidget(amount_widget=decimal_field.widget,
currency_widget=choice_field.widget)
fields = (decimal_field, choice_field)
super(MoneyField, self).__init__(fields, *args, **kwargs)
def compress(self, data_list):
return Money(*data_list[:2]) |
Implement destroy function for category destroy | @if ((int) count($categories) === 0)
<div class="alert alert-info" role="alert">
<strong><span class="fa fa-info-circle"></span> Info:</strong>
Er zijn geen categorieen gevonden voor de helpdesk in het systeem.
</div>
@else
<table class="table table-condensed table-hover">
<thead>
<tr>
<th>#</th>
<th>Aangemaakt door:</th>
<th>Categorie:</th>
<th colspan="2">Vragen:</th> {{-- Colspan 2 is needed because the functions are embedded. --}}
</tr>
</thead>
<tbody>
@foreach($categories as $category)
<tr>
<td><code>#C{{ $category->id }}</code></td>
<td>{{ $category->creator->name }}</td>
<td>{{ $category->category }}</td>
<td><span class="label label-primary">{{ count($category->question) }} Vragen </span></td>
{{-- Functions --}}
<td>
<a href="{{ base_url() }}" class="label label-success">Bekijken</a>
<a href="{{ base_url('category/destroy/', $category->id) }}" class="label label-danger">Verwijder</a>
</td>
{{-- /Functions --}}
</tr>
@endforeach
</tbody>
</table>
@endif
| @if ((int) count($categories) === 0)
<div class="alert alert-info" role="alert">
<strong><span class="fa fa-info-circle"></span> Info:</strong>
Er zijn geen categorieen gevonden voor de helpdesk in het systeem.
</div>
@else
<table class="table table-condensed table-hover">
<thead>
<tr>
<th>#</th>
<th>Aangemaakt door:</th>
<th>Categorie:</th>
<th colspan="2">Vragen:</th> {{-- Colspan 2 is needed because the functions are embedded. --}}
</tr>
</thead>
<tbody>
@foreach($categories as $category)
<tr>
<td><code>#C{{ $category->id }}</code></td>
<td>{{ $category->creator->name }}</td>
<td>{{ $category->category }}</td>
<td><span class="label label-primary">{{ count($category->question) }} Vragen </span></td>
{{-- Functions --}}
<td>
<a href="#" class="label label-success">Bekijken</a>
<a href="#" class="label label-danger">Verwijder</a>
</td>
{{-- /Functions --}}
</tr>
@endforeach
</tbody>
</table>
@endif
|
Allow newer versions of pyinotify | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'spotter',
version = '1.7',
url = "http://github.com/borntyping/spotter",
author = "Sam Clements",
author_email = "[email protected]",
description = "A command line tool for watching files and running shell commands when they change.",
long_description = open('README.rst').read(),
license = 'MIT',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Operating System :: Unix',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Testing',
'Topic :: System :: Monitoring',
'Topic :: Utilities',
],
packages = find_packages(),
entry_points = {
'console_scripts': [
'spotter = spotter:main',
]
},
install_requires = [
'pyinotify>=0.9.4',
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name = 'spotter',
version = '1.7',
url = "http://github.com/borntyping/spotter",
author = "Sam Clements",
author_email = "[email protected]",
description = "A command line tool for watching files and running shell commands when they change.",
long_description = open('README.rst').read(),
license = 'MIT',
classifiers = [
'Development Status :: 4 - Beta',
'Environment :: Console',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Operating System :: Unix',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Testing',
'Topic :: System :: Monitoring',
'Topic :: Utilities',
],
packages = find_packages(),
entry_points = {
'console_scripts': [
'spotter = spotter:main',
]
},
install_requires = [
'pyinotify==0.9.4',
],
)
|
Update LTS versions in test matrix | /* eslint-env node */
module.exports = {
scenarios: [
{
name: 'ember-lts-2.12',
npm: {
devDependencies: {
'ember-source': '~2.12.0'
}
}
},
{
name: 'ember-lts-2.16',
npm: {
devDependencies: {
'ember-source': '~2.16.0'
}
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-default',
npm: {
devDependencies: {}
}
}
]
};
| /* eslint-env node */
module.exports = {
scenarios: [
{
name: 'ember-lts-2.8',
bower: {
dependencies: {
'ember': 'components/ember#lts-2-8'
},
resolutions: {
'ember': 'lts-2-8'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-lts-2.12',
npm: {
devDependencies: {
'ember-source': '~2.12.0'
}
}
},
{
name: 'ember-release',
bower: {
dependencies: {
'ember': 'components/ember#release'
},
resolutions: {
'ember': 'release'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-beta',
bower: {
dependencies: {
'ember': 'components/ember#beta'
},
resolutions: {
'ember': 'beta'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-canary',
bower: {
dependencies: {
'ember': 'components/ember#canary'
},
resolutions: {
'ember': 'canary'
}
},
npm: {
devDependencies: {
'ember-source': null
}
}
},
{
name: 'ember-default',
npm: {
devDependencies: {}
}
}
]
};
|
Update language for over view charts | 'use strict';
module.exports = {
$meta: 'English translation file',
navigation: {
overview: {
$filter: 'role',
district: 'District Performance',
block: 'Block Performance',
$default: 'Overview Performance'
},
discrete: {
$filter: 'role',
district: 'Block Performance',
block: 'Panchayat Performance',
$default: 'Discrete Performance'
}
},
messages: {
loading: 'Loading graph data',
not_found: 'Page does not exist'
},
payment_steps: {
'1': 'Muster roll closure to muster roll entry',
'2': 'Muster roll entry to wage list generation',
'3': 'FTO generation to first signature',
'4': 'Wage list generation to wage list sign',
'5': 'Wage list sign to FTO generation',
'6': 'First signature to second signature',
'7': 'Second signature to processed by bank'
},
performance: {
overview: {
performance_chart: {
title: {
$filter: 'role',
district: 'District Performance',
block: 'Block Performance',
$default: 'Overview Performance'
},
description: {
$filter: 'role',
district: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
block: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.',
$default: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.'
}
}
}
}
};
| 'use strict';
module.exports = {
$meta: 'English translation file',
navigation: {
overview: {
$filter: 'role',
district: 'District Performance',
block: 'Block Performance',
$default: 'Overview Performance'
},
discrete: {
$filter: 'role',
district: 'Block Performance',
block: 'Panchayat Performance',
$default: 'Discrete Performance'
}
},
messages: {
loading: 'Loading graph data',
not_found: 'Page does not exist'
},
payment_steps: {
'1': 'Muster roll closure to muster roll entry',
'2': 'Muster roll entry to wage list generation',
'3': 'FTO generation to first signature',
'4': 'Wage list generation to wage list sign',
'5': 'Wage list sign to FTO generation',
'6': 'First signature to second signature',
'7': 'Second signature to processed by bank'
},
performance: {
overview: {
title: {
$filter: 'role',
district: 'You are looking at payment processing time in',
block: 'You are looking at payment processing time in',
$default: 'You are looking at payment processing time in'
}
}
}
};
|
Use heroku api by default | import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import Login from './components/Login/Login.js';
// TODO Use prod server in prod mode
const server = 'https://satoshi-api.herokuapp.com'
// const server = 'http://localhost:8080'
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = { text: null };
}
onLogin = async (nickname) => {
const deviceId = 'TODO DeviceID'
console.log(`Login: (${nickname}, ${deviceId})`) // user credentials
let response = await fetch(`${server}/api/login`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
nickname: nickname,
deviceId: deviceId,
})
})
let json = await response.json();
switch (json.status) {
case 'STATUS_OK':
this.props.navigation.navigate('Profile', { nickname: nickname })
return;
}
console.log('Username does not exist');
// TODO Display Error
}
render() {
return (
<View>
<Text>Welcome to Satoshi</Text>
<Login onLogin={this.onLogin} />
</View>
);
}
} | import React from 'react';
import { StyleSheet, Text, View, TextInput, Button } from 'react-native';
import Login from './components/Login/Login.js';
// TODO Use prod server in prod mode
// const server = 'https://satoshi-api.herokuapp.com'
const server = 'http://localhost:8080'
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = { text: null };
}
onLogin = async (nickname) => {
const deviceId = 'TODO DeviceID'
console.log(`Login: (${nickname}, ${deviceId})`) // user credentials
let response = await fetch(`${server}/api/login`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
nickname: nickname,
deviceId: deviceId,
})
})
let json = await response.json();
switch (json.status) {
case 'STATUS_OK':
this.props.navigation.navigate('Profile', { nickname: nickname })
return;
}
console.log('Username does not exist');
// TODO Display Error
}
render() {
return (
<View>
<Text>Welcome to Satoshi</Text>
<Login onLogin={this.onLogin} />
</View>
);
}
} |
[TASK] Adjust test fixture to Doctrine.ORM 2.2.0
The proxy interface in Common is now used, the fixture needs to
be adjusted.
Change-Id: I0ed772ad4d04cf80679f7f726698c9278812b2d9
Related: #32608
Releases: 1.1
Original-Commit-Hash: c2c171d440e60457cbefc8e11ec83bc41b4fc7f9 | <?php
namespace TYPO3\FLOW3\Tests\Functional\Reflection\Fixtures;
/* *
* This script belongs to the FLOW3 framework. *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License, either version 3 *
* of the License, or (at your option) any later version. *
* *
* The TYPO3 project - inspiring people to share! *
* */
/**
* A fixture for testing that doctrine proxies can never be reflected.
*
* See issue http://forge.typo3.org/issues/29449 for details.
*/
class BrokenClassImplementingDoctrineProxy {
// This class just exists to satisfy the class loader -- else the compilation
// run during functional tests will fail, as it expects to find a class named
// like the file. It is NOT used for the testcase.
}
namespace TYPO3\FLOW3\Persistence\Doctrine\Proxies;
/**
* This is our fake "doctrine proxy class"; which is in the same namespace
* as all the other doctrine proxies. Trying to reflect this class should
* result in an exception.
*
*/
abstract class FakePackageDomainModelBrokenClassProxy implements \Doctrine\ORM\Proxy\Proxy {
}
?> | <?php
namespace TYPO3\FLOW3\Tests\Functional\Reflection\Fixtures;
/* *
* This script belongs to the FLOW3 framework. *
* *
* It is free software; you can redistribute it and/or modify it under *
* the terms of the GNU Lesser General Public License, either version 3 *
* of the License, or (at your option) any later version. *
* *
* The TYPO3 project - inspiring people to share! *
* */
/**
* A fixture for testing that doctrine proxies can never be reflected.
*
* See issue http://forge.typo3.org/issues/29449 for details.
*/
class BrokenClassImplementingDoctrineProxy {
// This class just exists to satisfy the class loader -- else the compilation
// run during functional tests will fail. It is NOT used for the testcase.
}
namespace TYPO3\FLOW3\Persistence\Doctrine\Proxies;
/**
* This is our fake "doctrine proxy class"; which is in the same namespace
* as all the other doctrine proxies. Trying to reflect this class should
* result in an exception.
*
*/
class FakePackageDomainModelBrokenClassProxy implements \Doctrine\ORM\Proxy\Proxy {
}
?> |
Update the version of the config too. | package ro.nicuch.citizensbooks;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class ConfigUpdater {
public static boolean updateConfig(CitizensBooksPlugin plugin, int oldVersion) {
if (oldVersion == 7) {
Map<String, String> commandsMap = new HashMap<>();
plugin.getSettings().getConfigurationSection("commands").getKeys(false).forEach(str -> commandsMap.put(str, plugin.getSettings().getString("commands." + str)));
plugin.getSettings().set("commands", null);
commandsMap.forEach((key, value) -> {
plugin.getSettings().set("commands." + key + ".filter_name", value);
plugin.getSettings().set("commands." + key + ".permission", "none"); //default permission is to none
});
plugin.getSettings().set("lang.player_not_found", ConfigDefaults.player_not_found);
plugin.getSettings().set("lang.filter_not_found", ConfigDefaults.filter_not_found);
plugin.getSettings().set("lang.usage.forceopen", ConfigDefaults.usage_forceopen);
plugin.getSettings().set("lang.help.forceopen", ConfigDefaults.help_forceopen);
plugin.getSettings().set("version", plugin.configVersion); //update the version
plugin.saveSettings(); //save settings
return true;
}
return false;
}
}
| package ro.nicuch.citizensbooks;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
public class ConfigUpdater {
public static boolean updateConfig(CitizensBooksPlugin plugin, int oldVersion) {
if (oldVersion == 7) {
Map<String, String> commandsMap = new HashMap<>();
plugin.getSettings().getConfigurationSection("commands").getKeys(false).forEach(str -> commandsMap.put(str, plugin.getSettings().getString("commands." + str)));
plugin.getSettings().set("commands", null);
commandsMap.forEach((key, value) -> {
plugin.getSettings().set("commands." + key + ".filter_name", value);
plugin.getSettings().set("commands." + key + ".permission", "none"); //default permission is to none
});
plugin.getSettings().set("lang.player_not_found", ConfigDefaults.player_not_found);
plugin.getSettings().set("lang.filter_not_found", ConfigDefaults.filter_not_found);
plugin.getSettings().set("lang.usage.forceopen", ConfigDefaults.usage_forceopen);
plugin.getSettings().set("lang.help.forceopen", ConfigDefaults.help_forceopen);
plugin.saveSettings(); //save settings
return true;
}
return false;
}
}
|
Remove bluebird require from AdapterManager | var fs = require('fs'),
Path = require('path');
/**
* Represents an object capable of listing and loading adapters using defined
* conventions.
*
* @constructor
*/
var Adapters = function() {
this.basePath = Path.resolve(Path.join(__dirname, '..', 'adapters'));
};
Adapters.prototype = {
/**
* Gets a list of available adapters in the adapters folder.
* @return {String[]} List containing the names of available adapters.
*/
getAdapters: function() {
return fs.readdirSync(this.basePath)
.map(d => Path.join(this.basePath, d))
.filter(d => fs.statSync(d).isDirectory())
.filter(d => fs.readdirSync(d).some(f => f === 'index.js'))
.map(d => Path.basename(d));
},
/**
* Loads an adapter.
* @param {String} name Name of the adapter to be loaded.
* @return {Promise} Promise that will be resolved when the given adapter is loaded.
* Can be rejected if there's a problem during the process.
*/
loadAdapter: function(name) {
return new Promise((resolve, reject) => {
var entrypoint = Path.join(this.basePath, name, 'index.js');
try {
var klass = require(entrypoint);
resolve(klass);
} catch(ex) {
reject(ex);
}
});
}
};
module.exports = Adapters;
| var fs = require('fs'),
Path = require('path'),
Promise = require('bluebird');
/**
* Represents an object capable of listing and loading adapters using defined
* conventions.
*
* @constructor
*/
var Adapters = function() {
this.basePath = Path.resolve(Path.join(__dirname, '..', 'adapters'));
};
Adapters.prototype = {
/**
* Gets a list of available adapters in the adapters folder.
* @return {String[]} List containing the names of available adapters.
*/
getAdapters: function() {
return fs.readdirSync(this.basePath)
.map(d => Path.join(this.basePath, d))
.filter(d => fs.statSync(d).isDirectory())
.filter(d => fs.readdirSync(d).some(f => f === 'index.js'))
.map(d => Path.basename(d));
},
/**
* Loads an adapter.
* @param {String} name Name of the adapter to be loaded.
* @return {Promise} Promise that will be resolved when the given adapter is loaded.
* Can be rejected if there's a problem during the process.
*/
loadAdapter: function(name) {
return new Promise((resolve, reject) => {
var entrypoint = Path.join(this.basePath, name, 'index.js');
try {
var klass = require(entrypoint);
resolve(klass);
} catch(ex) {
reject(ex);
}
});
}
};
module.exports = Adapters;
|
Fix group on equality iterator type hints | <?php
namespace Pinq\Iterators\Standard;
use Pinq\Iterators\Common;
/**
* Implementation of the join iterator using the fetch method.
*
* @author Elliot Levin <[email protected]>
*/
class GroupJoinOnEqualityIterator extends GroupJoinIterator
{
use Common\JoinOnEqualityIterator;
/**
* @var OrderedMap
*/
protected $innerGroups;
public function __construct(
IIterator $outerIterator,
IIterator $innerIterator,
callable $traversableFactory,
callable $outerKeyFunction,
callable $innerKeyFunction)
{
parent::__construct($outerIterator, $innerIterator, $traversableFactory);
self::__constructJoinOnEqualityIterator($outerKeyFunction, $innerKeyFunction);
}
protected function doRewind()
{
$this->innerGroups = (new OrderedMap($this->innerIterator))->groupBy($this->innerKeyFunction);
parent::doRewind();
}
protected function getInnerValuesIterator($outerKey, $outerValue)
{
$outerKeyFunction = $this->outerKeyFunction;
$traversableFactory = $this->traversableFactory;
$groupKey = $outerKeyFunction($outerValue, $outerKey);
$traversableGroup = $traversableFactory($this->innerGroups->contains($groupKey) ?
$this->innerGroups->get($groupKey) : []);
return new ArrayIterator([$groupKey => $traversableGroup]);
}
}
| <?php
namespace Pinq\Iterators\Standard;
use Pinq\Iterators\Common;
/**
* Implementation of the join iterator using the fetch method.
*
* @author Elliot Levin <[email protected]>
*/
class GroupJoinOnEqualityIterator extends GroupJoinIterator
{
use Common\JoinOnEqualityIterator;
/**
* @var OrderedMap
*/
protected $innerGroups;
public function __construct(
\Traversable $outerIterator,
\Traversable $innerIterator,
callable $traversableFactory,
callable $outerKeyFunction,
callable $innerKeyFunction)
{
parent::__construct($outerIterator, $innerIterator, $traversableFactory);
self::__constructJoinOnEqualityIterator($outerKeyFunction, $innerKeyFunction);
}
protected function doRewind()
{
$this->innerGroups = (new OrderedMap($this->innerIterator))->groupBy($this->innerKeyFunction);
parent::doRewind();
}
protected function getInnerValuesIterator($outerKey, $outerValue)
{
$outerKeyFunction = $this->outerKeyFunction;
$traversableFactory = $this->traversableFactory;
$groupKey = $outerKeyFunction($outerValue, $outerKey);
$traversableGroup = $traversableFactory($this->innerGroups->contains($groupKey) ?
$this->innerGroups->get($groupKey) : []);
return new ArrayIterator([$groupKey => $traversableGroup]);
}
}
|
Add user page favorites and uploads number indicator | import React, { Component, PropTypes } from 'react'
import { Container, Segment, Menu, Header, Label } from 'semantic-ui-react'
import { Link } from 'react-router'
import moment from 'moment'
const propTypes = {
user: PropTypes.object
}
class UserPage extends Component {
render() {
const { user } = this.props
if (!user) return null
return (
<Container>
<Segment>
<Menu secondary>
<Menu.Item>
<Header>
<Link to={`/user/${user._id}`}>{user.username}</Link>
<Header.Subheader>
Joined {moment(user.createdAt).fromNow()}
</Header.Subheader>
</Header>
</Menu.Item>
<Menu.Item
as={Link}
to={`/user/${user._id}/favorites`}
name="Favorites"
activeClassName="active"
>
Favorites
<Label color="yellow" content={user.favorites.length} floating />
</Menu.Item>
<Menu.Item
as={Link}
to={`/user/${user._id}/uploads`}
name="Uploads"
activeClassName="active"
>
Uploads
<Label color="teal" content={user.screenshots.length} floating />
</Menu.Item>
{/* <Menu.Item name='Settings' activeClassName="active" /> */}
</Menu>
</Segment>
<Segment basic vertical>
{this.props.children}
</Segment>
</Container>
)
}
}
UserPage.propTypes = propTypes
export default UserPage
| import React, { Component, PropTypes } from 'react'
import { Container, Segment, Menu, Header } from 'semantic-ui-react'
import { Link } from 'react-router'
import moment from 'moment'
const propTypes = {
user: PropTypes.object
}
class UserPage extends Component {
render() {
const { user } = this.props
if (!user) return null
return (
<Container>
<Segment>
<Menu secondary>
<Menu.Item>
<Header>
<Link to={`/user/${user._id}`}>{user.username}</Link>
<Header.Subheader>
Joined {moment(user.createdAt).fromNow()}
</Header.Subheader>
</Header>
</Menu.Item>
<Menu.Item
as={Link}
to={`/user/${user._id}/favorites`}
name="Favorites"
activeClassName="active"
/>
<Menu.Item
as={Link}
to={`/user/${user._id}/uploads`}
name="Uploads"
activeClassName="active"
/>
{/* <Menu.Item name='Settings' activeClassName="active" /> */}
</Menu>
</Segment>
<Segment basic vertical>
{this.props.children}
</Segment>
</Container>
)
}
}
UserPage.propTypes = propTypes
export default UserPage
|
Use the right case for the package name | #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.executable,
'-m', 'unittest',
'discover',
'-p', '*.py',
'tests',
])
raise SystemExit(errno)
setup(name='steel',
version='0.1',
description='A Python framework for describing binary file formats',
author='Marty Alchin',
author_email='[email protected]',
url='https://github.com/gulopine/steel',
packages=['steel'],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: System :: Filesystems',
],
cmdclass={'test': TestDiscovery},
)
| #!/usr/bin/env python
from distutils.core import setup, Command
class TestDiscovery(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
import sys, subprocess
errno = subprocess.call([
sys.executable,
'-m', 'unittest',
'discover',
'-p', '*.py',
'tests',
])
raise SystemExit(errno)
setup(name='Steel',
version='0.1',
description='A Python framework for describing binary file formats',
author='Marty Alchin',
author_email='[email protected]',
url='https://github.com/gulopine/steel',
packages=['steel'],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Programming Language :: Python :: 3.1',
'Programming Language :: Python :: 3.2',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: System :: Filesystems',
],
cmdclass={'test': TestDiscovery},
)
|
Add Dependent Fixture Interface to fix fixture loading | <?php
namespace Soflomo\Blog\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\DependentFixtureInterface;
use Faker;
use Soflomo\Blog\Entity\Article;
class ArticleData extends AbstractFixture implements DependentFixtureInterface
{
protected $n = 10;
public function load(ObjectManager $manager)
{
$blog = $this->getReference('blog');
$faker = Faker\Factory::create('nl_NL');
for ($i=1; $i<=$this->n; $i++) {
$article = new Article;
$article->setTitle($faker->sentence(rand(3,6))); // Words
$article->setLead($faker->paragraph(rand(6,8))); // Sentences
$article->setBody($faker->paragraph(rand(6,10))); // Sentences
if (!$faker->boolean(10)) {
// For 9/10 cases post has publish date
$article->setPublishDate($faker->dateTimeThisMonth);
}
$article->setBlog($blog);
$manager->persist($article);
}
$manager->flush();
}
public function getDependencies()
{
return array(
'Soflomo\Blog\Fixture\BlogData',
);
}
} | <?php
namespace Soflomo\Blog\Fixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Faker;
use Soflomo\Blog\Entity\Article;
class ArticleData extends AbstractFixture
{
protected $n = 10;
public function load(ObjectManager $manager)
{
$blog = $this->getReference('blog');
$faker = Faker\Factory::create('nl_NL');
for ($i=1; $i<=$this->n; $i++) {
$article = new Article;
$article->setTitle($faker->sentence(rand(3,6))); // Words
$article->setLead($faker->paragraph(rand(6,8))); // Sentences
$article->setBody($faker->paragraph(rand(6,10))); // Sentences
if (!$faker->boolean(10)) {
// For 9/10 cases post has publish date
$article->setPublishDate($faker->dateTimeThisMonth);
}
$article->setBlog($blog);
$manager->persist($article);
}
$manager->flush();
}
public function getDependencies()
{
return array(
'Soflomo\Blog\Fixture\BlogData',
);
}
} |
Check we've got a result object before exiting the results loop. | /**
* bit.ly access library code.
*/
Shortener = {
displayName: 'Shortener',
shorten: function() {
var uri, callback, name;
if (typeof arguments[0] == 'string') {
uri = arguments[0];
callback = arguments[1];
} else {
uri = window.location.href;
callback = arguments[0];
}
name = this._registerCallback(callback);
if (name && this.CLIENT) {
this.CLIENT.call('shorten', {'longUrl': uri}, 'BitlyCB.' + name);
}
},
_dispatcher: function(callback, data) {
var result, p;
// Results are keyed by longUrl, so we need to grab the first one.
for (p in data.results) {
result = data.results[p];
if (typeof result == 'object') break;
}
callback.call(null, result, data);
},
_registerCallback: function(callback) {
if (!this.NAMESPACE) return false;
var name = 'abbr' + this.callbackCount,
self = this;
this.callbackCount += 1;
this.NAMESPACE[name] = function(data) {
self._dispatcher(callback, data);
};
return name;
},
callbackCount: 0,
CLIENT: BitlyClient,
NAMESPACE: BitlyCB
};
| /**
* bit.ly access library code.
*/
Shortener = {
displayName: 'Shortener',
shorten: function() {
var uri, callback, name;
if (typeof arguments[0] == 'string') {
uri = arguments[0];
callback = arguments[1];
} else {
uri = window.location.href;
callback = arguments[0];
}
name = this._registerCallback(callback);
if (name && this.CLIENT) {
this.CLIENT.call('shorten', {'longUrl': uri}, 'BitlyCB.' + name);
}
},
_dispatcher: function(callback, data) {
var result, p;
// Results are keyed by longUrl, so we need to grab the first one.
for (p in data.results) {
result = data.results[p];
break;
}
callback.call(null, result, data);
},
_registerCallback: function(callback) {
if (!this.NAMESPACE) return false;
var name = 'abbr' + this.callbackCount,
self = this;
this.callbackCount += 1;
this.NAMESPACE[name] = function(data) {
self._dispatcher(callback, data);
};
return name;
},
callbackCount: 0,
CLIENT: BitlyClient,
NAMESPACE: BitlyCB
};
|
Update bookmark interface to work with mercurial 3.0.2
--HG--
extra : transplant_source : Qn%AB4%08%F4%3D%60%0DDb%10%E1%9C%A2%82%00z%1D5 |
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.4"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mirror paths to the repo.
Also creates a `master` bookmark for the `default` branch.
"""
if len(getattr(repo, "changelog", [])) == 0:
return
hggit_reposetup(ui, repo, **kwargs)
bb = "ssh://[email protected]/"
for pathname, path in ui.configitems("paths"):
if path.startswith(bb):
user, project = path.replace(bb, "").split("/", 1)
# Strip slash and everything after it,
# such as mq patch queue path.
project = project.split("/")[0]
for k, v in ui.configitems("github"):
if k == "username":
user = v
gh_path = "git+ssh://[email protected]/%s/%s.git" % (user, project)
if pathname == "default":
if "master" not in repo._bookmarks:
from mercurial.commands import bookmark
bookmark(ui, repo, "master", rev="default")
gh_pathname = "github"
else:
gh_pathname = "github-" + pathname
ui.setconfig("paths", gh_pathname, gh_path)
|
# Mimic the hggit extension.
try:
from hggit import *
hggit_reposetup = reposetup
except ImportError:
# Allow this module to be imported without
# hg-git installed, eg for setup.py
pass
__version__ = "0.1.4"
def reposetup(ui, repo, **kwargs):
"""
Automatically adds Bitbucket->GitHub mirror paths to the repo.
Also creates a `master` bookmark for the `default` branch.
"""
if len(getattr(repo, "changelog", [])) == 0:
return
hggit_reposetup(ui, repo, **kwargs)
bb = "ssh://[email protected]/"
for pathname, path in ui.configitems("paths"):
if path.startswith(bb):
user, project = path.replace(bb, "").split("/", 1)
# Strip slash and everything after it,
# such as mq patch queue path.
project = project.split("/")[0]
for k, v in ui.configitems("github"):
if k == "username":
user = v
gh_path = "git+ssh://[email protected]/%s/%s.git" % (user, project)
if pathname == "default":
if "master" not in repo._bookmarks:
from mercurial.commands import bookmark
bookmark(ui, repo, mark="master", rev="default")
gh_pathname = "github"
else:
gh_pathname = "github-" + pathname
ui.setconfig("paths", gh_pathname, gh_path)
|
Make mono channel output activation more readable | from keras.layers import Convolution2D, Reshape, Lambda, Activation
from eva.layers.masked_convolution2d import MaskedConvolution2D
class OutChannels(object):
def __init__(self, height, width, channels, masked=False, palette=256):
self.height = height
self.width = width
self.channels = channels
self.cxp = MaskedConvolution2D if masked else Convolution2D
self.palette = palette
def __call__(self, model):
if self.channels == 1:
outs = Convolution2D(1, 1, 1, border_mode='valid')(model)
outs = Activation('sigmoid')(outs)
else:
out = self.cxp(self.palette*self.channels, 1, 1, border_mode='valid', name='channels_mult_palette')(model)
out = Reshape((self.height, self.width, self.palette, self.channels), name='palette_channels')(out)
outs = [None] * self.channels
for i in range(self.channels):
outs[i] = Lambda(lambda x: x[:, :, :, :, i], name='channel'+str(i)+'_extract')(out)
outs[i] = Reshape((self.height * self.width, self.palette), name='hw_palette'+str(i))(outs[i])
outs[i] = Activation('softmax', name='channel'+str(i))(outs[i])
return outs | from keras.layers import Convolution2D, Reshape, Lambda, Activation
from eva.layers.masked_convolution2d import MaskedConvolution2D
class OutChannels(object):
def __init__(self, height, width, channels, masked=False, palette=256):
self.height = height
self.width = width
self.channels = channels
self.cxp = MaskedConvolution2D if masked else Convolution2D
self.palette = palette
def __call__(self, model):
if self.channels == 1:
outs = Convolution2D(1, 1, 1, activation='sigmoid', border_mode='valid')(model)
else:
out = self.cxp(self.palette*self.channels, 1, 1, border_mode='valid', name='channels_mult_palette')(model)
out = Reshape((self.height, self.width, self.palette, self.channels), name='palette_channels')(out)
outs = [None] * self.channels
for i in range(self.channels):
outs[i] = Lambda(lambda x: x[:, :, :, :, i], name='channel'+str(i)+'_extract')(out)
outs[i] = Reshape((self.height * self.width, self.palette), name='hw_palette'+str(i))(outs[i])
outs[i] = Activation('softmax', name='channel'+str(i))(outs[i])
return outs |
[HeartBeat] Allow current frame modifictation by event | (function($, document, window) {
"use strict"
window.animationHeartBeat = function (steps)
{
var max = steps;
var delay = 70;
var current = 0;
var interval;
var beat;
$(document).bind('animation.stop', function()
{
console.log('animation.stop event caught');
clearInterval(interval);
});
$(document).bind('animation.start', function()
{
console.log('animation.start event caught');
if (current > max)
{
$(document).trigger('animation.reset');
}
interval = setInterval(beat, delay);
});
$(document).bind('animation.reset', function()
{
console.log('animation.reset event caught');
current = 0;
});
$(document).bind('animation.beat', function(event, animation)
{
current = animation.current + 1;
});
beat = function ()
{
$(document).trigger('animation.beat', [{'current': current, 'max': max}]);
if (current > max)
{
$(document).trigger('animation.stop');
}
}
}
})(jQuery, document, window);
| (function($, document, window) {
"use strict"
window.animationHeartBeat = function (steps)
{
var max = steps;
var delay = 70;
var current = 0;
var interval;
var beat;
$(document).bind('animation.stop', function()
{
console.log('animation.stop event caught');
clearInterval(interval);
});
$(document).bind('animation.start', function()
{
console.log('animation.start event caught');
if (current > max)
{
$(document).trigger('animation.reset');
}
interval = setInterval(beat, delay);
});
$(document).bind('animation.reset', function()
{
console.log('animation.reset event caught');
current = 0;
});
beat = function ()
{
$(document).trigger('animation.beat', [{'current': current, 'max': max}]);
current++;
if (current > max)
{
$(document).trigger('animation.stop');
}
}
}
})(jQuery, document, window); |
Fix broken default config file | <?php namespace Jigsaw\Jigsaw\Console;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class InitCommand extends Command
{
private $files;
private $base;
public function __construct(Filesystem $files)
{
$this->files = $files;
parent::__construct();
}
protected function configure()
{
$this->setName('init')
->setDescription('Scaffold a new Jigsaw project.')
->addArgument(
'name',
InputArgument::OPTIONAL,
'Where should we initialize this project?'
);
}
protected function fire()
{
if ($base = $this->input->getArgument('name')) {
$this->base = getcwd() . '/' . $base;
$this->createBaseDirectory();
}
$this->createSourceFolder();
$this->createBaseConfig();
$this->info('Site initialized successfully!');
}
private function createBaseDirectory()
{
if (! $this->files->isDirectory($this->base)) {
$this->files->makeDirectory($this->base);
}
}
private function createSourceFolder()
{
$this->files->makeDirectory($this->base . '/source');
}
private function createBaseConfig()
{
$this->files->put($this->base . '/config.php', <<<EOT
<?php
return [
'production' => false,
];
EOT
);
}
}
| <?php namespace Jigsaw\Jigsaw\Console;
use Illuminate\Filesystem\Filesystem;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
class InitCommand extends Command
{
private $files;
private $base;
public function __construct(Filesystem $files)
{
$this->files = $files;
parent::__construct();
}
protected function configure()
{
$this->setName('init')
->setDescription('Scaffold a new Jigsaw project.')
->addArgument(
'name',
InputArgument::OPTIONAL,
'Where should we initialize this project?'
);
}
protected function fire()
{
if ($base = $this->input->getArgument('name')) {
$this->base = getcwd() . '/' . $base;
$this->createBaseDirectory();
}
$this->createSourceFolder();
$this->createBaseConfig();
$this->info('Site initialized successfully!');
}
private function createBaseDirectory()
{
if (! $this->files->isDirectory($this->base)) {
$this->files->makeDirectory($this->base);
}
}
private function createSourceFolder()
{
$this->files->makeDirectory($this->base . '/source');
}
private function createBaseConfig()
{
$this->files->put($this->base . '/config.php', <<<EOT
<?php
return [
'production' = false,
];
EOT
);
}
}
|
Replace one last place where aioes was used | import elasticsearch
import os.path
from datetime import datetime
from .utils import read_json_file
from .settings import ELASTICSEARCH_ALIAS
def create_new_index(elastic):
print("Creating new index...")
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
index_name = generate_index_name()
elastic.indices.create(index_name, index_configuration)
return index_name
def switch_alias_to_index(elastic, alias_name, index_name):
print("Switching alias '%s' to index '%s'..." % (alias_name, index_name))
try:
existing_aliases = elastic.indices.get_alias(name=alias_name)
except elasticsearch.NotFoundError:
existing_aliases = []
actions = []
for existing_index_name in existing_aliases:
actions.append({
'remove': {
'index': existing_index_name,
'alias': alias_name,
}
})
actions.append({
'add': {
'index': index_name,
'alias': alias_name
}
})
elastic.indices.update_aliases({'actions': actions})
def generate_index_name():
return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
| import aioes
import os.path
from datetime import datetime
from .utils import read_json_file
from .settings import ELASTICSEARCH_ALIAS
def create_new_index(elastic):
print("Creating new index...")
module_path = os.path.dirname(__file__)
config_filename = os.path.join(module_path, 'configuration', 'index.json')
index_configuration = read_json_file(config_filename)
index_name = generate_index_name()
elastic.indices.create(index_name, index_configuration)
return index_name
def switch_alias_to_index(elastic, alias_name, index_name):
print("Switching alias '%s' to index '%s'..." % (alias_name, index_name))
try:
existing_aliases = elastic.indices.get_alias(name=alias_name)
except aioes.NotFoundError:
existing_aliases = []
actions = []
for existing_index_name in existing_aliases:
actions.append({
'remove': {
'index': existing_index_name,
'alias': alias_name,
}
})
actions.append({
'add': {
'index': index_name,
'alias': alias_name
}
})
elastic.indices.update_aliases({'actions': actions})
def generate_index_name():
return '{}-{}'.format(ELASTICSEARCH_ALIAS, int(datetime.now().timestamp()))
|
Make it so library doesn't spit out error, when trying to display 0 | <?php
namespace ByteUnits;
class PowerScale
{
private $base;
private $scale;
private $precision;
public function __construct($base, $scale, $precision)
{
$this->base = $base;
$this->scale = $scale;
$this->precision = $precision;
}
public function scaleToUnit($quantity, $unit)
{
if ($quantity === "0") return "0";
return bcdiv(
$quantity,
bcpow($this->base, $this->scale[$unit], $this->precision),
$this->precision
);
}
public function scaleFromUnit($quantity, $unit)
{
return $quantity * bcpow(
$this->base,
$this->scale[$unit],
$this->precision
);
}
public function isKnownUnit($unitAsString)
{
return preg_match(
'/^(?:' . implode('|', array_keys($this->scale)) . ')$/i',
trim($unitAsString)
);
}
public function normalizeNameOfUnit($unitAsString)
{
foreach ($this->scale as $unit => $_) {
if (strtolower($unit) === strtolower($unitAsString)) {
return $unit;
}
}
}
public function normalUnitFor($quantity)
{
foreach ($this->scale as $unit => $_) {
$scaled = $this->scaleToUnit($quantity, $unit);
if (bccomp($scaled, 1) >= 0) {
return $unit;
}
}
}
public function isBaseUnit($unit)
{
return (!isset($this->scale[$unit]) || $this->scale[$unit] === 0);
}
}
| <?php
namespace ByteUnits;
class PowerScale
{
private $base;
private $scale;
private $precision;
public function __construct($base, $scale, $precision)
{
$this->base = $base;
$this->scale = $scale;
$this->precision = $precision;
}
public function scaleToUnit($quantity, $unit)
{
return bcdiv(
$quantity,
bcpow($this->base, $this->scale[$unit], $this->precision),
$this->precision
);
}
public function scaleFromUnit($quantity, $unit)
{
return $quantity * bcpow(
$this->base,
$this->scale[$unit],
$this->precision
);
}
public function isKnownUnit($unitAsString)
{
return preg_match(
'/^(?:' . implode('|', array_keys($this->scale)) . ')$/i',
trim($unitAsString)
);
}
public function normalizeNameOfUnit($unitAsString)
{
foreach ($this->scale as $unit => $_) {
if (strtolower($unit) === strtolower($unitAsString)) {
return $unit;
}
}
}
public function normalUnitFor($quantity)
{
foreach ($this->scale as $unit => $_) {
$scaled = $this->scaleToUnit($quantity, $unit);
if (bccomp($scaled, 1) >= 0) {
return $unit;
}
}
}
public function isBaseUnit($unit)
{
return $this->scale[$unit] === 0;
}
}
|
Simplify definition of jscs task | module.exports = function( grunt ) {
"use strict";
grunt.initConfig({
bump: {
options: {
files: [ "package.json" ],
// Commit
commit: true,
commitMessage: "Release v%VERSION%",
commitFiles: [ "package.json" ],
// Tag
createTag: true,
tagName: "%VERSION%",
tagMessage: "Version %VERSION%",
// Push
push: true,
pushTo: "origin"
}
},
jshint: {
options: {
jshintrc: ".jshintrc"
},
all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ]
},
jscs: {
src: "<%= jshint.all %>"
},
nodeunit: {
test: "test/test.js"
}
});
// Load grunt tasks from NPM packages
require( "load-grunt-tasks" )( grunt );
grunt.loadTasks( "tasks" );
grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] );
};
| module.exports = function( grunt ) {
"use strict";
grunt.initConfig({
bump: {
options: {
files: [ "package.json" ],
// Commit
commit: true,
commitMessage: "Release v%VERSION%",
commitFiles: [ "package.json" ],
// Tag
createTag: true,
tagName: "%VERSION%",
tagMessage: "Version %VERSION%",
// Push
push: true,
pushTo: "origin"
}
},
jshint: {
options: {
jshintrc: ".jshintrc"
},
all: [ "Gruntfile.js", "tasks/*.js", "test/*.js" ]
},
jscs: {
all: {
files: {
src: "<%= jshint.all %>"
},
options: {
junit: "jscs-output.xml"
}
}
},
nodeunit: {
test: "test/test.js"
}
});
// Load grunt tasks from NPM packages
require( "load-grunt-tasks" )( grunt );
grunt.loadTasks( "tasks" );
grunt.registerTask( "default", [ "jshint", "jscs", "nodeunit" ] );
};
|
Add flushing for console logging | package io.airlift.log;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import static java.nio.charset.StandardCharsets.UTF_8;
final class OutputStreamHandler
extends Handler
{
private final StaticFormatter formatter = new StaticFormatter();
private final AtomicBoolean reported = new AtomicBoolean();
private final Writer writer;
public OutputStreamHandler(OutputStream out)
{
writer = new OutputStreamWriter(out, UTF_8);
}
@Override
public void publish(LogRecord record)
{
if (!isLoggable(record)) {
return;
}
try {
writer.write(formatter.format(record));
writer.flush();
}
catch (Exception e) {
// try to report the first error
if (!reported.getAndSet(true)) {
PrintWriter error = new PrintWriter(writer);
error.print("LOGGING FAILED: ");
e.printStackTrace(error);
error.flush();
}
}
}
@Override
public void flush() {}
@Override
public void close() {}
}
| package io.airlift.log;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.logging.ErrorManager.CLOSE_FAILURE;
import static java.util.logging.ErrorManager.FLUSH_FAILURE;
import static java.util.logging.ErrorManager.FORMAT_FAILURE;
import static java.util.logging.ErrorManager.WRITE_FAILURE;
final class OutputStreamHandler
extends Handler
{
private final Writer writer;
public OutputStreamHandler(OutputStream out)
{
writer = new OutputStreamWriter(out, UTF_8);
setFormatter(new StaticFormatter());
}
@Override
public void publish(LogRecord record)
{
if (!isLoggable(record)) {
return;
}
String message;
try {
message = getFormatter().format(record);
}
catch (Exception e) {
reportError(null, e, FORMAT_FAILURE);
return;
}
try {
writer.write(message);
}
catch (Exception e) {
reportError(null, e, WRITE_FAILURE);
}
}
@Override
public void flush()
{
try {
writer.flush();
}
catch (Exception e) {
reportError(null, e, FLUSH_FAILURE);
}
}
@Override
public void close()
{
try {
writer.flush();
}
catch (Exception e) {
reportError(null, e, CLOSE_FAILURE);
}
}
}
|
Fix for erroneous service definition | <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
return array(
'factories' => array(
'BedRest.Dispatcher' => 'BedRest\Framework\Zend2\Service\DispatcherFactory',
'BedRest.ResourceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory',
'BedRest.ServiceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory',
'BedRest.ContentNegotiator' => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory',
'BedRest.ContentNegotiationStrategy' => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory',
'BedRest.ExceptionStrategy' => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory',
'BedRest.Request' => 'BedRest\Framework\Zend2\Service\RequestFactory'
)
);
| <?php
/*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
return array(
'factories' => array(
'BedRest.Dispatcher' => 'BedRest\Framework\Zend2\Service\DispatcherFactory',
'BedRest.ResourceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ResourceMetadataFactoryFactory',
'BedRest.ServiceMetadataFactory' => 'BedRest\Framework\Zend2\Service\ServiceMetadataFactoryFactory',
'BedRest.ContentNegotiator' => 'BedRest\Framework\Zend2\Service\ContentNegotiatorFactory',
'BedRest.ContentNegotiationStrategy' => 'BedRest\Framework\Zend2\View\Service\ContentNegotiationStrategyFactory',
'BedRest.ExceptionStrategy' => 'BedRest\Framework\Zend2\Mvc\Service\ExceptionStrategyFactory',
'BedRest.Request' => 'BedRest\Framework\Zend2\Service\Request'
)
);
|
Make default QueryFactory return data (fixes test) | from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:
self.tags.add(*extracted)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda x: "user{}".format(x))
email = factory.Sequence(lambda x: "user{}@example.com".format(x))
password = factory.PostGenerationMethodCall('set_password', "password")
class DbFactory(TagsFactory):
class Meta:
model = Db
exclude = ('DB',)
DB = settings.DATABASES['default']
name_short = "default"
name_long = "default"
type = "MySQL"
host = factory.LazyAttribute(lambda a: a.DB['HOST'])
db = factory.LazyAttribute(lambda a: a.DB['NAME'])
port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306")
username = factory.LazyAttribute(lambda a: a.DB['USER'])
password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD'])
class QueryFactory(TagsFactory):
class Meta:
model = Query
title = "title"
description = "description"
db = factory.SubFactory(DbFactory)
owner = factory.SubFactory(UserFactory)
graph_extra = "{}"
query_text = "select app, name from django_migrations"
| from django.conf import settings
from django.contrib.auth.models import User
import factory
from website.models import Db, Query
class TagsFactory(factory.DjangoModelFactory):
class Meta:
abstract = True
@factory.post_generation
def tags(self, create, extracted):
if create and extracted:
self.tags.add(*extracted)
class UserFactory(factory.DjangoModelFactory):
class Meta:
model = User
username = factory.Sequence(lambda x: "user{}".format(x))
email = factory.Sequence(lambda x: "user{}@example.com".format(x))
password = factory.PostGenerationMethodCall('set_password', "password")
class DbFactory(TagsFactory):
class Meta:
model = Db
exclude = ('DB',)
DB = settings.DATABASES['default']
name_short = "default"
name_long = "default"
type = "MySQL"
host = factory.LazyAttribute(lambda a: a.DB['HOST'])
db = factory.LazyAttribute(lambda a: a.DB['NAME'])
port = factory.LazyAttribute(lambda a: a.DB['PORT'] or "3306")
username = factory.LazyAttribute(lambda a: a.DB['USER'])
password_encrypted = factory.LazyAttribute(lambda a: a.DB['PASSWORD'])
class QueryFactory(TagsFactory):
class Meta:
model = Query
title = "title"
description = "description"
db = factory.SubFactory(DbFactory)
owner = factory.SubFactory(UserFactory)
graph_extra = "{}"
query_text = "select id, username from auth_user"
|
Fix issue observed in jenkins errors (missing comma) | /* global UTILS */
'use strict';
angular.module('alienUiApp').factory('appEnvMngrService', ['applicationEnvironmentServices',
function(applicationEnvironmentServices) {
return {
init: function(applicationId) {
if(this.applicationId !== null) {
this.close();
}
this.applicationId = applicationId;
this.update();
},
update: function() {
var instance = this;
return applicationEnvironmentServices.getAllEnvironments(this.applicationId).then(function(result) {
instance.environments = result.data.data;
instance.updateRegistrations();
return instance;
});
},
updateRegistrations: function() {
if(UTILS.isUndefinedOrNull(this.eventRegistrations)) {
this.eventRegistrations = {};
}
},
/**
* Register for websocket updates on an environment status.
*/
register: function(environment) {
var registration = environmentEventServicesFactory(application.id, environment, callback);
this.eventRegistrations[environment.id] = registration;
var isEnvDeployer = alienAuthService.hasResourceRole(environment, 'DEPLOYMENT_MANAGER');
if(isManager || isEnvDeployer) {
this.deployEnvironments.push(environment);
}
isDeployer = isDeployer || isEnvDeployer;
},
close: function() {
for(var i=0; i < this.eventRegistrations.length; i++) {
this.eventRegistrations[i].close();
}
this.eventRegistrations = null;
this.environments = null;
this.deployEnvironments = null;
}
};
}]);
| /* global UTILS */
'use strict';
angular.module('alienUiApp').factory('appEnvMngrService', ['applicationEnvironmentServices',
function(applicationEnvironmentServices) {
return {
init: function(applicationId) {
if(this.applicationId !== null) {
this.close();
}
this.applicationId = applicationId;
this.update();
},
update: function() {
var instance = this;
return applicationEnvironmentServices.getAllEnvironments(this.applicationId).then(function(result) {
instance.environments = result.data.data;
instance.updateRegistrations();
return instance;
});
},
updateRegistrations: function() {
if(UTILS.isUndefinedOrNull(this.eventRegistrations)) {
this.eventRegistrations = {};
}
},
/**
* Register for websocket updates on an environment status.
*/
register: function(environment) {
var registration = environmentEventServicesFactory(application.id, environment, callback);
this.eventRegistrations[environment.id] = registration;
var isEnvDeployer = alienAuthService.hasResourceRole(environment, 'DEPLOYMENT_MANAGER');
if(isManager || isEnvDeployer) {
this.deployEnvironments.push(environment);
}
isDeployer = isDeployer || isEnvDeployer;
}
close: function() {
for(var i=0; i < this.eventRegistrations.length; i++) {
this.eventRegistrations[i].close();
}
this.eventRegistrations = null;
this.environments = null;
this.deployEnvironments = null;
}
};
}]);
|
FIx Document provider not refetching | import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import isEmpty from 'lodash/isEmpty';
export const fetchCountriesDocumentsInit = createAction(
'fetchCountriesDocumentsInit'
);
export const fetchCountriesDocumentsReady = createAction(
'fetchCountriesDocumentsReady'
);
export const fetchCountriesDocumentsFail = createAction(
'fetchCountriesDocumentsFail'
);
export const fetchCountriesDocuments = createThunkAction(
'fetchCountriesDocuments',
location => (dispatch, state) => {
const { countriesDocuments } = state();
if (
!countriesDocuments.loading &&
(!location ||
!countriesDocuments.data || isEmpty(countriesDocuments.data[location]))
) {
const url = `/api/v1/ndcs/countries_documents${
location ? `?location=${location}` : ''
}`;
dispatch(fetchCountriesDocumentsInit());
fetch(url)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
dispatch(fetchCountriesDocumentsReady(data.data));
})
.catch(error => {
console.warn(error);
dispatch(fetchCountriesDocumentsFail());
});
}
}
);
export default {
fetchCountriesDocuments,
fetchCountriesDocumentsInit,
fetchCountriesDocumentsReady,
fetchCountriesDocumentsFail
};
| import { createAction } from 'redux-actions';
import { createThunkAction } from 'utils/redux';
import isEmpty from 'lodash/isEmpty';
export const fetchCountriesDocumentsInit = createAction(
'fetchCountriesDocumentsInit'
);
export const fetchCountriesDocumentsReady = createAction(
'fetchCountriesDocumentsReady'
);
export const fetchCountriesDocumentsFail = createAction(
'fetchCountriesDocumentsFail'
);
export const fetchCountriesDocuments = createThunkAction(
'fetchCountriesDocuments',
location => (dispatch, state) => {
const { countriesDocuments } = state();
if (
!countriesDocuments.loading &&
(isEmpty(countriesDocuments.data) ||
(!!location && isEmpty(countriesDocuments.data[location])))
) {
const url = `/api/v1/ndcs/countries_documents${
location ? `?location=${location}` : ''
}`;
dispatch(fetchCountriesDocumentsInit());
fetch(url)
.then(response => {
if (response.ok) return response.json();
throw Error(response.statusText);
})
.then(data => {
dispatch(fetchCountriesDocumentsReady(data.data));
})
.catch(error => {
console.warn(error);
dispatch(fetchCountriesDocumentsFail());
});
}
}
);
export default {
fetchCountriesDocuments,
fetchCountriesDocumentsInit,
fetchCountriesDocumentsReady,
fetchCountriesDocumentsFail
};
|
Add error logging level methods | <?php namespace LaravelDecouplr\Log;
use Decouplr\Decouplr;
use Illuminate\Log\Writer;
abstract class LaravelLogDecouplr extends Decouplr {
public function __construct(Writer $writer){
$this->decoupled = $writer;
}
public function useFiles()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function useDailyFiles()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function useErrorLog()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function listen()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function getMonolog()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function getEventDispatcher()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function setEventDispatcher()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function write()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function debug()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function notice()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function warning()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function error()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function critical()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function alert()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
} | <?php namespace LaravelDecouplr\Log;
use Decouplr\Decouplr;
use Illuminate\Log\Writer;
abstract class LaravelLogDecouplr extends Decouplr {
public function __construct(Writer $writer){
$this->decoupled = $writer;
}
public function useFiles()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function useDailyFiles()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function useErrorLog()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function listen()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function getMonolog()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function getEventDispatcher()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function setEventDispatcher()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
public function write()
{
return $this->delegate(__FUNCTION__, func_get_args());
}
} |
Make the weather page use a named controller.
We have to use named controllers rather than inline controllers because
we want to be able to indicate to the client which controller to use to
render the page. We can send the client a string to look up, but we can't
reliably serialize the controller function and transmit it. |
var app = angular.module('simpleapp', ['ng', 'ngRoute']);
app.controller(
'simpleController',
function ($scope, $location, $http) {
$scope.currentUrl = $location.absUrl();
}
);
app.controller(
'weatherController',
function (weatherData, $scope) {
$scope.weather = weatherData;
}
);
app.config(
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when(
'/weather',
{
template: '<h2>Weather for {{weather.name}}</h2><pre>{{weather | json}}</pre>',
resolve: {
weatherData: function ($http) {
return $http.get(
'http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,%20CA,%20US'
).then(function (resp) { return resp.data; });
}
},
controller: 'weatherController'
}
);
$routeProvider.otherwise(
{
template: '<a href="/weather">Weather</a>'
}
);
}
);
|
var app = angular.module('simpleapp', ['ng', 'ngRoute']);
app.controller(
'simpleController',
function ($scope, $location, $http) {
$scope.currentUrl = $location.absUrl();
}
);
app.config(
function ($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when(
'/weather',
{
template: '<h2>Weather for {{weather.name}}</h2><pre>{{weather | json}}</pre>',
resolve: {
weatherData: function ($http) {
return $http.get(
'http://api.openweathermap.org/data/2.5/weather?q=San%20Francisco,%20CA,%20US'
).then(function (resp) { return resp.data; });
}
},
controller: function (weatherData, $scope) {
$scope.weather = weatherData;
}
}
);
$routeProvider.otherwise(
{
template: '<a href="/weather">Weather</a>'
}
);
}
);
|
Remove unused and commented code | #!/usr/bin/env node
var S=require('surku');
var fs=require('fs');
var surkuConfig={
maxMutations:20,
minMutations:1,
chunkSize:3000
};
var surku=new S(surkuConfig);
function init(config){
surkuConfig.tempDirectory=config.tempDirectory;
}
function generateTestCase(getSample,callback){
var prefix=new Date().getTime()+Math.random().toString().split('.')[1];
var sampleFile=getSample(1)[0];
if(sampleFile){
var fileName=surkuConfig.tempDirectory+'/samples/'+prefix;
var fileContent=fs.readFileSync(sampleFile);
var chunkSize=Math.ceil(fileContent.length/100);
if(chunkSize>3000){
surku.config.chunkSize=3000;
}else if(chunkSize<500){
surku.config.chunkSize=500;
}
else{
surku.config.chunkSize=chunkSize;
}
var testCase=surku.generateTestCase(fileContent);
fs.writeFile(fileName,testCase,function(){
callback({type:"file",data:fileName});
});
}
else{
callback();
}
}
module.exports={
init,
generateTestCase
};
| #!/usr/bin/env node
var S=require('surku');
var fs=require('fs');
var path=require('path');
var surkuConfig={
maxMutations:20,
minMutations:1,
chunkSize:3000
};
var surku=new S(surkuConfig);
function init(config){
surkuConfig.tempDirectory=config.tempDirectory;
}
function generateTestCase(getSample,callback){
//console.log('surku')
var prefix=new Date().getTime()+Math.random().toString().split('.')[1];
var sampleFile=getSample(1)[0];
if(sampleFile){
var fileName=surkuConfig.tempDirectory+'/samples/'+prefix;
var fileContent=fs.readFileSync(sampleFile);
var chunkSize=Math.ceil(fileContent.length/100);
if(chunkSize>3000){
surku.config.chunkSize=3000;
}else if(chunkSize<500){
surku.config.chunkSize=500;
}
else{
surku.config.chunkSize=chunkSize;
}
var testCase=surku.generateTestCase(fileContent);
fs.writeFile(fileName,testCase,function(){
//console.log(fileName)
//console.log("New length: "+testCase.length+ " Original length: "+fileContent.length)
callback({type:"file",data:fileName});
});
}
else{
callback();
}
}
module.exports={
init,
generateTestCase
};
|
Update mtgox api endpoint to use SSL | """Bitccoin ticker module for ppbot.
@package ppbot
Displays the current bitcoin pricing from mtgox
@syntax btc
"""
import requests
import string
import json
from xml.dom.minidom import parseString
from modules import *
class Bitcoin(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "https://data.mtgox.com/api/1/BTCUSD/ticker"
def _register_events(self):
"""Register module commands."""
self.add_command('btc')
def btc(self, event):
"""Action to react/respond to user calls."""
data = {}
try:
result = self.lookup()['return']
data['high'] = result['high']['display_short']
data['last'] = result['last_local']['display_short']
data['low'] = result['low']['display_short']
data['volume'] = result['vol']['display_short']
message = "Last: %(last)s - High/Low: (%(high)s/%(low)s) - Volume: %(volume)s" % (data)
self.msg(event['target'], message)
except:
pass
def lookup(self):
"""Connects to google's secret finance API and parses the receiving json for the stock info."""
# make the parser, and send the xml to be parsed
result = requests.get(self.url)
return result.json()
| """Bitccoin ticker module for ppbot.
@package ppbot
Displays the current bitcoin pricing from mtgox
@syntax btc
"""
import requests
import string
import json
from xml.dom.minidom import parseString
from modules import *
class Bitcoin(Module):
def __init__(self, *args, **kwargs):
"""Constructor"""
Module.__init__(self, kwargs=kwargs)
self.url = "http://data.mtgox.com/api/1/BTCUSD/ticker"
def _register_events(self):
"""Register module commands."""
self.add_command('btc')
def btc(self, event):
"""Action to react/respond to user calls."""
data = {}
try:
result = self.lookup()['return']
data['high'] = result['high']['display_short']
data['last'] = result['last_local']['display_short']
data['low'] = result['low']['display_short']
data['volume'] = result['vol']['display_short']
message = "Last: %(last)s - High/Low: (%(high)s/%(low)s) - Volume: %(volume)s" % (data)
self.msg(event['target'], message)
except:
pass
def lookup(self):
"""Connects to google's secret finance API and parses the receiving json for the stock info."""
# make the parser, and send the xml to be parsed
result = requests.get(self.url)
return result.json()
|
Feature: Remove deprecated reference + always cleanup the <style> block | <?php
namespace Fedeisas\LaravelMailCssInliner;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
class CssInlinerPlugin implements \Swift_Events_SendListener
{
/**
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(\Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$converter = new CssToInlineStyles();
$converter->setUseInlineStylesBlock();
$converter->setStripOriginalStyleTags();
$converter->setCleanup();
if ($message->getContentType() === 'text/html' ||
($message->getContentType() === 'multipart/alternative' && $message->getBody())
) {
$converter->setHTML($message->getBody());
$message->setBody($converter->convert());
}
foreach ($message->getChildren() as $part) {
if (strpos($part->getContentType(), 'text/html') === 0) {
$converter->setHTML($part->getBody());
$part->setBody($converter->convert());
}
}
}
/**
* Do nothing
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(\Swift_Events_SendEvent $evt)
{
// Do Nothing
}
}
| <?php
namespace Fedeisas\LaravelMailCssInliner;
use TijsVerkoyen\CssToInlineStyles\CssToInlineStyles;
class CssInlinerPlugin implements \Swift_Events_SendListener
{
/**
* @param Swift_Events_SendEvent $evt
*/
public function beforeSendPerformed(\Swift_Events_SendEvent $evt)
{
$message = $evt->getMessage();
$converter = new CssToInlineStyles();
$converter->setEncoding($message->getCharset());
$converter->setUseInlineStylesBlock();
$converter->setCleanup();
if ($message->getContentType() === 'text/html' ||
($message->getContentType() === 'multipart/alternative' && $message->getBody())
) {
$converter->setHTML($message->getBody());
$message->setBody($converter->convert());
}
foreach ($message->getChildren() as $part) {
if (strpos($part->getContentType(), 'text/html') === 0) {
$converter->setHTML($part->getBody());
$part->setBody($converter->convert());
}
}
}
/**
* Do nothing
*
* @param Swift_Events_SendEvent $evt
*/
public function sendPerformed(\Swift_Events_SendEvent $evt)
{
// Do Nothing
}
}
|
Bump version to see if pip installs it | import multiprocessing
from setuptools import setup, find_packages
setup(
name='sow-generator',
version='0.1.1',
description='Create a scope of work from templates and version controlled documentation.',
long_description = open('README.rst', 'r').read() + open('CHANGELOG.rst', 'r').read() + open('AUTHORS.rst', 'r').read(),
author='Hedley Roos',
author_email='[email protected]',
license='BSD',
url='http://github.com/praekelt/sow-generator',
packages = find_packages(),
install_requires = [
'Django<1.7',
'South',
'celery',
'django-celery',
'raven',
'PyYAML',
'requests',
'github3.py',
'pyandoc',
'django-object-tools',
'django-adminplus'
],
include_package_data=True,
tests_require=[
'django-setuptest>=0.1.4',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
| import multiprocessing
from setuptools import setup, find_packages
setup(
name='sow-generator',
version='0.1',
description='Create a scope of work from templates and version controlled documentation.',
long_description = open('README.rst', 'r').read() + open('CHANGELOG.rst', 'r').read() + open('AUTHORS.rst', 'r').read(),
author='Hedley Roos',
author_email='[email protected]',
license='BSD',
url='http://github.com/praekelt/sow-generator',
packages = find_packages(),
install_requires = [
'Django<1.7',
'South',
'celery',
'django-celery',
'raven',
'PyYAML',
'requests',
'github3.py',
'pyandoc',
'django-object-tools',
'django-adminplus'
],
include_package_data=True,
tests_require=[
'django-setuptest>=0.1.4',
],
test_suite="setuptest.setuptest.SetupTestSuite",
classifiers=[
"Programming Language :: Python",
"License :: OSI Approved :: BSD License",
"Development Status :: 4 - Beta",
"Operating System :: OS Independent",
"Framework :: Django",
"Intended Audience :: Developers",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
],
zip_safe=False,
)
|
Fix gulp task. Bundle should start after Transform is done. | var plumber = require("gulp-plumber");
var webpack = require("gulp-webpack");
var cssmin = require("gulp-minify-css");
var csscon = require("gulp-concat-css");
var jshint = require("gulp-jshint");
var watch = require("gulp-watch");
var react = require("gulp-react");
var gulp = require("gulp");
gulp.task("lint", function () {
return gulp.src(["server.js", "client.js", "test.js", "./build/*.js"]).
pipe(jshint()).
pipe(jshint.reporter("default"));
});
gulp.task("bundle:css", function () {
return gulp.src("stylesheet/*.css").
pipe(csscon("blog.0.1.0.min.css")).
pipe(cssmin()).
pipe(gulp.dest("static"));
});
gulp.task("transform", function () {
return gulp.src("component/*.jsx").
pipe(react()).
pipe(jshint()).
pipe(jshint.reporter("default", { verbose: true })).
pipe(gulp.dest("build"));
});
gulp.task("bundle:js", ["transform"], function () {
return gulp.src("./client.js").
pipe(webpack(require("./webpack.config.js"))).
pipe(gulp.dest("static"));
});
gulp.task("default", function () {
gulp.watch("stylesheet/*.css", ["bundle:css"]);
gulp.watch("component/*.jsx", ["bundle:js"]);
return;
});
| var plumber = require("gulp-plumber");
var webpack = require("gulp-webpack");
var cssmin = require("gulp-minify-css");
var csscon = require("gulp-concat-css");
var jshint = require("gulp-jshint");
var watch = require("gulp-watch");
var react = require("gulp-react");
var gulp = require("gulp");
gulp.task("css", function () {
return gulp.src("stylesheet/*.css").
pipe(csscon("blog.0.1.0.min.css")).
pipe(cssmin()).
pipe(gulp.dest("static"));
});
gulp.task("transform", function () {
return gulp.src("component/*.jsx").
pipe(react()).
pipe(jshint()).
pipe(jshint.reporter("default", { verbose: true })).
pipe(gulp.dest("build"));
});
gulp.task("bundle", function () {
return gulp.src("./client.js").
pipe(webpack(require("./webpack.config.js"))).
pipe(gulp.dest("static"));
});
gulp.task("default", function () {
gulp.watch("stylesheet/*.css", ["css"]);
gulp.watch("component/*.jsx", ["transform", "bundle"]);
return;
});
gulp.task("lint", function () {
return gulp.src(["server.js", "client.js", "test.js", "./build/*.js"]).
pipe(jshint()).
pipe(jshint.reporter("default"));
});
|
Use 'fields' instead of 'kwargs' to document intent. | # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **fields):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(fields)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
| # -*- coding: utf-8 -*-
"""
The Renderer class provides the infrastructure for generating template-based
code. It's used by the .grammars module for parser generation.
"""
from __future__ import print_function, division, absolute_import, unicode_literals
import itertools
from .util import trim
def render(item, **fields):
""" Render the given item
"""
if item is None:
return ''
elif isinstance(item, Renderer):
return item.render(**fields)
elif isinstance(item, list):
return ''.join(render(e) for e in item)
else:
return str(item)
class Renderer(object):
template = ''
_counter = itertools.count()
def __init__(self, template=None):
if template is not None:
self.template = template
def counter(self):
return next(self._counter)
def render_fields(self, fields):
pass
def render(self, template=None, **kwargs):
fields = ({k:v for k, v in vars(self).items() if not k.startswith('_')})
override = self.render_fields(fields)
if template is None:
if override is not None:
template = override
else:
template = self.template
fields.update(kwargs)
fields = {k:render(v) for k, v in fields.items()}
try:
return trim(template).format(**fields)
except KeyError as e:
raise KeyError(str(e), type(self))
|
Set defalut focus on first input element in search panel | angular.module('openspecimen')
.directive('osRightDrawer', function(osRightDrawerSvc) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.addClass('os-right-drawer');
element.removeAttr('os-right-drawer');
var header = element.find('div.os-head');
if (header) {
var divider = angular.element('<div/>')
.addClass('os-divider');
header.after(divider);
}
osRightDrawerSvc.setDrawer(element);
}
};
})
.directive('osRightDrawerToggle', function(osRightDrawerSvc) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
osRightDrawerSvc.toggle();
});
}
};
})
.factory('osRightDrawerSvc', function() {
var drawerEl = undefined;
return {
setDrawer: function(drawer) {
drawerEl = drawer;
},
toggle: function() {
drawerEl.toggleClass('active');
var cardsDiv = drawerEl.parent().find("div.os-cards");
if (drawerEl.hasClass('active')) {
var firstInput = drawerEl.find("input")[0];
if (firstInput) {
firstInput.focus();
}
cardsDiv.css("width", "75%");
} else {
cardsDiv.css("width", "100%");
}
}
}
});
| angular.module('openspecimen')
.directive('osRightDrawer', function(osRightDrawerSvc) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.addClass('os-right-drawer');
element.removeAttr('os-right-drawer');
var header = element.find('div.os-head');
if (header) {
var divider = angular.element('<div/>')
.addClass('os-divider');
header.after(divider);
}
osRightDrawerSvc.setDrawer(element);
}
};
})
.directive('osRightDrawerToggle', function(osRightDrawerSvc) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
element.on('click', function() {
osRightDrawerSvc.toggle();
});
}
};
})
.factory('osRightDrawerSvc', function() {
var drawerEl = undefined;
return {
setDrawer: function(drawer) {
drawerEl = drawer;
},
toggle: function() {
drawerEl.toggleClass('active');
var cardsDiv = drawerEl.parent().find("div.os-cards");
if (drawerEl.hasClass('active')) {
cardsDiv.css("width", "75%");
} else {
cardsDiv.css("width", "100%");
}
}
}
});
|
Fix Generator verification in loop() | <?php
declare(strict_types=1);
namespace Funktions;
use Exception;
use Generator;
/**
* Return a value based on a test
*
* @param boolean $test
* @param callable $truthy
* @param callable $falsy
* @return mixed
*/
function condition(bool $test, callable $truthy, callable $falsy)
{
if ($test) {
return call_user_func($truthy);
}
return call_user_func($falsy);
}
/**
* Loop over items and pass them to a generator
*
* @param iterable $iterable
* @param callable $callable
* @return array
*/
function loop(iterable $iterable, callable $callable): array
{
$array = [];
foreach ($iterable as $item) {
$generator = call_user_func($callable, $item);
if ($generator instanceof Generator === false) {
throw new Exception('Callable must be a generator');
}
$array = array_merge($array, iterator_to_array($generator));
}
return $array;
}
/**
* Loop in a generator until a returned condition
*
* @param callable $callable
* @return array
*/
function loop_until(callable $callable): array
{
$array = [];
do {
$generator = call_user_func($callable);
if ($generator instanceof Generator === false) {
throw Exception('Callable must be a generator');
}
$array = array_merge($array, iterator_to_array($generator));
}
while(!$generator->getReturn());
return $array;
}
| <?php
declare(strict_types=1);
namespace Funktions;
use Exception;
/**
* Return a value based on a test
*
* @param boolean $test
* @param callable $truthy
* @param callable $falsy
* @return mixed
*/
function condition(bool $test, callable $truthy, callable $falsy)
{
if ($test) {
return call_user_func($truthy);
}
return call_user_func($falsy);
}
/**
* Loop over items and pass them to a generator
*
* @param iterable $iterable
* @param callable $callable
* @return array
*/
function loop(iterable $iterable, callable $callable): array
{
$array = [];
foreach ($iterable as $item) {
$generator = call_user_func($callable, $item);
if ($generator instanceof Generator === false) {
throw new Exception('Callable must be a generator');
}
$array = array_merge($array, iterator_to_array($generator));
}
return $array;
}
/**
* Loop in a generator until a returned condition
*
* @param callable $callable
* @return array
*/
function loop_until(callable $callable): array
{
$array = [];
do {
$generator = call_user_func($callable);
if ($generator instanceof Generator === false) {
throw Exception('Callable must be a generator');
}
$array = array_merge($array, iterator_to_array($generator));
}
while(!$generator->getReturn());
return $array;
}
|
Check in built Stateful mixin | define(
["ember","./machine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var Mixin = __dependency1__.Mixin;
var computed = __dependency1__.computed;
var Machine = __dependency2__["default"] || __dependency2__;
__exports__["default"] = Mixin.create({
fsmEvents: null,
fsmStates: null,
fsmInitialState: null,
fsmIsLoading: computed.oneWay('__fsm__.isTransitioning'),
fsmCurrentState: computed.oneWay('__fsm__.currentState'),
init: function() {
var params = {};
var mixin = {};
var fsm;
params.target = this;
params.events = this.get('fsmEvents');
params.states = this.get('fsmStates');
params.initialState = this.get('fsmInitialState');
fsm = Machine.create(params);
this.set('__fsm__', fsm);
fsm.isInStateAccessorProperties.forEach(function(prop) {
mixin[prop] = computed.oneWay('__fsm__.' + prop);
});
this.reopen(mixin);
this._super();
},
sendStateEvent: function() {
var fsm = this.get('__fsm__');
return fsm.send.apply(fsm, arguments);
}
});
}); | define(
["ember","./machine","exports"],
function(__dependency1__, __dependency2__, __exports__) {
"use strict";
var Mixin = __dependency1__.Mixin;
var computed = __dependency1__.computed;
var Machine = __dependency2__["default"] || __dependency2__;
__exports__["default"] = Mixin.create({
fsmEvents: null,
fsmStates: null,
initialState: null,
isLoading: computed.oneWay('__fsm__.isTransitioning'),
currentState: computed.oneWay('__fsm__.currentState'),
init: function() {
var params = {};
var mixin = {};
var fsm;
params.target = this;
params.events = this.get('fsmEvents');
params.states = this.get('fsmStates');
params.initialState = this.get('initialState');
fsm = Machine.create(params);
this.set('__fsm__', fsm);
fsm.isInStateAccessorProperties.forEach(function(prop) {
mixin[prop] = computed.oneWay('__fsm__.' + prop);
});
this.reopen(mixin);
this._super();
},
sendStateEvent: function() {
var fsm = this.get('__fsm__');
return fsm.send.apply(fsm, arguments);
}
});
}); |
Add 'Systems Administration' to the list of project classifiers | from setuptools import setup, find_packages
from suponoff import __version__ as version
if __name__ == '__main__':
with open("README.rst") as f:
long_description = f.read()
setup(
name="suponoff",
version=version,
author="Gambit Research",
author_email="[email protected]",
description="An alternative Supervisor web interface.",
long_description=long_description,
license="BSD",
url="",
zip_safe=False,
include_package_data=True,
packages=find_packages(),
scripts=[
'suponoff-monhelper.py'
],
install_requires=[
"Django >= 1.7", # just because I only tested with Django 1.7...
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
("Topic :: Software Development :: Libraries :: "
"Application Frameworks"),
"Topic :: Software Development :: Libraries :: Python Modules",
"Topic :: System :: Systems Administration",
])
| from setuptools import setup, find_packages
from suponoff import __version__ as version
if __name__ == '__main__':
with open("README.rst") as f:
long_description = f.read()
setup(
name="suponoff",
version=version,
author="Gambit Research",
author_email="[email protected]",
description="An alternative Supervisor web interface.",
long_description=long_description,
license="BSD",
url="",
zip_safe=False,
include_package_data=True,
packages=find_packages(),
scripts=[
'suponoff-monhelper.py'
],
install_requires=[
"Django >= 1.7", # just because I only tested with Django 1.7...
],
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Operating System :: Linux",
"Programming Language :: Python",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.3",
"Topic :: Internet :: WWW/HTTP",
"Topic :: Internet :: WWW/HTTP :: Dynamic Content",
"Topic :: Internet :: WWW/HTTP :: WSGI",
("Topic :: Software Development :: Libraries :: "
"Application Frameworks"),
"Topic :: Software Development :: Libraries :: Python Modules",
])
|
Use try_update_model in sign in handler instead of dict update. | """
"""
from wheezy.core.collections import attrdict
from wheezy.core.comp import u
from wheezy.security import Principal
from wheezy.web.authorization import authorize
from shared.views import APIHandler
from membership.validation import credential_validator
class SignInHandler(APIHandler):
def post(self):
m = attrdict(username=u(''), password=u(''))
if (not self.try_update_model(m) or
not self.validate(m, credential_validator) or
not self.authenticate(m)):
return self.json_errors()
return self.json_response({'username': m.username})
def authenticate(self, credential):
with self.factory('ro') as f:
user = f.membership.authenticate(credential)
if not user:
return False
self.principal = Principal(id=user['id'])
return True
class SignUpHandler(APIHandler):
def post(self):
m = attrdict(email=u(''), username=u(''), password=u(''))
m.update(self.request.form)
if not self.signup(m):
return self.json_errors()
return self.json_response({})
def signup(self, m):
self.error('This feature is not available yet.')
return False
class SignOutHandler(APIHandler):
def get(self):
del self.principal
return self.json_response({})
class UserHandler(APIHandler):
@authorize
def get(self):
return self.json_response({'username': self.principal.id})
| """
"""
from wheezy.core.collections import attrdict
from wheezy.core.comp import u
from wheezy.security import Principal
from wheezy.web.authorization import authorize
from shared.views import APIHandler
from membership.validation import credential_validator
class SignInHandler(APIHandler):
def post(self):
m = attrdict(username=u(''), password=u(''))
m.update(self.request.form)
if (not self.validate(m, credential_validator) or
not self.authenticate(m)):
return self.json_errors()
return self.json_response({'username': m.username})
def authenticate(self, credential):
with self.factory('ro') as f:
user = f.membership.authenticate(credential)
if not user:
return False
self.principal = Principal(id=user['id'])
return True
class SignUpHandler(APIHandler):
def post(self):
m = attrdict(email=u(''), username=u(''), password=u(''))
m.update(self.request.form)
if not self.signup(m):
return self.json_errors()
return self.json_response({})
def signup(self, m):
self.error('This feature is not available yet.')
return False
class SignOutHandler(APIHandler):
def get(self):
del self.principal
return self.json_response({'ok': True})
class UserHandler(APIHandler):
@authorize
def get(self):
return self.json_response({'username': self.principal.id})
|
Implement deleteAll as a variant of delete
Will need to add tests for this entire thing later.
Change-Id: Ib40fe1d4f126923ed1788417f144d0d45fd24e61 | package org.wikimedia.wikipedia.data;
import android.content.ContentProviderClient;
import android.net.Uri;
import android.os.RemoteException;
abstract public class ContentPersister<T> {
private final ContentProviderClient client;
private final PersistanceHelper<T> persistanceHelper;
public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) {
this.client = client;
this.persistanceHelper = persistanceHelper;
}
public void persist(T obj) {
Uri uri = Uri.parse("content://" +
SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) +
"/" + persistanceHelper.getTableName());
try {
client.insert(uri, persistanceHelper.toContentValues(obj));
} catch (RemoteException e) {
// This shouldn't happen
throw new RuntimeException(e);
}
}
public void deleteAll() {
deleteWhere("", new String[] {});
}
public void deleteWhere(String selection, String[] selectionArgs) {
Uri uri = persistanceHelper.getBaseContentURI();
try {
client.delete(uri, selection, selectionArgs);
} catch (RemoteException e) {
// This also shouldn't happen
throw new RuntimeException(e);
}
}
public void cleanup() {
this.client.release();
}
}
| package org.wikimedia.wikipedia.data;
import android.content.ContentProviderClient;
import android.net.Uri;
import android.os.RemoteException;
abstract public class ContentPersister<T> {
private final ContentProviderClient client;
private final PersistanceHelper<T> persistanceHelper;
public ContentPersister(ContentProviderClient client, PersistanceHelper<T> persistanceHelper) {
this.client = client;
this.persistanceHelper = persistanceHelper;
}
public void persist(T obj) {
Uri uri = Uri.parse("content://" +
SQLiteContentProvider.getAuthorityForTable(persistanceHelper.getTableName()) +
"/" + persistanceHelper.getTableName());
try {
client.insert(uri, persistanceHelper.toContentValues(obj));
} catch (RemoteException e) {
// This shouldn't happen
throw new RuntimeException(e);
}
}
public void deleteAll() {
Uri uri = persistanceHelper.getBaseContentURI();
try {
client.delete(uri, "", new String[] {});
} catch (RemoteException e) {
// This also shouldn't happen
throw new RuntimeException(e);
}
}
public void cleanup() {
this.client.release();
}
}
|
Fix duplicates in imported venues | var Event = require('../models/Event.js');
var Venue = require('../models/Venue.js');
exports.sync = function(events) {
events.map(function(evt) {
var eventquery = {
'title': evt.title,
'startAt': evt.startAt
};
Event.findOne(
eventquery,
function (err, doc) {
if (!doc) {
Event.create(evt, function (err, doc) {
if (err) {
console.log("Something went wrong in creating new event");
}
}
);
}
}
);
var venuequery = {
'name': evt.venue.name
};
var venue = {};
venue.name = evt.venue.name;
venue.address = evt.venue.address;
venue.latitude = evt.venue.latitude;
venue.longitude = evt.venue.longitude;
Venue.findOneAndUpdate(
venuequery,
venue,
{'upsert': true},
function(err, doc) {
if (err) {
console.log("Something went wrong in creating new event");
}
}
);
});
};
| var Event = require('../models/Event.js');
var Venue = require('../models/Venue.js');
exports.sync = function(events) {
events.map(function(evt) {
var eventquery = {
'title': evt.title,
'startAt': evt.startAt
};
Event.findOne(
eventquery,
function(err, doc) {
if(!doc){
Event.create(evt , function(err, doc){
if(err){
console.log("Something went wrong in creating new event");
}
}
);}
}
);
var venuequery = {
'name': evt.venue.name
};
Venue.findOne(
venuequery,
function(err, doc) {
if(!doc){
var venue = new Venue();
venue.name = evt.venue.name;
venue.address = evt.venue.address;
venue.latitude = evt.venue.latitude;
venue.longitude = evt.venue.longitude;
venue.save(function(err, doc){
if(err){
console.log("Something went wrong in creating new event");
}
}
);}
}
);
});
};
|
Fix encoding (thanks to Yasushi Masuda) | # -*- coding: utf-8 -*-
#$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
'''
elements=[]
lines=data.splitlines()
for line in lines:
lexer=shlex.shlex(line)
lexer.whitespace+=','
tokens=list(lexer)
command=tokens[0]
if command == 'PageBreak':
if len(tokens)==1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]),int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now
#def depth (node):
# if node.parent==None:
# return 0
# else:
# return 1+depth(node.parent)
| #$HeadURL$
#$LastChangedDate$
#$LastChangedRevision$
import sys
from reportlab.platypus import PageBreak, Spacer
from flowables import *
import shlex
from log import log
def parseRaw (data):
'''Parse and process a simple DSL to handle creation of flowables.
Supported (can add others on request):
* PageBreak
* Spacer width, height
'''
elements=[]
lines=data.splitlines()
for line in lines:
lexer=shlex.shlex(line)
lexer.whitespace+=','
tokens=list(lexer)
command=tokens[0]
if command == 'PageBreak':
if len(tokens)==1:
elements.append(MyPageBreak())
else:
elements.append(MyPageBreak(tokens[1]))
if command == 'Spacer':
elements.append(Spacer(int(tokens[1]),int(tokens[2])))
if command == 'Transition':
elements.append(Transition(*tokens[1:]))
return elements
# Looks like this is not used anywhere now
#def depth (node):
# if node.parent==None:
# return 0
# else:
# return 1+depth(node.parent)
|
Change level and experience to regular integers. | module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
level: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 1
},
experience: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
}
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Quest, {as: 'OwnedQuests', foreignKey: 'OwnerId'});
User.belongsToMany(models.Quest, {through: 'UsersQuests'});
}
},
instanceMethods: {
/**
* Experience formula taken from HabitRPG
* http://habitrpg.wikia.com/wiki/Experience_Points
*/
getExperienceForLevel: function() {
return Math.round((0.25 * Math.pow(this.level, 2) + 10 * this.level + 139.75) / 10) * 10;
},
/**
* Increase experience by `amount` XP.
* Level up if necessary.
*/
increaseExperience: function(amount) {
this.experience += amount;
while (this.experience >= this.getExperienceForLevel()) {
this.experience -= this.getExperienceForLevel();
this.level++;
}
this.save();
}
}
});
return User;
};
| module.exports = function(sequelize, DataTypes) {
var User = sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true
},
password: {
type: DataTypes.STRING,
allowNull: false
},
email: {
type: DataTypes.STRING,
allowNull: false
},
level: {
type: DataTypes.BIGINT,
allowNull: false,
defaultValue: 1
},
experience: {
type: DataTypes.BIGINT,
allowNull: false,
defaultValue: 0
}
}, {
classMethods: {
associate: function(models) {
User.hasMany(models.Quest, {as: 'OwnedQuests', foreignKey: 'OwnerId'});
User.belongsToMany(models.Quest, {through: 'UsersQuests'});
}
},
instanceMethods: {
/**
* Experience formula taken from HabitRPG
* http://habitrpg.wikia.com/wiki/Experience_Points
*/
getExperienceForLevel: function() {
return Math.round((0.25 * Math.pow(this.level, 2) + 10 * this.level + 139.75) / 10) * 10;
},
/**
* Increase experience by `amount` XP.
* Level up if necessary.
*/
increaseExperience: function(amount) {
this.experience += amount;
while (this.experience >= this.getExperienceForLevel()) {
this.experience -= this.getExperienceForLevel();
this.level++;
}
this.save();
}
}
});
return User;
};
|
Put React lifecycle hooks on the prototype | import React from 'react';
import ReactDOM from 'react-dom';
/**
* @param {ReactClass} Target The component that defines `onOutsideEvent` handler.
* @param {String[]} supportedEvents A list of valid DOM event names. Default: ['mousedown'].
* @return {ReactClass}
*/
export default (Target, supportedEvents = ['mousedown']) => {
return class ReactOutsideEvent extends React.Component {
componentDidMount() {
if (!this.refs.target.onOutsideEvent) {
throw new Error('Component does not define "onOutsideEvent" method.');
}
supportedEvents.forEach((eventName) => {
window.addEventListener(eventName, this.handleEvent, false);
});
}
componentWillUnmount() {
supportedEvents.forEach((eventName) => {
window.removeEventListener(eventName, this.handleEvent, false);
});
}
handleEvent = (event) => {
let isInside,
isOutside,
target,
targetElement;
target = this.refs.target;
targetElement = ReactDOM.findDOMNode(target);
if (targetElement != undefined && !targetElement.contains(event.target)) {
target.onOutsideEvent(event);
}
};
render() {
return <Target ref='target' {... this.props} />;
}
};
};
| import React from 'react';
import ReactDOM from 'react-dom';
/**
* @param {ReactClass} Target The component that defines `onOutsideEvent` handler.
* @param {String[]} supportedEvents A list of valid DOM event names. Default: ['mousedown'].
* @return {ReactClass}
*/
export default (Target, supportedEvents = ['mousedown']) => {
return class ReactOutsideEvent extends React.Component {
componentDidMount = () => {
if (!this.refs.target.onOutsideEvent) {
throw new Error('Component does not define "onOutsideEvent" method.');
}
supportedEvents.forEach((eventName) => {
window.addEventListener(eventName, this.handleEvent, false);
});
};
componentWillUnmount = () => {
supportedEvents.forEach((eventName) => {
window.removeEventListener(eventName, this.handleEvent, false);
});
};
handleEvent = (event) => {
let isInside,
isOutside,
target,
targetElement;
target = this.refs.target;
targetElement = ReactDOM.findDOMNode(target);
if (targetElement != undefined && !targetElement.contains(event.target)) {
target.onOutsideEvent(event);
}
};
render() {
return <Target ref='target' {... this.props} />;
}
};
};
|
Allow service provider to run from console | <?php
namespace Watson\Breadcrumbs;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
class ServiceProvider extends BaseServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs');
$this->app->singleton('breadcrumbs', function ($app) {
return $app->make(Manager::class);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
$this->publishes([
__DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'),
], 'config');
$this->publishes([
__DIR__.'/../views' => resource_path('views/vendor/breadcrumbs')
], 'views');
$this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs');
if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) {
require $file;
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['breadcrumbs'];
}
}
| <?php
namespace Watson\Breadcrumbs;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
class ServiceProvider extends BaseServiceProvider
{
/**
* Indicates if loading of the provider is deferred.
*
* @var bool
*/
protected $defer = true;
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->mergeConfigFrom(__DIR__.'/../config/breadcrumbs.php', 'breadcrumbs');
$this->app->singleton('breadcrumbs', function ($app) {
return $app->make(Manager::class);
});
}
/**
* Perform post-registration booting of services.
*
* @return void
*/
public function boot()
{
if ($this->app->runningInConsole()) {
// Can't generate breadcrumbs in the console as there is no route
// from which we can build the trail from.
return;
}
$this->publishes([
__DIR__.'/../config/breadcrumbs.php' => config_path('breadcrumbs.php'),
], 'config');
$this->publishes([
__DIR__.'/../views' => resource_path('views/vendor/breadcrumbs')
], 'views');
$this->loadViewsFrom(__DIR__.'/../views', 'breadcrumbs');
if (file_exists($file = $this->app['path.base'].'/routes/breadcrumbs.php')) {
require $file;
}
}
/**
* Get the services provided by the provider.
*
* @return array
*/
public function provides()
{
return ['breadcrumbs'];
}
}
|
Order similar artist results properly | from django.db.models import Q
import echonest
from artists.models import Artist
from echonest.models import SimilarResponse
from users.models import User
from .models import (GeneralArtist, UserSimilarity, Similarity,
update_similarities)
def add_new_similarities(artist, force_update=False):
similarities = []
responses = SimilarResponse.objects.filter(
normalized_name=artist.normalized_name)
if responses.exists() and not force_update:
return # Echo Nest similarities already added
user = User.objects.get(email='echonest')
artist_names = echonest.get_similar(artist.name)
cc_artists = Artist.objects.filter(name__in=artist_names)
for cc_artist in cc_artists:
kwargs = dict(
cc_artist=cc_artist,
other_artist=artist,
)
UserSimilarity.objects.get_or_create(defaults={'weight': 1},
user=user, **kwargs)
similarities.append(Similarity.objects.get_or_create(**kwargs)[0])
update_similarities(similarities)
def get_similar(name):
artist, _ = GeneralArtist.objects.get_or_create(
normalized_name=name.upper(), defaults={'name': name})
add_new_similarities(artist)
similar = Q(similarity__other_artist=artist, similarity__weight__gt=0)
return Artist.objects.filter(similar).order_by('-similarity__weight')
| import echonest
from artists.models import Artist
from echonest.models import SimilarResponse
from users.models import User
from .models import (GeneralArtist, UserSimilarity, Similarity,
update_similarities)
def add_new_similarities(artist, force_update=False):
similarities = []
responses = SimilarResponse.objects.filter(
normalized_name=artist.normalized_name)
if responses.exists() and not force_update:
return # Echo Nest similarities already added
user = User.objects.get(email='echonest')
artist_names = echonest.get_similar(artist.name)
cc_artists = Artist.objects.filter(name__in=artist_names)
for cc_artist in cc_artists:
kwargs = dict(
cc_artist=cc_artist,
other_artist=artist,
)
UserSimilarity.objects.get_or_create(defaults={'weight': 1},
user=user, **kwargs)
similarities.append(Similarity.objects.get_or_create(**kwargs)[0])
update_similarities(similarities)
def get_similar(name):
artist, _ = GeneralArtist.objects.get_or_create(
normalized_name=name.upper(), defaults={'name': name})
add_new_similarities(artist)
return Artist.objects.filter(similarity__other_artist=artist,
similarity__weight__gt=0)
|
Use a non-locale aware output
Otherwise, the alpha value will not be handled correctly i.e. in a German locale (this locale uses a comma instead of a dot). | <?php
namespace OzdemirBurak\Iris\Traits;
trait AlphaTrait
{
/**
* @var double
*/
protected $alpha;
/**
* @param null $alpha
*
* @return $this|float
*/
public function alpha($alpha = null)
{
if ($alpha !== null) {
$this->alpha = $alpha <= 1 ? $alpha : 1;
return $this;
}
return $this->alpha;
}
/**
* @return string
*/
protected function validationRules()
{
return '/^(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d\.\d{1,})$/';
}
/**
* @param $color
*
* @return string
*/
protected function fixPrecision($color)
{
if (strpos($color, ',') !== false) {
$parts = explode(',', $color);
$parts[3] = strpos($parts[3], '.') === false ? $parts[3] . '.0' : $parts[3];
$color = implode(',', $parts);
}
return $color;
}
/**
* @param string $alpha
* @return float
*/
protected function alphaHexToFloat(string $alpha): float
{
return sprintf('%0.2F', hexdec($alpha) / 255);
}
/**
* @param float $alpha
* @return string
*/
protected function alphaFloatToHex(float $alpha): string
{
return dechex($alpha * 255);
}
}
| <?php
namespace OzdemirBurak\Iris\Traits;
trait AlphaTrait
{
/**
* @var double
*/
protected $alpha;
/**
* @param null $alpha
*
* @return $this|float
*/
public function alpha($alpha = null)
{
if ($alpha !== null) {
$this->alpha = $alpha <= 1 ? $alpha : 1;
return $this;
}
return $this->alpha;
}
/**
* @return string
*/
protected function validationRules()
{
return '/^(\d{1,3}),(\d{1,3}),(\d{1,3}),(\d\.\d{1,})$/';
}
/**
* @param $color
*
* @return string
*/
protected function fixPrecision($color)
{
if (strpos($color, ',') !== false) {
$parts = explode(',', $color);
$parts[3] = strpos($parts[3], '.') === false ? $parts[3] . '.0' : $parts[3];
$color = implode(',', $parts);
}
return $color;
}
/**
* @param string $alpha
* @return float
*/
protected function alphaHexToFloat(string $alpha): float
{
return sprintf('%0.2f', hexdec($alpha) / 255);
}
/**
* @param float $alpha
* @return string
*/
protected function alphaFloatToHex(float $alpha): string
{
return dechex($alpha * 255);
}
}
|
Add rst long description for pypi | """
Copyright (c) 2010-2013, Anthony Garcia <[email protected]>
Distributed under the ISC License (see LICENSE)
"""
from distutils.core import setup, Command
from distutils.errors import DistutilsOptionError
from unittest import TestLoader, TextTestRunner
import steam
class run_tests(Command):
description = "Run the steamodd unit tests"
user_options = [
("key=", 'k', "Your API key")
]
def initialize_options(self):
self.key = None
def finalize_options(self):
if not self.key:
raise DistutilsOptionError("API key is required")
else:
steam.api.key.set(self.key)
def run(self):
tests = TestLoader().discover("tests")
TextTestRunner(verbosity = 2).run(tests)
setup(name = "steamodd",
version = steam.__version__,
description = "High level Steam API implementation with low level reusable core",
long_description = "Please see the `README <https://github.com/Lagg/steamodd/blob/master/README.md>`_ for a full description.",
packages = ["steam"],
author = steam.__author__,
author_email = steam.__contact__,
url = "https://github.com/Lagg/steamodd",
classifiers = [
"License :: OSI Approved :: ISC License (ISCL)",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python"
],
license = steam.__license__,
cmdclass = {"run_tests": run_tests})
| """
Copyright (c) 2010-2013, Anthony Garcia <[email protected]>
Distributed under the ISC License (see LICENSE)
"""
from distutils.core import setup, Command
from distutils.errors import DistutilsOptionError
from unittest import TestLoader, TextTestRunner
import steam
class run_tests(Command):
description = "Run the steamodd unit tests"
user_options = [
("key=", 'k', "Your API key")
]
def initialize_options(self):
self.key = None
def finalize_options(self):
if not self.key:
raise DistutilsOptionError("API key is required")
else:
steam.api.key.set(self.key)
def run(self):
tests = TestLoader().discover("tests")
TextTestRunner(verbosity = 2).run(tests)
setup(name = "steamodd",
version = steam.__version__,
description = "High level Steam API implementation with low level reusable core",
packages = ["steam"],
author = steam.__author__,
author_email = steam.__contact__,
url = "https://github.com/Lagg/steamodd",
classifiers = [
"License :: OSI Approved :: ISC License (ISCL)",
"Intended Audience :: Developers",
"Operating System :: OS Independent",
"Programming Language :: Python"
],
license = steam.__license__,
cmdclass = {"run_tests": run_tests})
|
Include level, channel, and datetime in extra data sent to Rollbar. | <?php
namespace Monolog\Handler;
use RollbarNotifier;
use Exception;
/**
* Sends errors to Rollbar
*
* @author Paul Statezny <[email protected]>
*/
class RollbarHandler extends AbstractProcessingHandler
{
/**
* Rollbar notifier
*
* @var RollbarNotifier
*/
protected $rollbarNotifier;
/**
* @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token
* @param integer $level The minimum logging level at which this handler will be triggered
* @param boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true)
{
$this->rollbarNotifier = $rollbarNotifier;
parent::__construct($level, $bubble);
}
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
if (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
$this->rollbarNotifier->report_exception($record['context']['exception']);
} else {
$extraData = array(
'level' => $record['level'],
'channel' => $record['channel'],
'datetime' => $record['datetime'],
);
$this->rollbarNotifier->report_message(
$record['message'],
$record['level_name'],
array_merge($record['context'], $record['extra'], $extraData)
);
}
}
/**
* {@inheritdoc}
*/
public function close()
{
$this->rollbarNotifier->flush();
}
}
| <?php
namespace Monolog\Handler;
use RollbarNotifier;
use Exception;
/**
* Sends errors to Rollbar
*
* @author Paul Statezny <[email protected]>
*/
class RollbarHandler extends AbstractProcessingHandler
{
/**
* Rollbar notifier
*
* @var RollbarNotifier
*/
protected $rollbarNotifier;
/**
* @param RollbarNotifier $rollbarNotifier RollbarNotifier object constructed with valid token
* @param integer $level The minimum logging level at which this handler will be triggered
* @param boolean $bubble Whether the messages that are handled can bubble up the stack or not
*/
public function __construct(RollbarNotifier $rollbarNotifier, $level = Logger::ERROR, $bubble = true)
{
$this->rollbarNotifier = $rollbarNotifier;
parent::__construct($level, $bubble);
}
/**
* {@inheritdoc}
*/
protected function write(array $record)
{
if (isset($record['context']['exception']) && $record['context']['exception'] instanceof Exception) {
$this->rollbarNotifier->report_exception($record['context']['exception']);
} else {
$this->rollbarNotifier->report_message(
$record['message'],
$record['level_name'],
array_merge($record['context'], $record['extra'])
);
}
}
/**
* {@inheritdoc}
*/
public function close()
{
$this->rollbarNotifier->flush();
}
}
|
Add the Windows compatibility for the processor counter | <?php
namespace Liuggio\Fastest\Process;
use Symfony\Component\Process\Process;
/**
* Number of processors seen by the OS and used for process scheduling.
*/
class ProcessorCounter
{
const PROC_DEFAULT_NUMBER = 4;
const PROC_CPUINFO = '/proc/cpuinfo';
private static $count = null;
private $procCPUInfo;
public function __construct($procCPUInfo = self::PROC_CPUINFO)
{
$this->procCPUInfo = $procCPUInfo;
}
public function execute()
{
if (null !== self::$count) {
return self::$count;
}
self::$count = $this->readFromProcCPUInfo();
return self::$count;
}
private function readFromProcCPUInfo()
{
if (PHP_OS === 'Darwin') {
$processors = system('/usr/sbin/sysctl -n hw.physicalcpu');
if ($processors !== false && $processors) {
return $processors;
}
} elseif (PHP_OS === 'Linux') {
$file = $this->procCPUInfo;
if (is_file($file) && is_readable($file)) {
try {
$contents = trim(file_get_contents($file));
return substr_count($contents, 'processor');
} catch (\Exception $e) {
}
}
} elseif ('\\' === DIRECTORY_SEPARATOR) {
$process = new Process('for /F "tokens=2 delims==" %C in (\'wmic cpu get NumberOfLogicalProcessors /value ^| findstr NumberOfLogicalProcessors\') do @echo %C');
$process->run();
if ($process->isSuccessful() && ($numProc = intval($process->getOutput())) > 0) {
return $numProc;
}
}
return self::PROC_DEFAULT_NUMBER;
}
}
| <?php
namespace Liuggio\Fastest\Process;
/**
* Number of processors seen by the OS and used for process scheduling.
*/
class ProcessorCounter
{
const PROC_DEFAULT_NUMBER = 4;
const PROC_CPUINFO = '/proc/cpuinfo';
private static $count = null;
private $procCPUInfo;
public function __construct($procCPUInfo = self::PROC_CPUINFO)
{
$this->procCPUInfo = $procCPUInfo;
}
public function execute()
{
if (null !== self::$count) {
return self::$count;
}
self::$count = $this->readFromProcCPUInfo();
return self::$count;
}
private function readFromProcCPUInfo()
{
if (PHP_OS === 'Darwin') {
$processors = system('/usr/sbin/sysctl -n hw.physicalcpu');
if ($processors !== false && $processors) {
return $processors;
}
} elseif (PHP_OS === 'Linux') {
$file = $this->procCPUInfo;
if (is_file($file) && is_readable($file)) {
try {
$contents = trim(file_get_contents($file));
return substr_count($contents, 'processor');
} catch (\Exception $e) {
}
}
}
return self::PROC_DEFAULT_NUMBER;
}
}
|
Make privacy checkbox on user form required via required attribute. | from django import forms
from tower import ugettext_lazy as _lazy
from flicks.base.util import country_choices
from flicks.users.models import UserProfile
class UserProfileForm(forms.ModelForm):
# L10n: Used in a choice field where users can choose between receiving
# L10n: HTML-based or Text-only newsletter emails.
NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text')))
privacy_policy_agree = forms.BooleanField(
required=True,
widget=forms.CheckboxInput(attrs={'required': 'required'}))
mailing_list_signup = forms.BooleanField(required=False)
mailing_list_format = forms.ChoiceField(required=False,
choices=NEWSLETTER_FORMATS,
initial='html')
class Meta:
model = UserProfile
fields = ('full_name', 'nickname', 'country', 'address1', 'address2',
'city', 'mailing_country', 'state', 'postal_code')
widgets = {
'full_name': forms.TextInput(attrs={'required': 'required'}),
}
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
# Localize countries list
self.fields['country'].choices = country_choices(allow_empty=False)
self.fields['mailing_country'].choices = country_choices()
| from django import forms
from tower import ugettext_lazy as _lazy
from flicks.base.util import country_choices
from flicks.users.models import UserProfile
class UserProfileForm(forms.ModelForm):
# L10n: Used in a choice field where users can choose between receiving
# L10n: HTML-based or Text-only newsletter emails.
NEWSLETTER_FORMATS = (('html', 'HTML'), ('text', _lazy('Text')))
privacy_policy_agree = forms.BooleanField(required=True)
mailing_list_signup = forms.BooleanField(required=False)
mailing_list_format = forms.ChoiceField(required=False,
choices=NEWSLETTER_FORMATS,
initial='html')
class Meta:
model = UserProfile
fields = ('full_name', 'nickname', 'country', 'address1', 'address2',
'city', 'mailing_country', 'state', 'postal_code')
widgets = {
'full_name': forms.TextInput(attrs={'required': 'required'}),
'privacy_policy_agree': forms.CheckboxInput(
attrs={'required': 'required'}),
}
def __init__(self, *args, **kwargs):
super(UserProfileForm, self).__init__(*args, **kwargs)
# Localize countries list
self.fields['country'].choices = country_choices(allow_empty=False)
self.fields['mailing_country'].choices = country_choices()
|
Add code in order to get the current user | <?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
class APIController extends Controller
{
/**
* @param $request Request
* @throws NotFoundHttpException - if the webservice is not found (status code 404)
* @return \Symfony\Component\HttpFoundation\JsonResponse
* @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true})
*/
public function apiAction(Request $request, $namespace, $classname){
try{
$service = $this->get('app.api.webservice')->factory($namespace, $classname);
} catch (Exception $e){
throw $this->createNotFoundException('Webservice not found in the API');
}
$queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all()));
$user = null;
if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
$user = $this->get('security.token_storage')->getToken()->getUser();
}
$result = $service->execute($queryData, $user);
$response = $this->json($result);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
}
| <?php
namespace AppBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
class APIController extends Controller
{
/**
* @param $request Request
* @throws NotFoundHttpException - if the webservice is not found (status code 404)
* @return \Symfony\Component\HttpFoundation\JsonResponse
* @Route("/api/{namespace}/{classname}", name="api", options={"expose" = true})
*/
public function apiAction(Request $request, $namespace, $classname){
try{
$service = $this->get('app.api.webservice')->factory($namespace, $classname);
} catch (Exception $e){
throw $this->createNotFoundException('Webservice not found in the API');
}
$queryData = new ParameterBag(array_merge($request->query->all(), $request->request->all()));
$user = null;
// if($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')){
// $user = $this->get('security.token_storage')->getToken()->getUser();
// }
$result = $service->execute($queryData, $user);
$response = $this->json($result);
$response->headers->set('Access-Control-Allow-Origin', '*');
return $response;
}
}
|
Create return the created object from mongodb | const ModelState = require('../model-state');
class BaseData {
constructor(db, ModelClass, validator) {
this.db = db;
this.validator = validator;
this.collectionName = ModelClass.name.toLowerCase() + 's';
this.collection = db.collection(this.collectionName);
}
getAll(filters) {
if (filters) {
return this.collection.find(filters).toArray();
}
return this.collection.find().toArray();
}
create(model) {
const modelState = this.validate(model);
if (!modelState.isValid) {
return Promise.reject(modelState.errors);
}
return this.collection.insert(model)
.then((status) => {
// conatins the created Id
return status.ops[0];
// return model;
});
}
/*
findOrCreateBy(props) do we need this function ?
https://github.com/TelerikAcademy/Web-Applications-with-Node.js/blob/master/Live-demos/project-structure/data/base/base.data.js
*/
updateById(model) {
return this.collection.updateOne({
_id: model._id,
}, model);
}
validate(model) {
if (!this.validator || typeof this.validator.isValid !== 'function') {
return ModelState.valid();
}
return this.validator.isValid(model);
}
}
module.exports = BaseData;
| const ModelState = require('../model-state');
class BaseData {
constructor(db, ModelClass, validator) {
this.db = db;
this.validator = validator;
this.collectionName = ModelClass.name.toLowerCase() + 's';
this.collection = db.collection(this.collectionName);
}
getAll(filters) {
if (filters) {
return this.collection.find(filters).toArray();
}
return this.collection.find().toArray();
}
create(model) {
const modelState = this.validate(model);
if (!modelState.isValid) {
return Promise.reject(modelState.errors);
}
return this.collection.insert(model)
.then(() => {
// TODO: refactor, parameters?, should return the whole model?
return model;
});
}
/*
findOrCreateBy(props) do we need this function ?
https://github.com/TelerikAcademy/Web-Applications-with-Node.js/blob/master/Live-demos/project-structure/data/base/base.data.js
*/
updateById(model) {
return this.collection.updateOne({
_id: model._id,
}, model);
}
validate(model) {
if (!this.validator || typeof this.validator.isValid !== 'function') {
return ModelState.valid();
}
return this.validator.isValid(model);
}
}
module.exports = BaseData;
|
Move urlWithExtension to the global common
Remove from content common as it overwrites the global common defined by the user | const config = {
common: {
outputDir: 'public',
styles: [],
scripts: [],
urlWithExtension: false,
},
template: {
common: {
path: 'templates', // Path where the templates are
},
pug: {
pretty: true,
},
},
file: {
html: {},
json: {},
markdown: {},
yaml: {},
},
asset: {
active: [],
common: {
path: 'assets', // path to assets
},
styles: {
postcss: {
plugins: {
prod: [{ name: 'cssnano' }],
dev: [],
},
},
},
scripts: {},
fonts: {},
images: {
minify: {},
},
},
content: {
active: [],
common: {
path: 'content', // path to content
htmlmin: {
removeAttributeQuotes: true,
collapseWhitespace: true,
},
},
pages: {},
posts: {
urlFormat: '_blog/${year}/${month}/${date}/', // eslint-disable-line
},
},
decorator: {
active: [],
common: {},
sitemap: {},
tags: {},
pagination: {},
},
};
module.exports = config;
| const config = {
common: {
outputDir: 'public',
styles: [],
scripts: [],
},
template: {
common: {
path: 'templates', // Path where the templates are
},
pug: {
pretty: true,
},
},
file: {
html: {},
json: {},
markdown: {},
yaml: {},
},
asset: {
active: [],
common: {
path: 'assets', // path to assets
},
styles: {
postcss: {
plugins: {
prod: [{ name: 'cssnano' }],
dev: [],
},
},
},
scripts: {},
fonts: {},
images: {
minify: {},
},
},
content: {
active: [],
common: {
path: 'content', // path to content
urlWithExtension: false,
htmlmin: {
removeAttributeQuotes: true,
collapseWhitespace: true,
},
},
pages: {},
posts: {
urlFormat: '_blog/${year}/${month}/${date}/', // eslint-disable-line
},
},
decorator: {
active: [],
common: {},
sitemap: {},
tags: {},
pagination: {},
},
};
module.exports = config;
|
Stop stripping out the Server header from response from origins. Should overwrite this in a zuul filter if we don't want to use the Server header from origin, rather than removing it by default. | package com.netflix.zuul.util;
import com.netflix.client.http.HttpResponse;
import com.netflix.zuul.message.http.HttpRequestMessage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* User: [email protected]
* Date: 6/8/15
* Time: 11:50 AM
*/
public class ProxyUtils
{
public static boolean isValidRequestHeader(String headerName)
{
switch (headerName.toLowerCase()) {
case "connection":
case "content-length":
case "transfer-encoding":
return false;
default:
return true;
}
}
public static boolean isValidResponseHeader(String headerName)
{
switch (headerName.toLowerCase()) {
case "connection":
case "keep-alive":
case "content-length":
case "transfer-encoding":
return false;
default:
return true;
}
}
@RunWith(MockitoJUnitRunner.class)
public static class TestUnit
{
@Mock
HttpResponse proxyResp;
@Mock
HttpRequestMessage request;
@Test
public void testIsValidResponseHeader()
{
Assert.assertTrue(isValidResponseHeader("test"));
Assert.assertFalse(isValidResponseHeader("content-length"));
Assert.assertFalse(isValidResponseHeader("connection"));
}
}
}
| package com.netflix.zuul.util;
import com.netflix.client.http.HttpResponse;
import com.netflix.zuul.message.http.HttpRequestMessage;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/**
* User: [email protected]
* Date: 6/8/15
* Time: 11:50 AM
*/
public class ProxyUtils
{
public static boolean isValidRequestHeader(String headerName)
{
switch (headerName.toLowerCase()) {
case "connection":
case "content-length":
case "transfer-encoding":
return false;
default:
return true;
}
}
public static boolean isValidResponseHeader(String headerName)
{
switch (headerName.toLowerCase()) {
case "connection":
case "keep-alive":
case "content-length":
case "server":
case "transfer-encoding":
return false;
default:
return true;
}
}
@RunWith(MockitoJUnitRunner.class)
public static class TestUnit
{
@Mock
HttpResponse proxyResp;
@Mock
HttpRequestMessage request;
@Test
public void testIsValidResponseHeader()
{
Assert.assertTrue(isValidResponseHeader("test"));
Assert.assertFalse(isValidResponseHeader("content-length"));
Assert.assertFalse(isValidResponseHeader("connection"));
}
}
}
|
Add URLs to each searializer | from django.contrib.auth.models import User
from .models import ContentItem, Profile, Comment, Hashtag, ContentHashTag, Like
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'url', 'username', 'email', 'last_name', 'first_name')
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
fields = ('id', 'url', 'user', 'personal_info', 'job_title', 'department', 'location', 'expertise',
'phone_number', 'contact_skype', 'contact_facebook', 'contact_linkedin', 'user_photo')
class ContentItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ContentItem
fields = ('id', 'url', 'upload_date', 'title', 'description', 'image', 'uploaded_by')
class HashtagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hashtag
fields = ('id', 'url', 'hashtag_text')
class ContentHashtagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ContentHashTag
fields = ('id', 'url', 'content_id', 'hashtag_id')
class LikeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Like
fields = ('id', 'url', 'user_id', 'content_id')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = ('id', 'url', 'comment_text', 'publication_date', 'author', 'contentItem')
| from django.contrib.auth.models import User
from .models import ContentItem, Profile, Comment, Hashtag, ContentHashTag, Like
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('id', 'url', 'username', 'email', 'last_name', 'first_name')
class ProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Profile
fields = ('user', 'personal_info', 'job_title', 'department', 'location', 'expertise',
'phone_number', 'contact_skype', 'contact_facebook', 'contact_linkedin', 'user_photo')
class ContentItemSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ContentItem
fields = ('id', 'upload_date', 'title', 'description', 'image', 'uploaded_by')
class HashtagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Hashtag
fields = ('id', 'hashtag_text')
class ContentHashtagSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ContentHashTag
fields = ('id', 'content_id', 'hashtag_id')
class LikeSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Like
fields = ('id', 'user_id', 'content_id')
class CommentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Comment
fields = ('id', 'comment_text', 'publication_date', 'author', 'contentItem')
|
Allow retrieval of external api credentials | #!/usr/bin/env python2.7
import os
import json
class OAEnv(object):
@property
def static_http_root(self):
if self.envcfg['httpinfo']['secure'] is True:
security = "https://"
else:
security = "http://"
return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] )
@property
def dbinfo(self):
return self.envcfg['dbinfo']
@property
def crypto(self):
return self.envcfg['crypto']
@property
def extcreds(self):
return self.envcfg['extcreds']
def __init__(self, requested_env):
cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") )
with open( cfg_file ) as f:
self.envcfg = json.loads( f.read() )[requested_env]
#This is where we hold library state.
#You will get cut if you don't manipulate the p_* variables
#via getenv() and initenv()
p_refcount_env = 0
p_env = None
def initenv(envstr):
"""envstr: one of local, dev, qa, prod.
Does not return OAEnv variable; for that, you
must call getenv"""
global p_env
global p_refcount_env
if p_refcount_env == 0:
p_env = OAEnv(envstr)
p_refcount_env += 1
def getenv():
"""Accessor method for global state"""
global p_env
return p_env
| #!/usr/bin/env python2.7
import os
import json
class OAEnv(object):
@property
def static_http_root(self):
if self.envcfg['httpinfo']['secure'] is True:
security = "https://"
else:
security = "http://"
return "%s%s" % ( security, self.envcfg['httpinfo']['httproot'] )
@property
def dbinfo(self):
return self.envcfg['dbinfo']
@property
def crypto(self):
return self.envcfg['crypto']
def __init__(self, requested_env):
cfg_file = "%s/envcfg.json" % ( os.environ.get("OPENARC_CFG_DIR") )
with open( cfg_file ) as f:
self.envcfg = json.loads( f.read() )[requested_env]
#This is where we hold library state.
#You will get cut if you don't manipulate the p_* variables
#via getenv() and initenv()
p_refcount_env = 0
p_env = None
def initenv(envstr):
"""envstr: one of local, dev, qa, prod.
Does not return OAEnv variable; for that, you
must call getenv"""
global p_env
global p_refcount_env
if p_refcount_env == 0:
p_env = OAEnv(envstr)
p_refcount_env += 1
def getenv():
"""Accessor method for global state"""
global p_env
return p_env
|
Revert "Allow Ref in StringValue"
This reverts commit a1957fb04118ce13f2cb37a52bc93718eed0ae41. | from . import AWSObject, AWSProperty, Ref
from .validators import boolean
class ParameterObjectAttribute(AWSProperty):
props = {
'Key': (basestring, True),
'StringValue': (basestring, False),
}
class ParameterObject(AWSProperty):
props = {
'Attributes': ([ParameterObjectAttribute], True),
'Id': (basestring, True),
}
class ParameterValue(AWSProperty):
props = {
'Id': (basestring, True),
'StringValue': (basestring, True),
}
class ObjectField(AWSProperty):
props = {
'Key': (basestring, True),
'RefValue': ([basestring, Ref], False),
'StringValue': (basestring, False),
}
class PipelineObject(AWSProperty):
props = {
'Fields': ([ObjectField], True),
'Id': (basestring, True),
'Name': (basestring, True),
}
class PipelineTag(AWSProperty):
props = {
'Key': (basestring, True),
'Value': (basestring, True),
}
class Pipeline(AWSObject):
resource_type = "AWS::DataPipeline::Pipeline"
props = {
'Activate': (boolean, False),
'Description': (basestring, False),
'Name': (basestring, True),
'ParameterObjects': ([ParameterObject], False),
'ParameterValues': ([ParameterValue], False),
'PipelineObjects': ([PipelineObject], True),
'PipelineTags': ([PipelineTag], False),
}
| from . import AWSObject, AWSProperty, Ref
from .validators import boolean
class ParameterObjectAttribute(AWSProperty):
props = {
'Key': (basestring, True),
'StringValue': (basestring, False),
}
class ParameterObject(AWSProperty):
props = {
'Attributes': ([ParameterObjectAttribute], True),
'Id': (basestring, True),
}
class ParameterValue(AWSProperty):
props = {
'Id': (basestring, True),
'StringValue': (basestring, True),
}
class ObjectField(AWSProperty):
props = {
'Key': (basestring, True),
'RefValue': ([basestring, Ref], False),
'StringValue': ([basestring, Ref], False),
}
class PipelineObject(AWSProperty):
props = {
'Fields': ([ObjectField], True),
'Id': (basestring, True),
'Name': (basestring, True),
}
class PipelineTag(AWSProperty):
props = {
'Key': (basestring, True),
'Value': (basestring, True),
}
class Pipeline(AWSObject):
resource_type = "AWS::DataPipeline::Pipeline"
props = {
'Activate': (boolean, False),
'Description': (basestring, False),
'Name': (basestring, True),
'ParameterObjects': ([ParameterObject], False),
'ParameterValues': ([ParameterValue], False),
'PipelineObjects': ([PipelineObject], True),
'PipelineTags': ([PipelineTag], False),
}
|
Drop back to state as return val
If we store state on Algorithm then we're not thread-safe. | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
state = algorithm.run(argv=self.argv, _through='get_website_from_argv')
return state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
| from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from algorithm import Algorithm
def main():
Server().main()
class Server(object):
def __init__(self, argv=None):
self.argv = argv
def get_algorithm(self):
return Algorithm('aspen.algorithms.server')
def get_website(self):
"""Return a website object. Useful in testing.
"""
algorithm = self.get_algorithm()
algorithm.run(argv=self.argv, _through='get_website_from_argv')
return algorithm.state['website']
def main(self, argv=None):
"""http://aspen.io/cli/
"""
try:
argv = argv if argv is not None else self.argv
algorithm = self.get_algorithm()
algorithm.run(argv=argv)
except (SystemExit, KeyboardInterrupt):
# Under some (most?) network engines, a SIGINT will be trapped by the
# SIGINT signal handler above. However, gevent does "something" with
# signals and our signal handler never fires. However, we *do* get a
# KeyboardInterrupt here in that case. *shrug*
#
# See: https://github.com/gittip/aspen-python/issues/196
pass
except:
import aspen, traceback
aspen.log_dammit("Oh no! Aspen crashed!")
aspen.log_dammit(traceback.format_exc())
if __name__ == '__main__':
main()
|
:ambulance: Remove ref to deleted file | /* @flow */
import React from 'react'
import TogglolCalendar from './TogglolCalendar'
import ApiKeyInput from './ApiKeyInput'
import type { TimeEntryObject } from '../interfaces/togglol'
import type { ProjectObject } from '../interfaces/togglol'
type Props = {
time_entries: Array<TimeEntryObject>,
user_loaded: boolean,
fetchTimeEntries: Function,
fetchUserInfo: Function,
setApiKey: Function,
setApiKeyAndFetchUserInfo: Function,
getUserInfo: Function,
data: Object
}
class Togglol extends React.Component {
constructor(props) {
super(props);
}
setApiKeyAndFetchUserInfo(api_key) {
console.log("Set: " + api_key);
console.log(this);
//this.setApiKey({api_key: api_key});
}
render() {
if(this.props.user_loaded) {
return(
<TogglolCalendar
data={this.props.data}
time_entries={this.props.time_entries}
fetchTimeEntries={this.props.fetchTimeEntries}
/>
);
}
else {
return (<ApiKeyInput onSet={this.props.setApiKey} onLoad={this.props.fetchUserInfo}/>)
}
}
}
Togglol.propTypes = {
time_entries: React.PropTypes.array.isRequired,
fetchTimeEntries: React.PropTypes.func.isRequired,
setApiKey: React.PropTypes.func.isRequired,
data: React.PropTypes.object
}
export default Togglol | /* @flow */
import React from 'react'
import classes from './Togglol.scss'
import TogglolCalendar from './TogglolCalendar'
import ApiKeyInput from './ApiKeyInput'
import type { TimeEntryObject } from '../interfaces/togglol'
import type { ProjectObject } from '../interfaces/togglol'
type Props = {
time_entries: Array<TimeEntryObject>,
user_loaded: boolean,
fetchTimeEntries: Function,
fetchUserInfo: Function,
setApiKey: Function,
setApiKeyAndFetchUserInfo: Function,
getUserInfo: Function,
data: Object
}
class Togglol extends React.Component {
constructor(props) {
super(props);
}
setApiKeyAndFetchUserInfo(api_key) {
console.log("Set: " + api_key);
console.log(this);
//this.setApiKey({api_key: api_key});
}
render() {
if(this.props.user_loaded) {
return(
<TogglolCalendar
data={this.props.data}
time_entries={this.props.time_entries}
fetchTimeEntries={this.props.fetchTimeEntries}
/>
);
}
else {
return (<ApiKeyInput onSet={this.props.setApiKey} onLoad={this.props.fetchUserInfo}/>)
}
}
}
Togglol.propTypes = {
time_entries: React.PropTypes.array.isRequired,
fetchTimeEntries: React.PropTypes.func.isRequired,
setApiKey: React.PropTypes.func.isRequired,
data: React.PropTypes.object
}
export default Togglol |
Use classifiers to specify the license.
Classifiers are a standard way of specifying a license, and make it easy
for automated tools to properly detect the license of the package.
The "license" field should only be used if the license has no
corresponding Trove classifier. | #!/usr/bin/python
import os
import re
from setuptools import setup
from m2r import parse_from_file
import restructuredtext_lint
# Parser README.md into reStructuredText format
rst_readme = parse_from_file('README.md')
# Validate the README, checking for errors
errors = restructuredtext_lint.lint(rst_readme)
# Raise an exception for any errors found
if errors:
print(rst_readme)
raise ValueError('README.md contains errors: ',
', '.join([e.message for e in errors]))
# Attempt to get version number from TravisCI environment variable
version = os.environ.get('TRAVIS_TAG', default='0.0.0')
# Remove leading 'v'
version = re.sub('^v', '', version)
setup(
name='anybadge',
description='Simple, flexible badge generator for project badges.',
long_description=rst_readme,
version=version,
author='Jon Grace-Cox',
author_email='[email protected]',
py_modules=['anybadge', 'anybadge_server'],
setup_requires=['setuptools', 'wheel'],
tests_require=['unittest'],
install_requires=[],
data_files=[],
options={
'bdist_wheel': {'universal': True}
},
url='https://github.com/jongracecox/anybadge',
entry_points={
'console_scripts': ['anybadge=anybadge:main',
'anybadge-server=anybadge_server:main'],
},
classifiers=[
'License :: OSI Approved :: MIT License'
]
)
| #!/usr/bin/python
import os
import re
from setuptools import setup
from m2r import parse_from_file
import restructuredtext_lint
# Parser README.md into reStructuredText format
rst_readme = parse_from_file('README.md')
# Validate the README, checking for errors
errors = restructuredtext_lint.lint(rst_readme)
# Raise an exception for any errors found
if errors:
print(rst_readme)
raise ValueError('README.md contains errors: ',
', '.join([e.message for e in errors]))
# Attempt to get version number from TravisCI environment variable
version = os.environ.get('TRAVIS_TAG', default='0.0.0')
# Remove leading 'v'
version = re.sub('^v', '', version)
setup(
name='anybadge',
description='Simple, flexible badge generator for project badges.',
long_description=rst_readme,
version=version,
author='Jon Grace-Cox',
author_email='[email protected]',
py_modules=['anybadge', 'anybadge_server'],
setup_requires=['setuptools', 'wheel'],
tests_require=['unittest'],
install_requires=[],
data_files=[],
options={
'bdist_wheel': {'universal': True}
},
url='https://github.com/jongracecox/anybadge',
entry_points={
'console_scripts': ['anybadge=anybadge:main',
'anybadge-server=anybadge_server:main'],
}
)
|
Fix index as key anti pattern | import React from 'react';
import { BrowserRouter, Match, Miss } from 'react-router'
import Header from './components/Header';
import CTA from './components/CTA';
import Footer from './components/Footer';
import routes from './config/routes';
import FourOhFour from './components/404';
const App = () => (
// <BrowserRouter history={history}>
<BrowserRouter>
<div>
<Header />
{
routes.map((route, index) => (
// rendering `Match`s with different
// components but the same pattern as before
<Match
key={route.pattern}
pattern={route.pattern}
// component={route.main}
render={matchProps => {
const Component = route.main;
// TODO: double check where to put scrolling
window.scroll(0, 0);
return (
<div className="content">
<Component {...matchProps} />
<CTA matchProps={matchProps} />
</div>
);
}}
exactly={route.exactly}
/>
))
}
<Miss component={FourOhFour} />
<Footer />
</div>
</BrowserRouter>
);
export default App;
| import React from 'react';
import { BrowserRouter, Match, Miss } from 'react-router'
import Header from './components/Header';
import CTA from './components/CTA';
import Footer from './components/Footer';
import routes from './config/routes';
import FourOhFour from './components/404';
const App = () => (
// <BrowserRouter history={history}>
<BrowserRouter>
<div>
<Header />
{
routes.map((route, index) => (
// rendering `Match`s with different
// components but the same pattern as before
<Match
// FIXME: index as key
key={index}
pattern={route.pattern}
// component={route.main}
render={matchProps => {
const Component = route.main;
// TODO: double check where to put scrolling
window.scroll(0, 0);
return (
<div className="content">
<Component {...matchProps} />
<CTA matchProps={matchProps} />
</div>
);
}}
exactly={route.exactly}
/>
))
}
<Miss component={FourOhFour} />
<Footer />
</div>
</BrowserRouter>
);
export default App;
|
Remove glide, she doesn't even go here | <?php
namespace Northstar\Services;
use DoSomething\Gateway\Common\RestApiClient;
class Fastly extends RestApiClient
{
/**
* Create a new Fastly API client.
*/
public function __construct()
{
$url = config('services.fastly.url');
$options = [
'headers' => [
'Fastly-Key' => config('services.fastly.key'),
'Accept' => 'application/json',
],
];
parent::__construct($url, $options);
}
/**
* Purge object from Fastly cache based on give cache key
*
* @param $cacheKey String
*/
public function purgeKey($cacheKey)
{
$fastlyConfigured = ! is_null(config('services.fastly.url')) &&
! is_null(config('services.fastly.key')) &&
! is_null(config('services.fastly.service_id')) &&
isset($cacheKey);
if (! $fastlyConfigured) {
info('image_cache_purge_failed', ['response' => 'Fastly not configured correctly on this environment.']);
return null;
}
$service = config('services.fastly.service_id');
$purgeResponse = $this->post('service/'.$service.'/purge/'.$cacheKey);
info('image_cache_purge_successful', ['response' => $purgeResponse]);
return $purgeResponse;
}
}
| <?php
namespace Northstar\Services;
use DoSomething\Gateway\Common\RestApiClient;
class Fastly extends RestApiClient
{
/**
* Create a new Fastly API client.
*/
public function __construct()
{
$url = config('services.fastly.url');
$options = [
'headers' => [
'Fastly-Key' => config('services.fastly.key'),
'Accept' => 'application/json',
],
];
parent::__construct($url, $options);
}
/**
* Purge object from Fastly cache based on give cache key
*
* @param $cacheKey String
*/
public function purgeKey($cacheKey)
{
$fastlyConfigured = config('features.glide') &&
! is_null(config('services.fastly.url')) &&
! is_null(config('services.fastly.key')) &&
! is_null(config('services.fastly.service_id')) &&
isset($cacheKey);
if (! $fastlyConfigured) {
info('image_cache_purge_failed', ['response' => 'Fastly not configured correctly on this environment.']);
return null;
}
$service = config('services.fastly.service_id');
$purgeResponse = $this->post('service/'.$service.'/purge/'.$cacheKey);
info('image_cache_purge_successful', ['response' => $purgeResponse]);
return $purgeResponse;
}
}
|
Make sure the middleware checks URIs case insensitive | <?php
namespace A3020\Centry\Http\Middleware;
use Concrete\Core\Application\ApplicationAwareInterface;
use Concrete\Core\Application\ApplicationAwareTrait;
use Concrete\Core\Http\Middleware\DelegateInterface;
use Concrete\Core\Http\Middleware\MiddlewareInterface;
use Illuminate\Config\Repository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CentryApiTokenMiddleware implements MiddlewareInterface, ApplicationAwareInterface
{
use ApplicationAwareTrait;
public function process(Request $request, DelegateInterface $frame)
{
$requestUri = strtolower($request->getRequestUri());
if (strpos($requestUri, 'centry/api') !== false) {
if (!$this->isAuthorized($request)) {
return new JsonResponse([
'error' => t('Unauthorized Request'),
], 401);
}
}
/** @var Response $response */
$response = $frame->next($request);
return $response;
}
/**
* Return true is request is authorized.
*
* Meaning that the token in the header equals the one in the config.
*
* @param Request $request
* @return bool
*/
private function isAuthorized(Request $request)
{
$token = $request->headers->get('x-centry-api-token');
if (empty($token)) {
return false;
}
$config = $this->app->make(Repository::class);
return $token === (string) $config->get('centry.api_token');
}
}
| <?php
namespace A3020\Centry\Http\Middleware;
use Concrete\Core\Application\ApplicationAwareInterface;
use Concrete\Core\Application\ApplicationAwareTrait;
use Concrete\Core\Http\Middleware\DelegateInterface;
use Concrete\Core\Http\Middleware\MiddlewareInterface;
use Illuminate\Config\Repository;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class CentryApiTokenMiddleware implements MiddlewareInterface, ApplicationAwareInterface
{
use ApplicationAwareTrait;
public function process(Request $request, DelegateInterface $frame)
{
$requestUri = $request->getRequestUri();
if (strpos($requestUri, 'centry/api') !== false) {
if (!$this->isAuthorized($request)) {
return new JsonResponse([
'error' => t('Unauthorized Request'),
], 401);
}
}
/** @var Response $response */
$response = $frame->next($request);
return $response;
}
/**
* Return true is request is authorized.
*
* Meaning that the token in the header equals the one in the config.
*
* @param Request $request
* @return bool
*/
private function isAuthorized(Request $request)
{
$token = $request->headers->get('x-centry-api-token');
if (empty($token)) {
return false;
}
$config = $this->app->make(Repository::class);
return $token === (string) $config->get('centry.api_token');
}
}
|
Remove pointless `_cache` attribute on MemcacheLock class.
If this was doing anything useful, I have no idea what it was. | import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, unique_value):
self.identifier = identifier
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, unique_value)
time.sleep(0)
def release(self):
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
| import random
import time
from datetime import datetime
from django.core.cache import cache
class MemcacheLock(object):
def __init__(self, identifier, cache, unique_value):
self.identifier = identifier
self._cache = cache
self.unique_value = unique_value
@classmethod
def acquire(cls, identifier, wait=True, steal_after_ms=None):
start_time = datetime.utcnow()
unique_value = random.randint(1, 100000)
while True:
acquired = cache.add(identifier, unique_value)
if acquired:
return cls(identifier, cache, unique_value)
elif not wait:
return None
else:
# We are waiting for the lock
if steal_after_ms and (datetime.utcnow() - start_time).total_seconds() * 1000 > steal_after_ms:
# Steal anyway
cache.set(identifier, unique_value)
return cls(identifier, cache, unique_value)
time.sleep(0)
def release(self):
cache = self._cache
# Delete the key if it was ours. There is a race condition here
# if something steals the lock between the if and the delete...
if cache.get(self.identifier) == self.unique_value:
cache.delete(self.identifier)
|
Fix for function signature change in 0.4.0 in fetch_access_token | """
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
class LswApiAuth(object):
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
def __call__(self, r):
if path.exists(__token_store__):
with open(__token_store__, 'r') as file:
token = loads(file.read())
if 'expires_at' in token and token['expires_at'] > time():
r.headers['Authorization'] = '{token_type} {access_token}'.format(**token)
return r
token = fetch_access_token(__auth_token_url__, self.client_id, self.client_secret)
with open(__token_store__, 'w') as file:
file.write(dumps(token))
r.headers['Authorization'] = '{token_type} {access_token}'.format(**token)
return r
class ApiAuthPlugin(AuthPlugin):
name = 'LswApi Oauth'
auth_type = 'lswapi'
description = 'LeaseWeb Api Oauth Authentication'
def get_auth(self, username, password):
return LswApiAuth(username, password)
| """
LswApi auth plugin for HTTPie.
"""
from json import loads, dumps
from time import time
from os import path
from lswapi import __auth_token_url__, __token_store__, fetch_access_token
from requests import post
from httpie.plugins import AuthPlugin
class LswApiAuth(object):
def __init__(self, client_id, client_secret):
self.client_id = client_id
self.client_secret = client_secret
def __call__(self, r):
if path.exists(__token_store__):
with open(__token_store__, 'r') as file:
token = loads(file.read())
if 'expires_at' in token and token['expires_at'] > time():
r.headers['Authorization'] = '{token_type} {access_token}'.format(**token)
return r
token = fetch_access_token(self.client_id, self.client_secret, __auth_token_url__)
with open(__token_store__, 'w') as file:
file.write(dumps(token))
r.headers['Authorization'] = '{token_type} {access_token}'.format(**token)
return r
class ApiAuthPlugin(AuthPlugin):
name = 'LswApi Oauth'
auth_type = 'lswapi'
description = 'LeaseWeb Api Oauth Authentication'
def get_auth(self, username, password):
return LswApiAuth(username, password)
|
Set the role to button instead of tab | import 'accordion/src/accordion.js';
(function() {
"use strict";
document.querySelectorAll('.accordion').forEach(function(item) {
new Accordion(item, {
onToggle: function(target){
// Only allow one accordion item open at time
target.accordion.folds.forEach(fold => {
if(fold !== target) {
fold.open = false;
}
});
// Allow the content to be shown if its open or hide it when closed
target.content.classList.toggle('hidden')
},
enabledClass: 'enabled'
});
// Hide all accordion content from the start so content inside it isn't part of the tabindex
item.querySelectorAll('.content').forEach(function(item) {
item.classList.add('hidden');
});
// Remove the role="tablist" since it is not needed
item.removeAttribute('role');
item.querySelectorAll('li a:first-child').forEach(function(item) {
item.setAttribute('role', 'button');
});
});
document.querySelectorAll('ul.accordion > li').forEach(function(item) {
// Apply the required content fold afterwards to simplify the html
item.querySelector('div').classList.add('fold');
});
})();
| import 'accordion/src/accordion.js';
(function() {
"use strict";
document.querySelectorAll('.accordion').forEach(function(item) {
new Accordion(item, {
onToggle: function(target){
// Only allow one accordion item open at time
target.accordion.folds.forEach(fold => {
if(fold !== target) {
fold.open = false;
}
});
// Allow the content to be shown if its open or hide it when closed
target.content.classList.toggle('hidden')
},
enabledClass: 'enabled'
});
// Hide all accordion content from the start so content inside it isn't part of the tabindex
item.querySelectorAll('.content').forEach(function(item) {
item.classList.add('hidden');
});
// Remove the role="tablist" since it is not needed
item.removeAttribute('role');
});
document.querySelectorAll('ul.accordion > li').forEach(function(item) {
// Apply the required content fold afterwards to simplify the html
item.querySelector('div').classList.add('fold');
});
})();
|
Fix for CI comment
- this._super();
+ this._super(...arguments); | import Ember from 'ember'
import _ from 'lodash/lodash'
export default Ember.Component.extend({
classNames: ['frost-pods'],
classNameBindings: ['orientation'],
orientation: 'vertical',
podNames: Ember.computed('podStack.[]', function () {
return _.dropRight(this.get('podStack').map(function (entry) {
return entry.alias
}), 1)
}),
podLayerAlias: Ember.computed('podStack.[]', function () {
return this.get('podStack.lastObject.alias')
}),
podStack: null,
podLayer: Ember.computed('podStack.[]', function () {
let podLayer = {}
podLayer[this.get('podStack.lastObject.id')] = true
return podLayer
}),
init() {
this._super(...arguments);
this.set('podStack', Ember.A())
this.get('podStack').addObject({
id: 'root',
alias: 'NodeD'
})
},
actions: {
openPod (id, alias) {
this.get('podStack').addObject({
id: id,
alias: alias
})
},
closePod () {
this.get('podStack').popObject()
},
changePod (pod) {
_.dropRightWhile(this.get('podStack'), (n) => {
if (n.alias !== pod) {
this.get('podStack').popObject()
return true
}
return false
})
}
}
})
| import Ember from 'ember'
import _ from 'lodash/lodash'
export default Ember.Component.extend({
classNames: ['frost-pods'],
classNameBindings: ['orientation'],
orientation: 'vertical',
podNames: Ember.computed('podStack.[]', function () {
return _.dropRight(this.get('podStack').map(function (entry) {
return entry.alias
}), 1)
}),
podLayerAlias: Ember.computed('podStack.[]', function () {
return this.get('podStack.lastObject.alias')
}),
podStack: null,
podLayer: Ember.computed('podStack.[]', function () {
let podLayer = {}
podLayer[this.get('podStack.lastObject.id')] = true
return podLayer
}),
init() {
this._super();
this.set('podStack', Ember.A())
this.get('podStack').addObject({
id: 'root',
alias: 'NodeD'
})
},
actions: {
openPod (id, alias) {
this.get('podStack').addObject({
id: id,
alias: alias
})
},
closePod () {
this.get('podStack').popObject()
},
changePod (pod) {
_.dropRightWhile(this.get('podStack'), (n) => {
if (n.alias !== pod) {
this.get('podStack').popObject()
return true
}
return false
})
}
}
})
|
Add method that returns Birth based on age | package sizebay.catalog.client.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import static java.time.LocalDateTime.now;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProfileIdentification implements Serializable {
private static final BigDecimal DAYS_OF_YEAR = new BigDecimal(365.2425D);
long id;
String userId;
String name;
String gender;
int age;
int weight;
int height;
int bodyShapeChest;
int bodyShapeWaist;
int bodyShapeHip;
int footShape;
UserProfileMeasures measures;
UserProfileProduct product;
public static UserProfileIdentification empty() {
UserProfileIdentification profile = new UserProfileIdentification();
UserProfileMeasures measures = UserProfileMeasures.empty();
UserProfileProduct product = UserProfileProduct.empty();
profile.setName("Você");
profile.setAge(0);
profile.setWeight(0);
profile.setHeight(0);
profile.setBodyShapeChest(-99);
profile.setBodyShapeWaist(-99);
profile.setBodyShapeHip(-99);
profile.setFootShape(-99);
profile.setMeasures(measures);
profile.setProduct(product);
return profile;
}
public Date getBirth(int age) {
final int days = new BigDecimal(age).multiply(DAYS_OF_YEAR).intValue();
final ZonedDateTime then = now().minusDays(days).atZone(ZoneId.systemDefault());
return ( Date.from(then.toInstant()));
}
}
| package sizebay.catalog.client.model;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
@Data
@Accessors(chain = true)
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class UserProfileIdentification implements Serializable {
long id;
String userId;
String name;
String gender;
int age;
int weight;
int height;
int bodyShapeChest;
int bodyShapeWaist;
int bodyShapeHip;
int footShape;
UserProfileMeasures measures;
UserProfileProduct product;
public static UserProfileIdentification empty() {
UserProfileIdentification profile = new UserProfileIdentification();
UserProfileMeasures measures = UserProfileMeasures.empty();
UserProfileProduct product = UserProfileProduct.empty();
profile.setName("Você");
profile.setAge(0);
profile.setWeight(0);
profile.setHeight(0);
profile.setBodyShapeChest(-99);
profile.setBodyShapeWaist(-99);
profile.setBodyShapeHip(-99);
profile.setFootShape(-99);
profile.setMeasures(measures);
profile.setProduct(product);
return profile;
}
}
|
Add one more event button | $(document).ready(function(){
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var interactiveBrowse_humanAndEcosystems = d3.select("#interactiveBrowse_humanAndEcosystems");
var toxicity = interactiveBrowse_humanAndEcosystems.append("rect")
.attr("x", 590)
.attr("y", 180)
.attr("width", 220)
.attr("height", 70)
.attr("id", "human/livestock toxicity")
.attr("type_cvterm_id", "480")
.style("opacity", 0.01)
.style("fill", "#fff")
.style("cursor", "pointer")
.on("click", function(){
displayPage(d3.select(this).attr("type_cvterm_id"));
});
var plantPropMethod = interactiveBrowse_humanAndEcosystems.append("rect")
.attr("x", 200)
.attr("y", 650)
.attr("width", 220)
.attr("height", 70)
.attr("id", "plant propagation method")
.attr("type_cvterm_id", "515")
.style("opacity", 0.01)
.style("fill", "#fff")
.style("cursor", "pointer")
.on("click", function(){
displayPage(d3.select(this).attr("type_cvterm_id"));
});
function displayPage(traitId){
var resultPage = WebRoot+"/trait/details/byId/"+traitId;
$.fancybox.open({
type: 'iframe',
href: resultPage,
minWidth: 1000,
maxWidth: 1000,
maxHeight: 800,
minHeight: 800
});
}
});
| $(document).ready(function(){
var div = d3.select("body").append("div")
.attr("class", "tooltip")
.style("opacity", 0);
var interactiveBrowse_humanAndEcosystems = d3.select("#interactiveBrowse_humanAndEcosystems");
var toxicity = interactiveBrowse_humanAndEcosystems.append("rect")
.attr("x", 590)
.attr("y", 180)
.attr("width", 220)
.attr("height", 70)
.attr("id", "human/livestock toxicity")
.attr("type_cvterm_id", "480")
.style("opacity", 0.01)
.style("fill", "#fff")
.style("cursor", "pointer")
.on("click", function(){
displayPage(d3.select(this).attr("type_cvterm_id"));
});
function displayPage(traitId){
var resultPage = WebRoot+"/trait/details/byId/"+traitId;
$.fancybox.open({
type: 'iframe',
href: resultPage,
minWidth: 1000,
maxWidth: 1000,
maxHeight: 800,
minHeight: 800
});
}
});
|
Add ActionBar title on QnaBuilder | package zero.zd.zquestionnaire;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class QnaBuilderActivity extends AppCompatActivity {
public static Intent getStartIntent(Context context) {
return new Intent(context, QnaBuilderActivity.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qna_builder);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setTitle("QnA Builder");
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_qna_builder, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
// @TODO add action to write to a file
break;
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickAdd(View view) {
// @TODO add action to add QnA
Toast.makeText(QnaBuilderActivity.this, "ADD!!!", Toast.LENGTH_SHORT).show();
}
}
| package zero.zd.zquestionnaire;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
public class QnaBuilderActivity extends AppCompatActivity {
public static Intent getStartIntent(Context context) {
return new Intent(context, QnaBuilderActivity.class);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qna_builder);
if (getSupportActionBar() != null)
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_qna_builder, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_save:
// @TODO add action to write to a file
break;
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onClickAdd(View view) {
// @TODO add action to add QnA
Toast.makeText(QnaBuilderActivity.this, "ADD!!!", Toast.LENGTH_SHORT).show();
}
}
|
Update SdlArtwork test to have reusable equalTest | package com.smartdevicelink.managers.file;
import com.smartdevicelink.AndroidTestCase2;
import com.smartdevicelink.managers.file.filetypes.SdlArtwork;
import com.smartdevicelink.managers.file.filetypes.SdlFile;
import com.smartdevicelink.proxy.rpc.enums.StaticIconName;
import com.smartdevicelink.test.Test;
public class SdlArtworkTests extends AndroidTestCase2 {
public void testClone(){
SdlArtwork original = Test.GENERAL_ARTWORK;
SdlArtwork clone = original.clone();
equalTest(original, clone);
SdlArtwork artwork = new SdlArtwork(StaticIconName.ALBUM);
assertNotNull(artwork);
SdlArtwork staticIconClone = artwork.clone();
assertNotNull(staticIconClone);
assertTrue(clone instanceof Cloneable);
assertTrue(artwork instanceof Cloneable);
}
public static boolean equalTest(SdlArtwork original, SdlArtwork clone){
assertNotNull(original);
assertNotNull(clone);
assertNotSame(original,clone);
assertEquals(original.getResourceId(), clone.getResourceId());
assertEquals(original.getFileData(), clone.getFileData());
assertNotNull(original.getImageRPC());
assertNotNull(clone.getImageRPC());
assertNotSame(original.getImageRPC(),clone.getImageRPC());
assertEquals(original.getImageRPC().getIsTemplate(), clone.getImageRPC().getIsTemplate());
assertEquals(original.getImageRPC().getValue(), clone.getImageRPC().getValue());
assertEquals(original.getImageRPC().getImageType(), clone.getImageRPC().getImageType());
return true;
}
}
| package com.smartdevicelink.managers.file;
import com.smartdevicelink.AndroidTestCase2;
import com.smartdevicelink.managers.file.filetypes.SdlArtwork;
import com.smartdevicelink.managers.file.filetypes.SdlFile;
import com.smartdevicelink.proxy.rpc.enums.StaticIconName;
import com.smartdevicelink.test.Test;
public class SdlArtworkTests extends AndroidTestCase2 {
public void testClone(){
SdlArtwork original = Test.GENERAL_ARTWORK;
SdlArtwork clone = original.clone();
assertNotNull(clone);
assertNotSame(original,clone);
assertEquals(original.getResourceId(), clone.getResourceId());
assertEquals(original.getFileData(), clone.getFileData());
assertNotNull(original.getImageRPC());
assertNotNull(clone.getImageRPC());
assertNotSame(original.getImageRPC(),clone.getImageRPC());
assertEquals(original.getImageRPC().getIsTemplate(), clone.getImageRPC().getIsTemplate());
assertEquals(original.getImageRPC().getValue(), clone.getImageRPC().getValue());
assertEquals(original.getImageRPC().getImageType(), clone.getImageRPC().getImageType());
SdlArtwork artwork = new SdlArtwork(StaticIconName.ALBUM);
assertNotNull(artwork);
SdlArtwork staticIconClone = artwork.clone();
assertNotNull(staticIconClone);
assertTrue(clone instanceof Cloneable);
assertTrue(artwork instanceof Cloneable);
}
}
|
Remove extraneous OSC message listener in SoundTestController | 'use strict';
angular.module('core').controller('SoundTestController', ['$scope', 'TrialData',
function($scope, TrialData) {
/* global io */
var socket = io();
// Send a message to Max to start the sound test
socket.emit('sendOSCMessage', {
oscType: 'message',
address: '/eim/control/soundTest',
args: [
{
type: 'integer',
value: 1
},
{
type: 'string',
value: '' + TrialData.data.metadata.session_number
}
]
});
// Function to send a message to Max to stop the sound test
$scope.stopSoundTest = function() {
socket.emit('sendOSCMessage', {
oscType: 'message',
address: '/eim/control/soundTest',
args: [
{
type: 'integer',
value: 0
},
{
type: 'string',
value: '' + TrialData.data.metadata.session_number
}
]
});
};
// Send stop sound test message when controller is destroyed
$scope.$on('$destroy', $scope.stopSoundTest);
$scope.trialDataJson = function() {
return TrialData.toJson();
};
}
]); | 'use strict';
angular.module('core').controller('SoundTestController', ['$scope', 'TrialData',
function($scope, TrialData) {
/* global io */
var socket = io();
socket.on('oscMessageSent', function(data) {
console.log('socket "oscMessageSent" event received with data: ' + data);
});
socket.emit('sendOSCMessage', {
oscType: 'message',
address: '/eim/control/soundTest',
args: [
{
type: 'integer',
value: 1
},
{
type: 'string',
value: '' + TrialData.data.metadata.session_number
}
]
});
$scope.stopSoundTest = function() {
socket.emit('sendOSCMessage', {
oscType: 'message',
address: '/eim/control/soundTest',
args: [
{
type: 'integer',
value: 0
},
{
type: 'string',
value: '' + TrialData.data.metadata.session_number
}
]
});
};
// Send stop sound test message when controller is destroyed
$scope.$on('$destroy', $scope.stopSoundTest);
$scope.trialDataJson = function() {
return TrialData.toJson();
};
}
]); |
Put weaker requirements on Archive.org service | # -*- coding: utf-8 -*-
"""
This module contains Service implementation of Archive.org.
http://archive.org
"""
from . import Service, JSONMixin
from six import text_type
from tornado.httpclient import HTTPRequest
##############################################################################
class ArchiveOrg(JSONMixin, Service):
"""
Implementation of Service which is intended to parse Archive.org.
"""
def generate_request(self):
resource = self.url.rstrip("/").rpartition("/")[-1]
return HTTPRequest(
"http://archive.org/metadata/" + resource + "/files/",
use_gzip=True,
headers=dict(Accept="application/json")
)
def parse(self, response):
converted_response = self.convert_response(response)
tracks = {}
required_fields = ("title", "track", "album")
for file_ in converted_response["result"]:
if file_.get("source") != "original":
continue
if not all(field in file_ for field in required_fields):
continue
track = int(file_["track"])
title = text_type(file_["title"])
length = text_type(file_.get("length", ""))
if length and ":" not in length:
length = int(float(length))
length = self.second_to_timestamp(length)
length = self.normalize_track_length(length)
tracks[track] = (title, length)
if not tracks:
raise Exception("Empty list")
return tuple(data for track, data in sorted(tracks.iteritems())) | # -*- coding: utf-8 -*-
"""
This module contains Service implementation of Archive.org.
http://archive.org
"""
from . import Service, JSONMixin
from six import text_type
from tornado.httpclient import HTTPRequest
##############################################################################
class ArchiveOrg(JSONMixin, Service):
"""
Implementation of Service which is intended to parse Archive.org.
"""
def generate_request(self):
resource = self.url.rstrip("/").rpartition("/")[-1]
return HTTPRequest(
"http://archive.org/metadata/" + resource + "/files/",
use_gzip=True,
headers=dict(Accept="application/json")
)
def parse(self, response):
converted_response = self.convert_response(response)
tracks = {}
required_fields = ("title", "track", "length", "album")
for file_ in converted_response["result"]:
if file_.get("source") != "original":
continue
if not all(field in file_ for field in required_fields):
continue
track = int(file_["track"])
title = text_type(file_["title"])
length = text_type(file_["length"])
if ":" not in length:
length = int(float(length))
length = self.second_to_timestamp(length)
length = self.normalize_track_length(length)
tracks[track] = (title, length)
if not tracks:
raise Exception("Empty list")
return tuple(data for track, data in sorted(tracks.iteritems())) |
Return a simple object when an entity is picked | angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead'])
.directive('entityPicker', function() {
var tpl =
'<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' +
'<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>';
return {
restrict: 'E',
transclude: true,
scope: {
url: '=',
subject: '='
},
template: tpl,
controller: function($scope, $http, $attrs) {
// Get the object by search term
$scope.getObject = function(term) {
return $http.get($scope.url, {
params: {
term: term
}
}).then(function(response){
return response.data.map(function(item){
return item;
});
});
};
// Select the object
$scope.onSelect = function(item, model, label) {
if (angular.isUndefined($scope.subject.right.value)) {
$scope.subject.right.value = [];
}
var item = {id:item.id, name:item.name};
if ($scope.subject.right.value.indexOf(item) == -1) {
$scope.subject.right.value.push(item);
}
$scope.search = null;
};
}
};
})
;
| angular.module('OpiferEntityPicker', ['ui.bootstrap.typeahead'])
.directive('entityPicker', function() {
var tpl =
'<input type="text" ng-model="search" typeahead="object.name for object in getObject($viewValue)" typeahead-on-select="onSelect($item, $model, $label)" typeahead-loading="loadingLocations" class="form-control">' +
'<i ng-show="loadingLocations" class="glyphicon glyphicon-refresh"></i>';
return {
restrict: 'E',
transclude: true,
scope: {
url: '=',
subject: '='
},
template: tpl,
controller: function($scope, $http, $attrs) {
// Get the object by search term
$scope.getObject = function(term) {
return $http.get($scope.url, {
params: {
term: term
}
}).then(function(response){
return response.data.map(function(item){
return item;
});
});
};
// Select the object
$scope.onSelect = function(item, model, label) {
if (angular.isUndefined($scope.subject.right.value)) {
$scope.subject.right.value = [];
}
if ($scope.subject.right.value.indexOf(item.id) == -1) {
$scope.subject.right.value.push(item.id);
}
$scope.search = null;
};
}
};
})
;
|
Add assertions for error logging | (function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
it('should log an error if a route is not found');
it('should log an error if params are required and missing');
it('should log an error if params keys are not found');
});
});
}());
| (function () {
'use strict';
var reverseUrl, $route;
var routeMock = {};
routeMock.routes = {
'/testRoute1/': {
controller: 'TestController1',
originalPath: '/test-route-1/'
},
'/testRoute1/:params/': {
controller: 'TestController1',
originalPath: '/test-route-1/:param/'
},
'/testRoute2/': {
name: 'TestRoute2',
originalPath: '/test-route-2/'
},
};
describe('Unit: angular-reverse-url', function () {
beforeEach(module('angular-reverse-url', function ($provide) {
$provide.value('$route', routeMock);
}));
describe('reverseUrl filter', function () {
beforeEach(inject(function ($injector) {
$route = $injector.get('$route')
reverseUrl = $injector.get('$filter')('reverseUrl');
}));
it('should correctly match to a basic route by controller', function () {
expect(reverseUrl('TestController1')).toEqual('#/test-route-1/');
});
it('should correctly match to a basic route by name', function () {
expect(reverseUrl('TestRoute2')).toEqual('#/test-route-2/');
});
it('should correctly match to a route with params', function () {
expect(reverseUrl('TestController1', {param: 'foobar'})).toEqual('#/test-route-1/foobar/');
});
});
});
}());
|
Add tests for TCP flow interception | import pytest
from mitmproxy.addons import intercept
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def test_simple():
r = intercept.Intercept()
with taddons.context(r) as tctx:
assert not r.filt
tctx.configure(r, intercept="~q")
assert r.filt
assert tctx.options.intercept_active
with pytest.raises(exceptions.OptionsError):
tctx.configure(r, intercept="~~")
tctx.configure(r, intercept=None)
assert not r.filt
assert not tctx.options.intercept_active
tctx.configure(r, intercept="~s")
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert f.intercepted
f = tflow.tflow(resp=False)
tctx.cycle(r, f)
assert not f.intercepted
f = tflow.tflow(resp=True)
r.response(f)
assert f.intercepted
tctx.configure(r, intercept_active=False)
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert not f.intercepted
tctx.configure(r, intercept_active=True)
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert f.intercepted
tctx.configure(r, intercept_active=False)
f = tflow.ttcpflow()
tctx.cycle(r, f)
assert not f.intercepted
tctx.configure(r, intercept_active=True)
f = tflow.ttcpflow()
tctx.cycle(r, f)
assert f.intercepted
| import pytest
from mitmproxy.addons import intercept
from mitmproxy import exceptions
from mitmproxy.test import taddons
from mitmproxy.test import tflow
def test_simple():
r = intercept.Intercept()
with taddons.context(r) as tctx:
assert not r.filt
tctx.configure(r, intercept="~q")
assert r.filt
assert tctx.options.intercept_active
with pytest.raises(exceptions.OptionsError):
tctx.configure(r, intercept="~~")
tctx.configure(r, intercept=None)
assert not r.filt
assert not tctx.options.intercept_active
tctx.configure(r, intercept="~s")
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert f.intercepted
f = tflow.tflow(resp=False)
tctx.cycle(r, f)
assert not f.intercepted
f = tflow.tflow(resp=True)
r.response(f)
assert f.intercepted
tctx.configure(r, intercept_active=False)
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert not f.intercepted
tctx.configure(r, intercept_active=True)
f = tflow.tflow(resp=True)
tctx.cycle(r, f)
assert f.intercepted
|
Handle response status and headers in default adapter | <?php
namespace Hochstrasser\Wirecard;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;
abstract class Adapter
{
static function defaultAdapter()
{
return function (RequestInterface $request) {
$headers = [];
foreach ($request->getHeaders() as $header => $values) {
$headers[] = $header.': '.implode(',', $values);
}
$streamContext = stream_context_create([
'http' => [
'method' => $request->getMethod(),
'header' => $headers,
'content' => Psr7\copy_to_string($request->getBody()),
'protocol_version' => $request->getProtocolVersion()
]
]);
$stream = fopen((string) $request->getUri(), 'r', false, $streamContext);
$responseBody = stream_get_contents($stream);
fclose($stream);
$headers = [];
$statusLine = $http_response_header[0];
preg_match('{^HTTP/([0-9\.]+) (\d+) (.+)$}', $statusLine, $matches);
$version = $matches[1];
$status = $matches[2];
$reason = $matches[3];
foreach (array_slice($http_response_header, 1) as $headerLine) {
list($header, $value) = explode(':', $headerLine);
$headers[$header] = explode(';', $value);
}
$response = new Response($status, $headers, $responseBody, $version, $reason);
return $response;
};
}
}
| <?php
namespace Hochstrasser\Wirecard;
use Psr\Http\Message\RequestInterface;
use GuzzleHttp\Psr7\Response;
use GuzzleHttp\Psr7;
abstract class Adapter
{
static function defaultAdapter()
{
return function (RequestInterface $request) {
$headers = [];
foreach ($request->getHeaders() as $header => $values) {
$headers[] = $header.': '.implode(',', $values);
}
$streamContext = stream_context_create([
'http' => [
'method' => $request->getMethod(),
'header' => $headers,
'content' => Psr7\copy_to_string($request->getBody()),
'protocol_version' => $request->getProtocolVersion()
]
]);
$stream = fopen((string) $request->getUri(), 'r', false, $streamContext);
$responseBody = stream_get_contents($stream);
$metadata = stream_get_meta_data($stream);
fclose($stream);
$response = new Response(200, [], $responseBody);
return $response;
};
}
}
|
Add method to create a test container to interface
I've simply forgot that... | <?php
declare(strict_types=1);
namespace Lcobucci\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Definition of how the container builder should behave
*
* @author Luís Otávio Cobucci Oblonczyk <[email protected]>
*/
interface Builder
{
/**
* Changes the generator to handle the files
*/
public function setGenerator(Generator $generator): Builder;
/**
* Add a file to be loaded
*/
public function addFile(string $file): Builder;
/**
* Add a compiler pass
*/
public function addPass(
CompilerPassInterface $pass,
string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION
): Builder;
/**
* Mark the container to be used as development mode
*/
public function useDevelopmentMode(): Builder;
/**
* Configures the dump directory
*/
public function setDumpDir(string $dir): Builder;
/**
* Adds a default parameter
*/
public function setParameter(string $name, $value): Builder;
/**
* Adds a path to load the files
*/
public function addPath(string $path): Builder;
/**
* Configures the container's base class
*/
public function setBaseClass(string $class): Builder;
/**
* Creates the container with the given configuration
*/
public function getContainer(): ContainerInterface;
/**
* Creates a test container with the given configuration
*/
public function getTestContainer(): ContainerInterface;
}
| <?php
declare(strict_types=1);
namespace Lcobucci\DependencyInjection;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PassConfig;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Definition of how the container builder should behave
*
* @author Luís Otávio Cobucci Oblonczyk <[email protected]>
*/
interface Builder
{
/**
* Changes the generator to handle the files
*/
public function setGenerator(Generator $generator): Builder;
/**
* Add a file to be loaded
*/
public function addFile(string $file): Builder;
/**
* Add a compiler pass
*/
public function addPass(
CompilerPassInterface $pass,
string $type = PassConfig::TYPE_BEFORE_OPTIMIZATION
): Builder;
/**
* Mark the container to be used as development mode
*/
public function useDevelopmentMode(): Builder;
/**
* Configures the dump directory
*/
public function setDumpDir(string $dir): Builder;
/**
* Adds a default parameter
*/
public function setParameter(string $name, $value): Builder;
/**
* Adds a path to load the files
*/
public function addPath(string $path): Builder;
/**
* Configures the container's base class
*/
public function setBaseClass(string $class): Builder;
/**
* Creates the container with the given configuration
*/
public function getContainer(): ContainerInterface;
}
|
Disable autocomplete for client_id and client_secret inputs on Wave credentials form | <?php
/**
* Form for Wave credentials.
*
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*/
namespace Wave\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Skyflow\Domain\Users;
class WaveCredentialsType extends AbstractType
{
/**
* The skyflow current logged-in user.
*
* @var Users
*/
protected $user;
/**
* WaveCredentialsType constructor.
*
* @param Users $user The skyflow current logged-in user.
*/
public function __construct(Users $user)
{
$this->user = $user;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('client_id', 'text', array('attr' => array('autocomplete' => 'off')))
->add('client_secret', 'text', array('attr' => array('autocomplete' => 'off')))
->add('sandbox', 'checkbox', array('required' => false));
;
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$form->setData(array(
'client_id' => $this->user->getWaveClientId(),
'client_secret' => $this->user->getWaveClientSecret(),
'sandbox' => $this->user->getWaveSandbox() ? true : false
));
}
public function getName()
{
return 'app_wave_credentials';
}
}
| <?php
/**
* Form for Wave credentials.
*
* @license http://opensource.org/licenses/MIT The MIT License (MIT)
*/
namespace Wave\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Skyflow\Domain\Users;
class WaveCredentialsType extends AbstractType
{
/**
* The skyflow current logged-in user.
*
* @var Users
*/
protected $user;
/**
* WaveCredentialsType constructor.
*
* @param Users $user The skyflow current logged-in user.
*/
public function __construct(Users $user)
{
$this->user = $user;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('client_id','text')
->add('client_secret','text')
->add('sandbox', 'checkbox', array('required' => false));
;
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
$form->setData(array(
'client_id' => $this->user->getWaveClientId(),
'client_secret' => $this->user->getWaveClientSecret(),
'sandbox' => $this->user->getWaveSandbox() ? true : false
));
}
public function getName()
{
return 'app_wave_credentials';
}
}
|
Fix PHP warning when submitting new conversation without any recipient | <?php
namespace FireDIY\PrivateMessageBundle\Validator;
use FireDIY\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator
* @package FireDIY\PrivateMessageBundle\Validator
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/**
* Entry point of the conversation's validation process.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
public static function validate(Conversation $conversation, ExecutionContextInterface $context)
{
self::validateRecipients($conversation, $context);
}
/**
* Make sure the author of the conversation is not sending a message to himself.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
{
// This could be NULL or array.
$recipients = $conversation->getRecipients();
if (is_array($recipients) && in_array($conversation->getAuthor(), $recipients)) {
$context
->buildViolation(self::RECIPIENT_VIOLATION)
->atPath('recipients')
->addViolation();
}
}
}
| <?php
namespace FireDIY\PrivateMessageBundle\Validator;
use FireDIY\PrivateMessageBundle\Entity\Conversation;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
/**
* Class ConversationValidator
* @package FireDIY\PrivateMessageBundle\Validator
*/
class ConversationValidator
{
const RECIPIENT_VIOLATION = 'You cannot send a message to yourself';
/**
* Entry point of the conversation's validation process.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
public static function validate(Conversation $conversation, ExecutionContextInterface $context)
{
self::validateRecipients($conversation, $context);
}
/**
* Make sure the author of the conversation is not sending a message to himself.
*
* @param Conversation $conversation : instance of the conversation to validate.
* @param ExecutionContextInterface $context : instance of the execution context.
*/
private static function validateRecipients(Conversation $conversation, ExecutionContextInterface $context)
{
if (in_array($conversation->getAuthor(), $conversation->getRecipients())) {
$context
->buildViolation(self::RECIPIENT_VIOLATION)
->atPath('recipients')
->addViolation();
}
}
}
|
Add support of s3 path | """
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
import boto3
import botocore
import uuid
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
from data_refinery_common.utils import parse_s3_url
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes. s3:// URLs are also accepted.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
if 's3://' in options["file"]:
bucket, key = parse_s3_url(options["file"])
s3 = boto3.resource('s3')
try:
filepath = "/tmp/input_" + str(uuid.uuid4()) + ".txt"
s3.Bucket(bucket).download_file(key, filepath)
except botocore.exceptions.ClientError as e:
if e.response['Error']['Code'] == "404":
logger.error("The remote file does not exist.")
raise
else:
filepath = options["file"]
with open(filepath) as file:
for accession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
| """
This command will create and run survey jobs for each SRA run accession
in the range from start_accession to end_accession.
"""
from django.core.management.base import BaseCommand
from data_refinery_foreman.surveyor import surveyor
from data_refinery_common.logging import get_and_configure_logger
logger = get_and_configure_logger(__name__)
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument(
"--accession",
type=str,
help=("An SRA run accession. "))
parser.add_argument(
"--file",
type=str,
help=("An optional file listing accession codes.")
)
def handle(self, *args, **options):
if options["accession"] is None and options["file"] is None:
logger.error("You must specify accession or input file.")
return 1
if options["file"]:
with open(options["file"]) as file:
for acession in file:
try:
surveyor.survey_sra_experiment(accession.strip())
except Exception as e:
print(e)
else:
surveyor.survey_sra_experiment(options["accession"])
return 0
|
Fix navigator.languages not supported in IE and Safari | import ActionTypes from '../constants/ActionTypes';
import BaseStore from './BaseStore';
class LocaleStore extends BaseStore {
constructor() {
super();
this.subscribe(() => this._registerToActions.bind(this));
this._locale = 'en';
let locale = localStorage.getItem('locale');
if (locale) {
this._locale = locale;
} else if (navigator.languages && navigator.languages.length > 0) {
let locale = navigator.languages[0];
if (locale.startsWith('es')) {
this._locale = 'es';
}
} else if (navigator.language) {
if (navigator.language.startsWith('es')) {
this._locale = 'es';
}
}
}
_registerToActions(action) {
switch (action.type) {
case ActionTypes.CHANGE_LOCALE:
this._locale = action.locale;
localStorage.setItem('locale', this._locale);
this.emitChange();
break;
default:
break;
}
}
get locale() {
return this._locale;
}
}
export default new LocaleStore();
| import ActionTypes from '../constants/ActionTypes';
import BaseStore from './BaseStore';
class LocaleStore extends BaseStore {
constructor() {
super();
this.subscribe(() => this._registerToActions.bind(this));
this._locale = 'en';
let locale = localStorage.getItem('locale');
if (locale) {
this._locale = locale;
} else if (navigator.languages.length > 0) {
let locale = navigator.languages[0];
if (locale.startsWith('es')) {
this._locale = 'es';
}
} else if (navigator.language) {
if (navigator.language.startsWith('es')) {
this._locale = 'es';
}
}
}
_registerToActions(action) {
switch (action.type) {
case ActionTypes.CHANGE_LOCALE:
this._locale = action.locale;
localStorage.setItem('locale', this._locale);
this.emitChange();
break;
default:
break;
}
}
get locale() {
return this._locale;
}
}
export default new LocaleStore();
|
Fix image grouping in gallery view | from django.shortcuts import render
from .models import Image
from .forms import ImageForm
from django.views.generic import CreateView, DeleteView, UpdateView, ListView, View
from django.shortcuts import redirect, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
class ImageDeleteView(PermissionRequiredMixin, DeleteView):
model = Image
success_url = '/files/images'
permission_required = "files.delete_image"
class ImageListView(PermissionRequiredMixin, ListView):
queryset = Image.objects.order_by('img_category', '-time')
template_name = 'files/images.html'
permission_required = 'files.view_image'
context_object_name = 'images'
class ImageView(PermissionRequiredMixin, View):
permission_required = "files.view_image"
def get(self, request, *args, **kwargs):
image = get_object_or_404(Image, pk=kwargs['pk'])
return HttpResponseRedirect('/media/'+str(image.file))
@login_required()
def imageUpload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES, prefix='img')
if form.is_valid():
image = form.save(commit=False)
image.save()
return render(request, 'files/single-image.html', {'image':image})
else:
return HttpResponse(form.errors)
else:
return HttpResponseRedirect('/')
| from django.shortcuts import render
from .models import Image
from .forms import ImageForm
from django.views.generic import CreateView, DeleteView, UpdateView, ListView, View
from django.shortcuts import redirect, get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import PermissionRequiredMixin
class ImageDeleteView(PermissionRequiredMixin, DeleteView):
model = Image
success_url = '/files/images'
permission_required = "files.delete_image"
class ImageListView(PermissionRequiredMixin, ListView):
queryset = Image.objects.order_by('category', '-time')
template_name = 'files/images.html'
permission_required = 'files.view_image'
context_object_name = 'images'
class ImageView(PermissionRequiredMixin, View):
permission_required = "files.view_image"
def get(self, request, *args, **kwargs):
image = get_object_or_404(Image, pk=kwargs['pk'])
return HttpResponseRedirect('/media/'+str(image.file))
@login_required()
def imageUpload(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES, prefix='img')
if form.is_valid():
image = form.save(commit=False)
image.save()
return render(request, 'files/single-image.html', {'image':image})
else:
return HttpResponse(form.errors)
else:
return HttpResponseRedirect('/')
|
feat: Modify script which split your region in smaller sample | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow
import os
OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file
SAMPLE_FILE = "sample_sfb.osm"
k = 20 # Parameter: take every k-th top level element
def get_element(osm_file, tags=('node', 'way', 'relation')):
"""Yield element if it is the right type of tag
Reference:
http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python
"""
context = iter(ET.iterparse(osm_file, events=('start', 'end')))
_, root = next(context)
for event, elem in context:
if event == 'end' and elem.tag in tags:
yield elem
root.clear()
def main():
os.chdir('./data')
with open(SAMPLE_FILE, 'wb') as output:
output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
output.write('<osm>\n ')
# Write every kth top level element
for i, element in enumerate(get_element(OSM_FILE)):
if i % k == 0:
output.write(ET.tostring(element, encoding='utf-8'))
output.write('</osm>')
if __name__ == '__main__':
main() | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import xml.etree.ElementTree as ET # Use cElementTree or lxml if too slow
import os
OSM_FILE = "san-francisco-bay_california.osm" # Replace this with your osm file
SAMPLE_FILE = "sample_sfb.osm"
k = 20 # Parameter: take every k-th top level element
def get_element(osm_file, tags=('node', 'way', 'relation')):
"""Yield element if it is the right type of tag
Reference:
http://stackoverflow.com/questions/3095434/inserting-newlines-in-xml-file-generated-via-xml-etree-elementtree-in-python
"""
context = iter(ET.iterparse(osm_file, events=('start', 'end')))
_, root = next(context)
for event, elem in context:
if event == 'end' and elem.tag in tags:
yield elem
root.clear()
def main():
os.chdir('./data')
with open(SAMPLE_FILE, 'wb') as output:
output.write('<?xml version="1.0" encoding="UTF-8"?>\n')
output.write('<osm>\n ')
# Write every kth top level element
for i, element in enumerate(get_element(OSM_FILE)):
if i % k == 0:
output.write(ET.tostring(element, encoding='utf-8'))
output.write('</osm>') |
Append lang mock to the end of file to not make source map being invalid. | var vfs = require('enb/lib/fs/async-fs');
module.exports = require('enb/lib/build-flow').create()
.name('mock-lang-js.js')
.target('target', '?.js')
.useSourceFilename('source', '?.lang.js')
.builder(function (source) {
return vfs.read(source, 'utf8')
.then(function (content) {
var mock = [
'(function(global, bem_) {',
' if(bem_.I18N) return;',
' global.BEM = bem_;',
' var i18n = bem_.I18N = function(keyset, key) {',
' return key;',
' };',
' i18n.keyset = function() { return i18n }',
' i18n.key = function(key) { return key }',
' i18n.lang = function() { return }',
'})(this, typeof BEM === \'undefined\' ? {} : BEM);'
].join('\n'),
mapIndex = content.lastIndexOf('//# sourceMappingURL='),
map;
// if there is a #sourceMappingURL pragma append
// the mock before it so the source map will be
// valid. We can't insert it in the beginning because
// source map locations will point to the wrong lines.
if (mapIndex !== -1) {
map = content.substring(mapIndex);
content = content.substring(0, mapIndex);
}
return [content, mock, map].join('\n');
});
})
.createTech();
| var vfs = require('enb/lib/fs/async-fs');
module.exports = require('enb/lib/build-flow').create()
.name('mock-lang-js.js')
.target('target', '?.js')
.useSourceFilename('source', '?.lang.js')
.builder(function (source) {
return vfs.read(source, 'utf8')
.then(function (content) {
var mock = [
'(function(global, bem_) {',
' if(bem_.I18N) return;',
' global.BEM = bem_;',
' var i18n = bem_.I18N = function(keyset, key) {',
' return key;',
' };',
' i18n.keyset = function() { return i18n }',
' i18n.key = function(key) { return key }',
' i18n.lang = function() { return }',
'})(this, typeof BEM === \'undefined\' ? {} : BEM);'
].join('\n');
return [mock, content].join('\n');
});
})
.createTech();
|
Switch to using options, as with newer module definitions
- Also allows easier extension of existing objects within the option set | define([
'common/collections/single-timeseries'
],
function (Collection) {
return {
requiresSvg: true,
hasDatePicker: true,
collectionClass: Collection,
collectionOptions: function () {
var options = {};
options.numeratorMatcher = new RegExp(this.model.get('numerator-matcher')),
options.denominatorMatcher = new RegExp(this.model.get('denominator-matcher')),
options.matchingAttribute = this.model.get('group-by'),
options.valueAttr = this.model.get('value-attribute') || 'uniqueEvents',
options.axisPeriod = this.model.get('axis-period') || this.model.get('period'),
options.axes = _.merge({
x: {
label: 'Date of Application',
key: ['_start_at', '_end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: 'uniqueEvents',
format: this.model.get('format-options') || 'integer'
}
]
}, this.model.get('axes')),
options.defaultValue = this.model.get('default-value')
return options;
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
totalAttr: 'mean',
formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
};
}
};
});
| define([
'common/collections/single-timeseries'
],
function (Collection) {
return {
requiresSvg: true,
hasDatePicker: true,
collectionClass: Collection,
collectionOptions: function () {
return {
numeratorMatcher: new RegExp(this.model.get('numerator-matcher')),
denominatorMatcher: new RegExp(this.model.get('denominator-matcher')),
matchingAttribute: this.model.get('group-by'),
valueAttr: this.model.get('value-attribute') || 'uniqueEvents',
axisPeriod: this.model.get('axis-period') || this.model.get('period'),
axes: _.merge({
x: {
label: 'Date of Application',
key: ['_start_at', '_end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: 'uniqueEvents',
format: this.model.get('format-options') || 'integer'
}
]
}, this.model.get('axes')),
defaultValue: this.model.get('default-value')
};
},
visualisationOptions: function () {
return {
valueAttr: 'uniqueEvents',
totalAttr: 'mean',
formatOptions: this.model.get('format-options') || { type: 'number', magnitude: true, pad: true }
};
}
};
});
|
Update license text and classifiers and README ext | ##############################################################################
#
# Copyright Benji York and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Apache License, Version
# 2.0.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Setup for manuel package."""
from setuptools import setup, find_packages
long_description = (
open('README.rst').read()
+ '\n\n'
+ open('CHANGES.txt').read()
)
tests_require = ['zope.testing']
setup(
name='manuel',
version='0',
url = 'http://pypi.python.org/pypi/manuel',
packages=find_packages('src'),
package_dir={'':'src'},
zip_safe=False,
author='Benji York',
author_email='[email protected]',
description='Manuel lets you build tested documentation.',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
'License :: OSI Approved :: Apache Software License',
],
license='Apache Software License, Version 2.0',
extras_require={
'tests': tests_require,
},
tests_require = tests_require,
test_suite = 'manuel.tests.test_suite',
install_requires=[
'setuptools',
'six',
],
include_package_data=True,
long_description = long_description,
)
| ##############################################################################
#
# Copyright Benji York and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Apache License, Version
# 2.0.
#
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Setup for manuel package."""
from setuptools import setup, find_packages
long_description = (
open('README.txt').read()
+ '\n\n'
+ open('CHANGES.txt').read()
)
tests_require = ['zope.testing']
setup(
name='manuel',
version='0',
url = 'http://pypi.python.org/pypi/manuel',
packages=find_packages('src'),
package_dir={'':'src'},
zip_safe=False,
author='Benji York',
author_email='[email protected]',
description='Manuel lets you build tested documentation.',
classifiers=[
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 3',
],
license='ZPL',
extras_require={
'tests': tests_require,
},
tests_require = tests_require,
test_suite = 'manuel.tests.test_suite',
install_requires=[
'setuptools',
'six',
],
include_package_data=True,
long_description = long_description,
)
|
Split the transformation to File's. | package org.jboss.loom.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.tools.ant.DirectoryScanner;
/**
* Usage:
*
* <pre><code>files = new DirScanner("** /foo/*.bar").list( baseDir );</code></pre>
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class DirScanner {
private String pattern;
public DirScanner( String pattern ) {
if( pattern == null )
throw new IllegalArgumentException("pattern can't be null.");
this.pattern = pattern;
}
public List<String> list( File dirToScan ) throws IOException {
if( dirToScan == null )
throw new IllegalArgumentException("dirToScan can't be null.");
DirectoryScanner ds = new DirectoryScanner();
String[] includes = { this.pattern };
//String[] excludes = {"modules\\*\\**"};
ds.setIncludes(includes);
//ds.setExcludes(excludes);
ds.setBasedir( dirToScan );
//ds.setCaseSensitive(true);
ds.scan();
String[] matches = ds.getIncludedFiles();
return Arrays.asList( matches );
}
public List<File> listAsFiles( File dirToScan ) throws IOException {
List<String> matches = this.list( dirToScan );
List<File> files = new ArrayList(matches.size());
for( String path : matches ) {
files.add( new File( path ) );
}
return files;
}
}// class
| package org.jboss.loom.utils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.tools.ant.DirectoryScanner;
/**
* Usage:
*
* <pre><code>files = new DirScanner("** /foo/*.bar").list( baseDir );</code></pre>
*
* @author Ondrej Zizka, ozizka at redhat.com
*/
public class DirScanner {
private String pattern;
public DirScanner( String pattern ) {
if( pattern == null )
throw new IllegalArgumentException("pattern can't be null.");
this.pattern = pattern;
}
public List<File> list( File dirToScan ) throws IOException {
if( dirToScan == null )
throw new IllegalArgumentException("dirToScan can't be null.");
DirectoryScanner ds = new DirectoryScanner();
String[] includes = { this.pattern };
//String[] excludes = {"modules\\*\\**"};
ds.setIncludes(includes);
//ds.setExcludes(excludes);
ds.setBasedir( dirToScan );
//ds.setCaseSensitive(true);
ds.scan();
String[] matches = ds.getIncludedFiles();
List<File> files = new ArrayList(matches.length);
for (int i = 0; i < matches.length; i++) {
files.add( new File(matches[i]) );
}
return files;
}
}// class
|
Fix minor issues in CollisionManager | "use strict";
function CollisionManager() {
var objects = [];
this.intersect = function(object1, object2) {
var pos1 = object1.getLocation();
var pos2 = object2.getLocation();
return (((pos1.x >= pos2.x && pos1.x <= pos2.x + pos2.width) &&
(pos1.y >= pos2.y && pos1.y <= pos2.y + pos2.height)) ||
((pos2.x >= pos1.x && pos2.x <= pos1.x + pos1.width) &&
(pos2.y >= pos1.y && pos2.y <= pos1.y + pos1.height)));
}
this.addObject = function(object) {
objects.push(object);
}
this.findCollisions = function(object) {
var collidedWith = [];
for (var i = 0; i < objects.length; i++) {
if (object.settings.id.value != objects[i].settings.id.value &&
this.intersect(object, objects[i]))
collidedWith.push(objects[i].settings.id.value);
}
if (collidedWith.length > 0) {
console.log('Found collision');
object.onCollision({
'collidedWith': collidedWith
});
}
}
}
| "use strict";
function CollisionManager() {
var objects = [];
this.intersect = function(object1, object2) {
var pos1 = object1.getLocation();
var pos2 = object2.getLocation();
return (((pos1.x >= pos2.x && pos1.x <= pos2.x + pos2.width) &&
(pos1.y >= pos2.y && pos1.y <= pos2.y + pos2.height)) ||
((pos2.x >= pos1.x && pos2.x <= pos1.x + pos1.width) &&
(pos2.y >= pos1.y && pos2.y <= pos1.y + pos1.height)));
}
this.addObject = function(object) {
objects.push(object);
}
this.findCollisions = function(object) {
var collidedWith = [];
for (var i = 0; i < objects.length; i++) {
if (objects.id != objects[i].id &&
this.intersect(object, objects[i]))
collidedWith.push(objects[i].id);
}
if (collidedWith.length > 0) {
object.onCollision({
'collided_with': collidedWith
});
}
}
}
|