text
stringlengths 17
1.47k
| positive
stringlengths 673
4.43k
| negative
stringlengths 677
2.81k
|
---|---|---|
Switch rear DT to move in opposite direction of front DT | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mechanism;
import actuator.IMotor;
import core.GRTLoggedProcess;
/**
* Standard 4 motor drivetrain.
* @author ajc
*/
public class GRTDriveTrain extends GRTLoggedProcess {
private final IMotor leftFront;
private final IMotor leftBack;
private final IMotor rightFront;
private final IMotor rightBack;
/**
*
* @param leftFront left front motor
* @param leftBack left back motor
* @param rightFront right front motor
* @param rightBack right back motor
*/
public GRTDriveTrain(IMotor leftFront, IMotor leftBack,
IMotor rightFront, IMotor rightBack, String name) {
super(name);
this.leftFront = leftFront;
this.leftBack = leftBack;
this.rightFront = rightFront;
this.rightBack = rightBack;
}
/**
* TankDrive uses differential steering.
* @param leftVelocity
* @param rightVelocity
*/
public void tankDrive(double leftVelocity, double rightVelocity) {
// System.out.println("left:" + (-leftVelocity) + "\tright:" + -rightVelocity);
leftFront.setSpeed(-leftVelocity);
leftBack.setSpeed(leftVelocity);
log(100, leftVelocity);
rightFront.setSpeed(-rightVelocity);
rightBack.setSpeed(rightVelocity);
log(101, rightVelocity);
}
}
| /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mechanism;
import actuator.IMotor;
import core.GRTLoggedProcess;
/**
* Standard 4 motor drivetrain.
* @author ajc
*/
public class GRTDriveTrain extends GRTLoggedProcess {
private final IMotor leftFront;
private final IMotor leftBack;
private final IMotor rightFront;
private final IMotor rightBack;
/**
*
* @param leftFront left front motor
* @param leftBack left back motor
* @param rightFront right front motor
* @param rightBack right back motor
*/
public GRTDriveTrain(IMotor leftFront, IMotor leftBack,
IMotor rightFront, IMotor rightBack, String name) {
super(name);
this.leftFront = leftFront;
this.leftBack = leftBack;
this.rightFront = rightFront;
this.rightBack = rightBack;
}
/**
* TankDrive uses differential steering.
* @param leftVelocity
* @param rightVelocity
*/
public void tankDrive(double leftVelocity, double rightVelocity) {
// System.out.println("left:" + (-leftVelocity) + "\tright:" + -rightVelocity);
leftFront.setSpeed(-leftVelocity);
leftBack.setSpeed(-leftVelocity);
log(100, leftVelocity);
rightFront.setSpeed(-rightVelocity);
rightBack.setSpeed(-rightVelocity);
log(101, rightVelocity);
}
}
|
Fix test of assets twig extension | <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Dependency\DependencyMap;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\File\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
class AssetsTwigExtensionTest extends TestCase
{
/**
* Assert that the exposed twig functions don't change
*/
public function testMethodNames ()
{
$htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class)
->disableOriginalConstructor()
->getMock();
$assetUrl = $this->getMockBuilder(AssetUrl::class)
->disableOriginalConstructor()
->getMock();
$fileLoader = $this->getMockBuilder(FileLoader::class)
->disableOriginalConstructor()
->getMock();
$extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader, new DependencyMap([]));
$functions = \array_map(
function (\Twig_SimpleFunction $f)
{
return $f->getName();
},
$extension->getFunctions()
);
self::assertArraySubset([
"asset",
"asset_inline",
"assets_link",
], $functions);
}
}
| <?php
namespace Tests\Becklyn\AssetsBundle\Twig;
use Becklyn\AssetsBundle\Html\AssetHtmlGenerator;
use Becklyn\AssetsBundle\File\FileLoader;
use Becklyn\AssetsBundle\Twig\AssetsTwigExtension;
use Becklyn\AssetsBundle\Url\AssetUrl;
use PHPUnit\Framework\TestCase;
class AssetsTwigExtensionTest extends TestCase
{
/**
* Assert that the exposed twig functions don't change
*/
public function testMethodNames ()
{
$htmlReferences = $this->getMockBuilder(AssetHtmlGenerator::class)
->disableOriginalConstructor()
->getMock();
$assetUrl = $this->getMockBuilder(AssetUrl::class)
->disableOriginalConstructor()
->getMock();
$fileLoader = $this->getMockBuilder(FileLoader::class)
->disableOriginalConstructor()
->getMock();
$extension = new AssetsTwigExtension($htmlReferences, $assetUrl, $fileLoader);
$functions = \array_map(
function (\Twig_SimpleFunction $f)
{
return $f->getName();
},
$extension->getFunctions()
);
self::assertArraySubset([
"asset",
"asset_inline",
"assets_link",
], $functions);
}
}
|
Validate even when we don't detect a mapper | <?php
namespace NS\ImportBundle\Validators;
use NS\ImportBundle\Converter\ColumnChooser;
use NS\ImportBundle\Entity\Column;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ImportMapColumnValidator extends ConstraintValidator
{
/** @var ColumnChooser */
private $columnChooser;
/** @var array */
private $complexChoices;
/**
* ImportMapColumnValidator constructor.
* @param $columnChooser
*/
public function __construct(ColumnChooser $columnChooser)
{
$this->columnChooser = $columnChooser;
}
/**
* @inheritDoc
*/
public function validate($value, Constraint $constraint)
{
if (!$value instanceof Column) {
throw new \InvalidArgumentException(sprintf('Expected object of class %s received %s', Column::class, \get_class($value)));
}
if (empty($this->complexChoices)) {
$this->initializeChoices($value->getMap()->getClass());
}
// if db column is not scalar, ensure we have a 'validator'
if (!$value->hasConverter() && isset($this->complexChoices[$value->getMapper()])) {
$this->context
->buildViolation('This column has a field that requires a validator, but none were selected')
->atPath('converter')
->addViolation();
}
}
/**
* @param $class
*/
public function initializeChoices($class)
{
$this->complexChoices = $this->columnChooser->getComplexChoices($class);
}
}
| <?php
namespace NS\ImportBundle\Validators;
use NS\ImportBundle\Converter\ColumnChooser;
use NS\ImportBundle\Entity\Column;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class ImportMapColumnValidator extends ConstraintValidator
{
/** @var ColumnChooser */
private $columnChooser;
/** @var array */
private $complexChoices;
/**
* ImportMapColumnValidator constructor.
* @param $columnChooser
*/
public function __construct(ColumnChooser $columnChooser)
{
$this->columnChooser = $columnChooser;
}
/**
* @inheritDoc
*/
public function validate($value, Constraint $constraint)
{
if (!$value instanceof Column) {
throw new \InvalidArgumentException(sprintf('Expected object of class %s received %s', Column::class, \get_class($value)));
}
if (empty($this->complexChoices)) {
$this->initializeChoices($value->getMap()->getClass());
}
if ($value->hasMapper()) {
// if db column is not scalar, ensure we have a 'validator'
if (!$value->hasConverter() && isset($this->complexChoices[$value->getMapper()])) {
$this->context
->buildViolation('This column has a field that requires a validator, but none were selected')
->atPath('converter')
->addViolation();
}
}
}
/**
* @param $class
*/
public function initializeChoices($class)
{
$this->complexChoices = $this->columnChooser->getComplexChoices($class);
}
}
|
Fix for msg "Api validation failed" on first time save | <?php
namespace Dotdigitalgroup\Email\Model\Apiconnector;
class Test
{
/**
* @var \Dotdigitalgroup\Email\Helper\Data
*/
public $helper;
/**
* @var \Magento\Framework\App\Config\ReinitableConfigInterface
*/
public $config;
/**
* Test constructor.
*
* @param \Dotdigitalgroup\Email\Helper\Data $data
*/
public function __construct(
\Dotdigitalgroup\Email\Helper\Data $data,
\Magento\Framework\App\Config\ReinitableConfigInterface $config
) {
$this->helper = $data;
$this->config = $config;
}
/**
* Validate apiuser on save.
*
* @param string $apiUsername
* @param string $apiPassword
*
* @return bool|mixed
*/
public function validate($apiUsername, $apiPassword)
{
//Clear config cache
$this->config->reinit();
if (!$this->helper->isEnabled()) {
return false;
}
$website = $this->helper->getWebsite();
$client = $this->helper->getWebsiteApiClient($website);
if ($apiUsername && $apiPassword) {
$client->setApiUsername($apiUsername)
->setApiPassword($apiPassword);
$accountInfo = $client->getAccountInfo();
if (isset($accountInfo->message)) {
$this->helper->log('VALIDATION ERROR : ' . $accountInfo->message);
return false;
}
return $accountInfo;
}
return false;
}
}
| <?php
namespace Dotdigitalgroup\Email\Model\Apiconnector;
class Test
{
/**
* @var \Dotdigitalgroup\Email\Helper\Data
*/
public $helper;
/**
* Test constructor.
*
* @param \Dotdigitalgroup\Email\Helper\Data $data
*/
public function __construct(
\Dotdigitalgroup\Email\Helper\Data $data
) {
$this->helper = $data;
}
/**
* Validate apiuser on save.
*
* @param string $apiUsername
* @param string $apiPassword
*
* @return bool|mixed
*/
public function validate($apiUsername, $apiPassword)
{
if (!$this->helper->isEnabled()) {
return false;
}
$website = $this->helper->getWebsite();
$client = $this->helper->getWebsiteApiClient($website);
if ($apiUsername && $apiPassword) {
$client->setApiUsername($apiUsername)
->setApiPassword($apiPassword);
$accountInfo = $client->getAccountInfo();
if (isset($accountInfo->message)) {
$this->helper->log('VALIDATION ERROR : ' . $accountInfo->message);
return false;
}
return $accountInfo;
}
return false;
}
}
|
Add some basic error handling in case the executables don't exist | #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super(Module, self).__init__(engine, config,
bumblebee.output.Widget(full_text="")
)
self._active = False
self.interval(1)
engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
cmd=self._toggle
)
def state(self, widget):
if self._active:
return "activated"
return "deactivated"
def _toggle(self, event):
self._active = not self._active
try:
if self._active:
bumblebee.util.execute("xdg-screensaver reset")
bumblebee.util.execute("notify-send \"Consuming caffeine\"")
else:
bumblebee.util.execute("notify-send \"Out of coffee\"")
except:
self._active = not self._active
def update(self, widgets):
if self._active:
bumblebee.util.execute("xdg-screensaver reset")
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
| #pylint: disable=C0111,R0903
"""Enable/disable automatic screen locking.
Requires the following executables:
* xdg-screensaver
* notify-send
"""
import bumblebee.input
import bumblebee.output
import bumblebee.engine
class Module(bumblebee.engine.Module):
def __init__(self, engine, config):
super(Module, self).__init__(engine, config,
bumblebee.output.Widget(full_text="")
)
self._active = False
self.interval(1)
engine.input.register_callback(self, button=bumblebee.input.LEFT_MOUSE,
cmd=self._toggle
)
def state(self, widget):
if self._active:
return "activated"
return "deactivated"
def _toggle(self, event):
self._active = not self._active
if self._active:
bumblebee.util.execute("xdg-screensaver reset")
bumblebee.util.execute("notify-send \"Consuming caffeine\"")
else:
bumblebee.util.execute("notify-send \"Out of coffee\"")
def update(self, widgets):
if self._active:
bumblebee.util.execute("xdg-screensaver reset")
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
|
Test that log messages go to stderr. | import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
self.assertEqual(opts.silent, False)
self.assertEqual(args, [])
class TestMain(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
root = logging.getLogger()
buffer = logging.handlers.BufferingHandler(100)
root.addHandler(buffer)
self.buffer = buffer.buffer
self.out = StringIO()
self.err = StringIO()
def main(self, *args, **kwargs):
from script import main
_kwargs = {
"out": self.out,
"err": self.err,
}
_kwargs.update(kwargs)
return main(*args, **_kwargs)
def test_main(self):
result = self.main(["foo"])
self.assertEqual(result, None)
self.assertEqual(self.buffer, [])
def test_main_verbose(self):
result = self.main(["foo", "-vv"])
self.assertEqual(result, None)
self.assertEqual(len(self.buffer), 1)
self.assertEqual(self.buffer[0].msg, "Ready to run")
self.assertTrue("Ready to run" in self.err.getvalue())
| import logging
import unittest
from StringIO import StringIO
class TestArgParsing(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
from script import parseargs
self.parseargs = parseargs
def test_parseargs(self):
opts, args = self.parseargs(["foo"])
self.assertEqual(opts.silent, False)
self.assertEqual(args, [])
class TestMain(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
root = logging.getLogger()
buffer = logging.handlers.BufferingHandler(100)
root.addHandler(buffer)
self.buffer = buffer.buffer
self.out = StringIO()
self.err = StringIO()
def main(self, *args, **kwargs):
from script import main
_kwargs = {
"out": self.out,
"err": self.err,
}
_kwargs.update(kwargs)
return main(*args, **_kwargs)
def test_main(self):
result = self.main(["foo"])
self.assertEqual(result, None)
self.assertEqual(self.buffer, [])
def test_main_verbose(self):
result = self.main(["foo", "-vv"])
self.assertEqual(result, None)
self.assertEqual(len(self.buffer), 1)
self.assertEqual(self.buffer[0].msg, "Ready to run")
|
Implement suggested changes in PR review | """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'private_key_data'
PRIVATE_KEY_FILENAME = 'private_key_file'
def check_configuration_contains(config, keys):
available_keys = frozenset(keys).intersection(frozenset(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the following keys is required but none was '
'specified: {}'.format(keys))
if len(available_keys) > 1:
raise ImproperlyConfigured(
'found conflicting configuration: {}. Only one key can be used at'
'a time.'.format(available_keys))
def validate_configuration(config):
check_configuration_contains(config=config,
keys=(PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME))
check_configuration_contains(config=config,
keys=(CERTIFICATE_DATA, CERTIFICATE_FILENAME))
try:
SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG
except:
raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.')
else:
validate_configuration(SAML2IDP_CONFIG)
try:
SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES
except:
raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
| """
Django Settings that more closely resemble SAML Metadata.
Detailed discussion is in doc/SETTINGS_AND_METADATA.txt.
"""
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
CERTIFICATE_DATA = 'certificate_data'
CERTIFICATE_FILENAME = 'certificate_file'
PRIVATE_KEY_DATA = 'private_key_data'
PRIVATE_KEY_FILENAME = 'private_key_file'
def check_configuration_contains(config, keys):
available_keys = set(keys).intersection(set(config.keys()))
if not available_keys:
raise ImproperlyConfigured(
'one of the followin keys is required but none was '
'specified: {}'.format(keys))
if len(available_keys) > 1:
raise ImproperlyConfigured(
'found conflicting configuration: {}. Only one key can be used at'
'a time.'.format(available_keys))
def validate_configuration(config):
check_configuration_contains(config=config,
keys=[PRIVATE_KEY_DATA, PRIVATE_KEY_FILENAME])
check_configuration_contains(config=config,
keys=[CERTIFICATE_DATA, CERTIFICATE_FILENAME])
try:
SAML2IDP_CONFIG = settings.SAML2IDP_CONFIG
except:
raise ImproperlyConfigured('SAML2IDP_CONFIG setting is missing.')
else:
validate_configuration(SAML2IDP_CONFIG)
try:
SAML2IDP_REMOTES = settings.SAML2IDP_REMOTES
except:
raise ImproperlyConfigured('SAML2IDP_REMOTES setting is missing.')
|
Update to AJAX functions in click controller. | 'use strict';
(function () {
var addButton = document.querySelector('.btn-add');
var deleteButton = document.querySelector('.btn-delete');
var clickNbr = document.querySelector('#click-nbr');
var apiUrl = 'http://localhost:3000/api/clicks';
function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
}
function ajaxRequest (method, url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.send();
}
function updateClickCount (data) {
var clicksObject = JSON.parse(data);
clickNbr.innerHTML = clicksObject.clicks;
}
ready(ajaxRequest('GET', apiUrl, updateClickCount));
addButton.addEventListener('click', function () {
ajaxRequest('POST', apiUrl, function () {
ajaxRequest('GET', apiUrl, updateClickCount);
});
}, false);
deleteButton.addEventListener('click', function () {
ajaxRequest('DELETE', apiUrl, function () {
ajaxRequest('GET', apiUrl, updateClickCount);
});
}, false);
})();
| 'use strict';
(function () {
var addButton = document.querySelector('.btn-add');
var deleteButton = document.querySelector('.btn-delete');
var clickNbr = document.querySelector('#click-nbr');
var apiUrl = 'http://localhost:3000/api/clicks';
function ready (fn) {
if (typeof fn !== 'function') {
return;
}
if (document.readyState === 'complete') {
return fn();
}
document.addEventListener('DOMContentLoaded', fn, false);
}
function ajaxRequest (method, url, callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
callback(xmlhttp.response);
}
};
xmlhttp.open(method, url, true);
xmlhttp.send();
}
function updateClickCount (data) {
var clicksObject = JSON.parse(data);
clickNbr.innerHTML = clicksObject.clicks;
}
ready(function () {
ajaxRequest('GET', apiUrl, updateClickCount);
});
addButton.addEventListener('click', function () {
ajaxRequest('POST', apiUrl, function () {
ajaxRequest('GET', apiUrl, updateClickCount);
});
}, false);
deleteButton.addEventListener('click', function () {
ajaxRequest('DELETE', apiUrl, function () {
ajaxRequest('GET', apiUrl, updateClickCount);
});
}, false);
})();
|
Use array index instead of .index | import React, { Component, PropTypes } from 'react'
import Tile from './Tile'
const styles = {
row: {
position: 'relative',
flexDirection: 'row'
}
}
export default class Board extends Component {
static propTypes = {
tiles: PropTypes.array.isRequired,
playTile: PropTypes.func.isRequired
}
render() {
const { tiles } = this.props;
return (
<div style={styles.row}>
{
tiles.map((tile, idx) => {
return (
<Tile
type={tile.type}
position={tile.position}
key={idx}
index={idx}
isPlayable={tile.isPlayable}
onClickCb={this.props.playTile}
/>
)
})
}
</div>
);
}
}
| import React, { Component, PropTypes } from 'react'
import Tile from './Tile'
import { sortBy } from 'lodash'
const styles = {
row: {
position: 'relative',
flexDirection: 'row'
}
}
export default class Board extends Component {
static propTypes = {
tiles: PropTypes.array.isRequired,
playTile: PropTypes.func.isRequired
}
render() {
const { tiles } = this.props;
return (
<div style={styles.row}>
{
sortBy(tiles, 'index').map((tile) => {
return (
<Tile
type={tile.type}
position={tiles.indexOf(tile)}
key={tile.index}
index={tile.index}
isPlayable={tile.isPlayable}
onClickCb={this.props.playTile}
/>
)
})
}
</div>
);
}
}
|
Implement hashCode() when you implement equals()! | package nodomain.freeyourgadget.gadgetbridge.model;
/**
* Created by steffen on 07.06.16.
*/
public class MusicStateSpec {
public static final int STATE_PLAYING = 0;
public static final int STATE_PAUSED = 1;
public static final int STATE_STOPPED = 2;
public static final int STATE_UNKNOWN = 3;
public byte state;
public int position;
public int playRate;
public byte shuffle;
public byte repeat;
public MusicStateSpec() {
}
public MusicStateSpec(MusicStateSpec old) {
this.state = old.state;
this.position = old.position;
this.playRate = old.playRate;
this.shuffle = old.shuffle;
this.repeat = old.repeat;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MusicStateSpec)) {
return false;
}
MusicStateSpec stateSpec = (MusicStateSpec) obj;
return this.state == stateSpec.state &&
Math.abs(this.position - stateSpec.position)<=2 &&
this.playRate == stateSpec.playRate &&
this.shuffle == stateSpec.shuffle &&
this.repeat == stateSpec.repeat;
}
@Override
public int hashCode() {
int result = (int) state;
// ignore the position -- it is taken into account in equals()
// result = 31 * result + position;
result = 31 * result + playRate;
result = 31 * result + (int) shuffle;
result = 31 * result + (int) repeat;
return result;
}
}
| package nodomain.freeyourgadget.gadgetbridge.model;
/**
* Created by steffen on 07.06.16.
*/
public class MusicStateSpec {
public static final int STATE_PLAYING = 0;
public static final int STATE_PAUSED = 1;
public static final int STATE_STOPPED = 2;
public static final int STATE_UNKNOWN = 3;
public byte state;
public int position;
public int playRate;
public byte shuffle;
public byte repeat;
public MusicStateSpec() {
}
public MusicStateSpec(MusicStateSpec old) {
this.state = old.state;
this.position = old.position;
this.playRate = old.playRate;
this.shuffle = old.shuffle;
this.repeat = old.repeat;
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MusicStateSpec)) {
return false;
}
MusicStateSpec stateSpec = (MusicStateSpec) obj;
return this.state == stateSpec.state &&
Math.abs(this.position - stateSpec.position)<=2 &&
this.playRate == stateSpec.playRate &&
this.shuffle == stateSpec.shuffle &&
this.repeat == stateSpec.repeat;
}
}
|
Rename /user route to /min-side | var passport = require('passport');
var auth0 = require('../lib/services/auth0');
module.exports = {
type: 'authentication',
module: auth0,
initialize: (app) => {
passport.use(auth0.strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user;
next();
});
},
registerRoutes: app => {
app.get('/login', function(req, res) {
res.render('login', {env: process.env});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// Most user facing routes are danish, so let's keep it that way.
app.get('/min-side', function (req, res) {
res.render('profile', {user: req.user});
});
app.get('/auth/callback', passport.authenticate('auth0', {
failureRedirect: '/'
}), function(req, res) {
const serializedState = req.query.state;
if(typeof(serializedState) === 'string') {
const state = JSON.parse(Buffer.from(serializedState, 'base64'));
res.redirect(state.returnPath);
} else {
res.redirect('/');
}
});
}
};
| var passport = require('passport');
var auth0 = require('../lib/services/auth0');
module.exports = {
type: 'authentication',
module: auth0,
initialize: (app) => {
passport.use(auth0.strategy);
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user;
next();
});
},
registerRoutes: app => {
app.get('/login', function(req, res) {
res.render('login', {env: process.env});
});
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
app.get('/user', function (req, res) {
res.render('user', {user: req.user});
});
app.get('/auth/callback', passport.authenticate('auth0', {
failureRedirect: '/'
}), function(req, res) {
const serializedState = req.query.state;
if(typeof(serializedState) === 'string') {
const state = JSON.parse(Buffer.from(serializedState, 'base64'));
res.redirect(state.returnPath);
} else {
res.redirect('/');
}
});
}
};
|
Remove line numbers from recipe code
The larger font made the numbers not match the code.
Added better link text to download the recipe. | """
Generate the rst files for the cookbook from the recipes.
"""
import sys
import os
body = r"""
**Download** source code: :download:`{recipe}<{code}>`
.. literalinclude:: {code}
:language: python
"""
def recipe_to_rst(recipe):
"""
Convert a .py recipe to a .rst entry for sphinx
"""
sys.stderr.write("Converting {} to rst ...".format(recipe))
recipe_file = os.path.split(recipe)[-1]
recipe_name = os.path.splitext(recipe_file)[0]
output = recipe_name + '.rst'
# Get the title from the first lines of the recipe docstring
title = ''
with open(recipe) as f:
for line in f.readlines()[1:]:
line = line.strip()
if line == '"""' or not line:
break
title = ' '.join([title, line])
with open(output, 'w') as f:
f.write('.. _cookbook_{}:\n\n'.format(recipe_name))
f.write(title.strip() + '\n')
f.write('='*len(title) + '\n')
f.write(body.format(
recipe=recipe_file,
code='../_static/cookbook/{}'.format(recipe_file)))
sys.stderr.write(" done\n")
if __name__ == '__main__':
for recipe in sys.argv[1:]:
recipe_to_rst(recipe)
| """
Generate the rst files for the cookbook from the recipes.
"""
import sys
import os
body = r"""
.. raw:: html
[<a href="{code}">source code</a>]
.. literalinclude:: {code}
:language: python
:linenos:
"""
def recipe_to_rst(recipe):
"""
Convert a .py recipe to a .rst entry for sphinx
"""
sys.stderr.write("Converting {} to rst ...".format(recipe))
recipe_file = os.path.split(recipe)[-1]
recipe_name = os.path.splitext(recipe_file)[0]
output = recipe_name + '.rst'
# Get the title from the first lines of the recipe docstring
title = ''
with open(recipe) as f:
for line in f.readlines()[1:]:
line = line.strip()
if line == '"""' or not line:
break
title = ' '.join([title, line])
with open(output, 'w') as f:
f.write('.. _cookbook_{}:\n\n'.format(recipe_name))
f.write(title.strip() + '\n')
f.write('='*len(title) + '\n')
f.write(body.format(
code='../_static/cookbook/{}'.format(recipe_file)))
sys.stderr.write(" done\n")
if __name__ == '__main__':
for recipe in sys.argv[1:]:
recipe_to_rst(recipe)
|
Fix Stream instance of Guzzle | <?php
namespace Gerencianet\Exception;
use Exception;
class GerencianetException extends Exception
{
private $error;
private $errorDescription;
public function __construct($exception)
{
$error = $exception;
if ($exception instanceof \GuzzleHttp\Stream\Stream) {
$error = $this->parseStream($exception);
}
$message = isset($error['error_description']['message']) ? $error['error_description']['message'] : $error['error_description'];
if (isset($error['error_description']['property'])) {
$message .= ': '.$error['error_description']['property'];
}
$this->error = $error['error'];
$this->errorDescription = $error['error_description'];
parent::__construct($message, $error['code']);
}
private function parseStream($stream)
{
$error = '';
while (!$stream->eof()) {
$error .= $stream->read(1024);
}
return json_decode($error, true);
}
public function __toString()
{
return 'Error '.$this->code.': '.$this->message."\n";
}
public function __get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
}
}
| <?php
namespace Gerencianet\Exception;
use Exception;
class GerencianetException extends Exception
{
private $error;
private $errorDescription;
public function __construct($exception)
{
$error = $exception;
if ($exception instanceof \GuzzleHttp\Psr7\Stream) {
$error = $this->parseStream($exception);
}
$message = isset($error['error_description']['message']) ? $error['error_description']['message'] : $error['error_description'];
if (isset($error['error_description']['property'])) {
$message .= ': '.$error['error_description']['property'];
}
$this->error = $error['error'];
$this->errorDescription = $error['error_description'];
parent::__construct($message, $error['code']);
}
private function parseStream($stream)
{
$error = '';
while (!$stream->eof()) {
$error .= $stream->read(1024);
}
return json_decode($error, true);
}
public function __toString()
{
return 'Error '.$this->code.': '.$this->message."\n";
}
public function __get($property)
{
if (property_exists($this, $property)) {
return $this->$property;
}
}
}
|
Rename content field to field_value. | # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.CharField(
max_length=100,
verbose_name=_('identifier'),
help_text=_('The registered model identifier.'))
object_id = models.IntegerField(
verbose_name=_('The object ID'),
help_text=_('The object ID of this translation'))
language = models.CharField(
max_length=10,
verbose_name=_('locale'),
choices=settings.SUPPORTED_LANGUAGES,
default=settings.DEFAULT_LANGUAGE,
help_text=_('The language for this translation'))
field_name = models.CharField(
max_length=100,
verbose_name=_('field name'),
help_text=_('The model field name for this translation.'))
field_value = models.TextField(
verbose_name=_('field value'),
null=True,
help_text=_('The translated content for the field.'))
class Meta:
abstract = True
app_label = 'linguist'
verbose_name = _('translation')
verbose_name_plural = _('translations')
unique_together = (('identifier', 'object_id', 'language', 'field_name'),)
def __str__(self):
return '%s:%d:%s:%s' % (
self.identifier,
self.object_id,
self.field_name,
self.language)
| # -*- coding: utf-8 -*-
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from .. import settings
@python_2_unicode_compatible
class Translation(models.Model):
"""
A Translation.
"""
identifier = models.CharField(
max_length=100,
verbose_name=_('identifier'),
help_text=_('The registered model identifier.'))
object_id = models.IntegerField(
verbose_name=_('The object ID'),
help_text=_('The object ID of this translation'))
language = models.CharField(
max_length=10,
verbose_name=_('locale'),
choices=settings.SUPPORTED_LANGUAGES,
default=settings.DEFAULT_LANGUAGE,
help_text=_('The language for this translation'))
field_name = models.CharField(
max_length=100,
verbose_name=_('field name'),
help_text=_('The model field name for this translation.'))
content = models.TextField(
verbose_name=_('content'),
null=True,
help_text=_('The translated content for the field.'))
class Meta:
abstract = True
app_label = 'linguist'
verbose_name = _('translation')
verbose_name_plural = _('translations')
unique_together = (('identifier', 'object_id', 'language', 'field_name'),)
def __str__(self):
return '%s:%d:%s:%s' % (
self.identifier,
self.object_id,
self.field_name,
self.language)
|
Remove unneeded variable from test. | from textwrap import dedent
from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from flocker import __version__ as version
from flocker.common.version import get_installable_version
from flocker.testtools import run_process
class VersionExtensionsTest(SynchronousTestCase):
"""
Tests for Sphinx version extensions.
"""
def test_version_prompt(self):
"""
The ``version-prompt`` directive replaces the placemarker
``|latest-installable|`` in a source file with the current
installable version in the output file.
"""
temp_dir = FilePath(self.mktemp())
temp_dir.makedirs()
source_file = temp_dir.child('contents.rst')
source_file.setContent(dedent('''
.. version-prompt:: bash $
$ PRE-|latest-installable|-POST
'''))
run_process([
'sphinx-build', '-b', 'html',
'-C', # don't look for config file, use -D flags instead
'-D', 'extensions=flocker.docs.version_extensions',
temp_dir.path, # directory containing source/config files
temp_dir.path, # directory containing build files
source_file.path]) # source file to process
expected = 'PRE-{}-POST'.format(get_installable_version(version))
content = temp_dir.child('contents.html').getContent()
self.assertIn(expected, content)
| from textwrap import dedent
from twisted.python.filepath import FilePath
from twisted.trial.unittest import SynchronousTestCase
from flocker import __version__ as version
from flocker.common.version import get_installable_version
from flocker.testtools import run_process
class VersionExtensionsTest(SynchronousTestCase):
"""
Tests for Sphinx version extensions.
"""
def test_version_prompt(self):
"""
The ``version-prompt`` directive replaces the placemarker
``|latest-installable|`` in a source file with the current
installable version in the output file.
"""
temp_dir = FilePath(self.mktemp())
temp_dir.makedirs()
source_file = temp_dir.child('contents.rst')
source_file.setContent(dedent('''
.. version-prompt:: bash $
$ PRE-|latest-installable|-POST
'''))
target = temp_dir.child('contents.html')
run_process([
'sphinx-build', '-b', 'html',
'-C', # don't look for config file, use -D flags instead
'-D', 'extensions=flocker.docs.version_extensions',
temp_dir.path, # directory containing source/config files
temp_dir.path, # directory containing build files
source_file.path]) # source file to process
content = target.getContent()
expected = 'PRE-{}-POST'.format(get_installable_version(version))
self.assertIn(expected, content)
|
Use BrokerAwareExtension instead of deprecated BrokerAwareClassReflectionExtension | <?php
declare(strict_types=1);
namespace SaschaEgerer\PhpstanTypo3\Reflection;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\BrokerAwareExtension;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\MethodsClassReflectionExtension;
class RepositoryMethodsClassReflectionExtension implements MethodsClassReflectionExtension, BrokerAwareExtension
{
/**
* @var Broker
*/
private $broker;
public function setBroker(Broker $broker)
{
$this->broker = $broker;
}
public function hasMethod(ClassReflection $classReflection, string $methodName): bool
{
if (
!$classReflection->getNativeReflection()->hasMethod($methodName)
&& $classReflection->isSubclassOf(\TYPO3\CMS\Extbase\Persistence\Repository::class)
) {
return 0 === strpos($methodName, 'findBy') || 0 === strpos($methodName, 'findOneBy');
}
return false;
}
public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
{
if (0 === strpos($methodName, 'findOneBy')) {
$methodReflection = new RepositoryFindOneByMethodReflection($classReflection, $methodName, $this->broker);
} else {
$methodReflection = new RepositoryFindByMethodReflection($classReflection, $methodName, $this->broker);
}
return $methodReflection;
}
}
| <?php
declare(strict_types=1);
namespace SaschaEgerer\PhpstanTypo3\Reflection;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\BrokerAwareClassReflectionExtension;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Reflection\MethodReflection;
class RepositoryMethodsClassReflectionExtension implements \PHPStan\Reflection\MethodsClassReflectionExtension, BrokerAwareClassReflectionExtension
{
/**
* @var Broker
*/
private $broker;
public function setBroker(Broker $broker)
{
$this->broker = $broker;
}
public function hasMethod(ClassReflection $classReflection, string $methodName): bool
{
if (
!$classReflection->getNativeReflection()->hasMethod($methodName)
&& $classReflection->isSubclassOf(\TYPO3\CMS\Extbase\Persistence\Repository::class)
) {
return 0 === strpos($methodName, 'findBy') || 0 === strpos($methodName, 'findOneBy');
}
return false;
}
public function getMethod(ClassReflection $classReflection, string $methodName): MethodReflection
{
if (0 === strpos($methodName, 'findOneBy')) {
$methodReflection = new RepositoryFindOneByMethodReflection($classReflection, $methodName, $this->broker);
} else {
$methodReflection = new RepositoryFindByMethodReflection($classReflection, $methodName, $this->broker);
}
return $methodReflection;
}
}
|
Add TODO on how to make a better libspotify lookup | import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class LibspotifyLibraryController(BaseLibraryController):
def find_exact(self, **query):
return self.search(**query)
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
# TODO Block until metadata_updated callback is called. Before that the
# track will be unloaded, unless it's already in the stored playlists.
return LibspotifyTranslator.to_mopidy_track(spotify_track)
def refresh(self, uri=None):
pass # TODO
def search(self, **query):
spotify_query = []
for (field, values) in query.iteritems():
if not hasattr(values, '__iter__'):
values = [values]
for value in values:
if field == u'track':
field = u'title'
if field == u'any':
spotify_query.append(value)
else:
spotify_query.append(u'%s:"%s"' % (field, value))
spotify_query = u' '.join(spotify_query)
logger.debug(u'Spotify search query: %s' % spotify_query)
my_end, other_end = multiprocessing.Pipe()
self.backend.spotify.search(spotify_query.encode(ENCODING), other_end)
my_end.poll(None)
playlist = my_end.recv()
return playlist
| import logging
import multiprocessing
from spotify import Link
from mopidy.backends.base import BaseLibraryController
from mopidy.backends.libspotify import ENCODING
from mopidy.backends.libspotify.translator import LibspotifyTranslator
logger = logging.getLogger('mopidy.backends.libspotify.library')
class LibspotifyLibraryController(BaseLibraryController):
def find_exact(self, **query):
return self.search(**query)
def lookup(self, uri):
spotify_track = Link.from_string(uri).as_track()
return LibspotifyTranslator.to_mopidy_track(spotify_track)
def refresh(self, uri=None):
pass # TODO
def search(self, **query):
spotify_query = []
for (field, values) in query.iteritems():
if not hasattr(values, '__iter__'):
values = [values]
for value in values:
if field == u'track':
field = u'title'
if field == u'any':
spotify_query.append(value)
else:
spotify_query.append(u'%s:"%s"' % (field, value))
spotify_query = u' '.join(spotify_query)
logger.debug(u'Spotify search query: %s' % spotify_query)
my_end, other_end = multiprocessing.Pipe()
self.backend.spotify.search(spotify_query.encode(ENCODING), other_end)
my_end.poll(None)
playlist = my_end.recv()
return playlist
|
Replace "pass" with "self.fail()" in tests
In this way, tests that haven't been written will run noisily instead of
silently, encouraging completion of writing tests. | # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
self.fail()
def test_version(self):
"""
`ref --version` should return version string
"""
self.fail()
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
self.fail()
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
self.fail()
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
self.fail()
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
self.fail()
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
self.fail()
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
self.fail()
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
self.fail()
| # -*- coding: utf-8 -*-
import unittest
import pathlib2 as pathlib
import refmanage
class NoSpecifiedFunctionality(unittest.TestCase):
"""
Tests when no functionality has been specified on cli
"""
def test_no_args(self):
"""
`ref` without arguments should print the help text
"""
pass
def test_version(self):
"""
`ref --version` should return version string
"""
pass
class TestFunctionality(unittest.TestCase):
"""
Test "test" functionality
"""
def test_no_args(self):
"""
`ref test` without additonal arguments should print the help text
"""
pass
def test_default(self):
"""
`ref test *.bib` without flags should default to --unparseable and print list of unparseable files
"""
pass
def test_unparseable(self):
"""
`ref test -u *.bib` should print list of unparseable files
"""
pass
def test_unparseable_verbose(self):
"""
`ref test -uv *.bib` should print list of unparseable files with information about corresponding parsing message
"""
pass
def test_parseable(self):
"""
`ref test -p *.bib` should print list of parseable files
"""
pass
def test_parseable_verbose(self):
"""
`ref test -pv *.bib` should print list of parseable files and nothing more
"""
pass
def test_parseable_unparseable(self):
"""
`ref test -up *.bib` should exit with an error
"""
pass
|
Switch to update_or_create - Django 1.7+
Can't use this on older versions of Django | from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
# Need to escape HTML entities
htmlparser = html_parser.HTMLParser()
unescape = htmlparser.unescape
for i in messages:
tweet_id = i['id']
tweet_username = i['user']['screen_name']
tweet_text = unescape(i['text'])
tweet_created = datetime.strptime(
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
obj, created = Tweet.objects.update_or_create(tweet_id=tweet_id, defaults={
'user': tweet_username,
'text': tweet_text,
'created': tweet_created,
})
class Command(BaseCommand):
def handle(self, *args, **options):
for i in args:
update_user(i)
| from django.core.management.base import BaseCommand
from django.conf import settings
from django.utils.timezone import utc
from datetime import datetime
from twitter import Twitter, OAuth
from latest_tweets.models import Tweet
from django.utils.six.moves import html_parser
def update_user(user):
t = Twitter(auth=OAuth(
settings.TWITTER_OAUTH_TOKEN,
settings.TWITTER_OAUTH_SECRET,
settings.TWITTER_CONSUMER_KEY,
settings.TWITTER_CONSUMER_SECRET
))
messages = t.statuses.user_timeline(screen_name=user, include_rts=True)
# Need to escape HTML entities
htmlparser = html_parser.HTMLParser()
unescape = htmlparser.unescape
for i in messages:
tweet_id = i['id']
tweet_username = i['user']['screen_name']
tweet_text = unescape(i['text'])
tweet_created = datetime.strptime(
i['created_at'], '%a %b %d %H:%M:%S +0000 %Y'
).replace(tzinfo=utc)
obj, created = Tweet.objects.get_or_create(tweet_id=tweet_id, defaults={
'user': tweet_username,
'text': tweet_text,
'created': tweet_created,
})
class Command(BaseCommand):
def handle(self, *args, **options):
for i in args:
update_user(i)
|
Remove default name and text of the control class | <?php
/**
* @author Manuel Thalmann <[email protected]>
* @license Apache-2.0
*/
namespace System\Web\Forms;
use System\Object;
use System\Web\Forms\Rendering\IRenderable;
{
abstract class Control extends Object implements IRenderable
{
/**
* Initializes a new instance of the control-class.
*/
public function Control()
{
}
/**
* Gets or sets the identifier of the control.
*
* @var string
*/
public $Name;
/**
* Gets or sets the Text of the control.
*
* @var string
*/
public $Text;
/**
* Gets or sets a value indicating whether the control can respond to user interaction.
*
* @var boolean
*/
public $Enabled = true;
/**
* Gets or sets a value indicating whether the control and all its child controls are displayed.
*
* @var boolean
*/
public $Visible = true;
}
}
?> | <?php
/**
* @author Manuel Thalmann <[email protected]>
* @license Apache-2.0
*/
namespace System\Web\Forms;
use System\Object;
use System\Web\Forms\Rendering\IRenderable;
{
abstract class Control extends Object implements IRenderable
{
/**
* Initializes a new instance of the control-class.
*/
public function Control()
{
}
/**
* Gets or sets the identifier of the control.
*
* @var string
*/
public $Name = '';
/**
* Gets or sets the Text of the control.
*
* @var string
*/
public $Text = '';
/**
* Gets or sets a value indicating whether the control can respond to user interaction.
*
* @var boolean
*/
public $Enabled = true;
/**
* Gets or sets a value indicating whether the control and all its child controls are displayed.
*
* @var boolean
*/
public $Visible = true;
}
}
?> |
Add .0 to version number. | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-imgix',
version='0.2.0',
packages=find_packages(),
include_package_data=True,
license='BSD License', # example license
description='Django app to generate imgix urls in your templates.',
long_description=README,
url='https://github.com/pancentric/django-imgix',
author='Pancentric Ltd',
author_email='[email protected]',
install_requires=[
'django>=1.4.0',
'imgix>=1.0.0',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
# Replace these appropriately if you are stuck on Python 2.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-imgix',
version='0.2',
packages=find_packages(),
include_package_data=True,
license='BSD License', # example license
description='Django app to generate imgix urls in your templates.',
long_description=README,
url='https://github.com/pancentric/django-imgix',
author='Pancentric Ltd',
author_email='[email protected]',
install_requires=[
'django>=1.4.0',
'imgix>=1.0.0',
],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
# Replace these appropriately if you are stuck on Python 2.
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
|
FIX only post message if a partner is existent | # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Steve Ferry
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
if part:
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
| # -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (C) 2014-2015 Compassion CH (http://www.compassion.ch)
# Releasing children from poverty in Jesus' name
# @author: Steve Ferry
#
# The licence is in the file __manifest__.py
#
##############################################################################
from odoo import api, models, _
# pylint: disable=C8107
class ResPartnerBank(models.Model):
""" This class upgrade the partners.bank to match Compassion needs.
"""
_inherit = 'res.partner.bank'
@api.model
def create(self, data):
"""Override function to notify creation in a message
"""
result = super(ResPartnerBank, self).create(data)
part = result.partner_id
part.message_post(_("<b>Account number: </b>" + result.acc_number),
_("New account created"), 'comment')
return result
@api.multi
def unlink(self):
"""Override function to notify delte in a message
"""
for account in self:
part = account.partner_id
part.message_post(_("<b>Account number: </b>" +
account.acc_number),
_("Account deleted"), 'comment')
result = super(ResPartnerBank, self).unlink()
return result
|
Set mocha test timeout for entire test, extended timeout to 30 seconds. | /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('Ionic Framework Generator', function () {
this.timeout(30000);
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ionic:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
compass: false,
plugins: ['com.ionic.keyboard'],
starter: 'Tabs'
});
this.app.init = function () {};
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
| /*global describe, beforeEach, it*/
'use strict';
var path = require('path');
var helpers = require('yeoman-generator').test;
describe('Ionic Framework Generator', function () {
beforeEach(function (done) {
helpers.testDirectory(path.join(__dirname, 'temp'), function (err) {
if (err) {
return done(err);
}
this.app = helpers.createGenerator('ionic:app', [
'../../app'
]);
done();
}.bind(this));
});
it('creates expected files', function (done) {
this.timeout(30000);
var expected = [
// add files you expect to exist here.
'.jshintrc',
'.editorconfig'
];
helpers.mockPrompt(this.app, {
compass: false,
plugins: ['com.ionic.keyboard'],
starter: 'Tabs'
});
this.app.init = function () {};
this.app.run({}, function () {
helpers.assertFiles(expected);
done();
});
});
});
|
Allow subclasses to customise the worker class | from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_locale_alone = True
worker_class = Worker
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
"--layer", action="store", dest="layer", default=DEFAULT_CHANNEL_LAYER,
help="Channel layer alias to use, if not the default.",
)
parser.add_argument(
"channels",
nargs="+",
help="Channels to listen on."
)
def handle(self, *args, **options):
# Get the backend to use
self.verbosity = options.get("verbosity", 1)
# Get the channel layer they asked for (or see if one isn't configured)
if "layer" in options:
self.channel_layer = get_channel_layer(options["layer"])
else:
self.channel_layer = get_channel_layer()
if self.channel_layer is None:
raise CommandError("You do not have any CHANNEL_LAYERS configured.")
# Run the worker
self.logger = setup_logger("django.channels", self.verbosity)
self.logger.info("Running worker for channels %s", options["channels"])
worker = self.worker_class(
application=get_default_application(),
channels=options["channels"],
channel_layer=self.channel_layer,
)
worker.run()
| from django.core.management import BaseCommand, CommandError
from channels import DEFAULT_CHANNEL_LAYER
from channels.layers import get_channel_layer
from channels.log import setup_logger
from channels.routing import get_default_application
from channels.worker import Worker
class Command(BaseCommand):
leave_locale_alone = True
def add_arguments(self, parser):
super(Command, self).add_arguments(parser)
parser.add_argument(
"--layer", action="store", dest="layer", default=DEFAULT_CHANNEL_LAYER,
help="Channel layer alias to use, if not the default.",
)
parser.add_argument(
"channels",
nargs="+",
help="Channels to listen on."
)
def handle(self, *args, **options):
# Get the backend to use
self.verbosity = options.get("verbosity", 1)
# Get the channel layer they asked for (or see if one isn't configured)
if "layer" in options:
self.channel_layer = get_channel_layer(options["layer"])
else:
self.channel_layer = get_channel_layer()
if self.channel_layer is None:
raise CommandError("You do not have any CHANNEL_LAYERS configured.")
# Run the worker
self.logger = setup_logger("django.channels", self.verbosity)
self.logger.info("Running worker for channels %s", options["channels"])
worker = Worker(
application=get_default_application(),
channels=options["channels"],
channel_layer=self.channel_layer,
)
worker.run()
|
createNotificationsMiddleware: Put an arg default back | import { fetch } from 'domain/Api';
import ApiCall from 'containers/ApiCalls';
/*
* Supports currying so that args can be recycled more conveniently.
* A contrived example:
* ```
* const createCreatorForX =
* createApiActionCreator('X_REQUEST', 'X_SUCCESS', 'X_FAILURE', 'http://...');
* const getXActionCreator = createCreatorForX('GET');
* const postXActionCreator = createCreatorForX('POST');
* ```
*/
const createApiActionCreator = (
requestActionType, successActionType, failureActionType, url, method = 'GET') =>
(dispatch) => {
return dispatch(createFetchRequestAction()).payload
.then((response) => dispatch(createFetchSuccessAction(response)))
.catch((error) => dispatch(createFetchFailureAction(error)));
function createFetchRequestAction() {
return ApiCall.createAction({
type: requestActionType,
payload: fetch(url),
url,
method,
});
}
function createFetchSuccessAction(response) {
return ApiCall.createAction({
type: successActionType,
payload: response,
url,
method,
});
}
function createFetchFailureAction(error) {
return ApiCall.createAction({
type: failureActionType,
error,
url,
method,
});
}
};
const curried = (...args) => {
if (args.length >= createApiActionCreator.length) {
return createApiActionCreator.apply(this, args);
}
return (...rest) => curried.apply(this, args.concat(rest));
};
export default curried;
| import { fetch } from 'domain/Api';
import ApiCall from 'containers/ApiCalls';
/*
* Supports currying so that args can be recycled more conveniently.
* A contrived example:
* ```
* const createCreatorForX =
* createApiActionCreator('X_REQUEST', 'X_SUCCESS', 'X_FAILURE', 'http://...');
* const getXActionCreator = createCreatorForX('GET');
* const postXActionCreator = createCreatorForX('POST');
* ```
*/
const createApiActionCreator = (
requestActionType, successActionType, failureActionType, url, method) =>
(dispatch) => {
return dispatch(createFetchRequestAction()).payload
.then((response) => dispatch(createFetchSuccessAction(response)))
.catch((error) => dispatch(createFetchFailureAction(error)));
function createFetchRequestAction() {
return ApiCall.createAction({
type: requestActionType,
payload: fetch(url),
url,
method,
});
}
function createFetchSuccessAction(response) {
return ApiCall.createAction({
type: successActionType,
payload: response,
url,
method,
});
}
function createFetchFailureAction(error) {
return ApiCall.createAction({
type: failureActionType,
error,
url,
method,
});
}
};
const curried = (...args) => {
if (args.length >= createApiActionCreator.length) {
return createApiActionCreator.apply(this, args);
}
return (...rest) => curried.apply(this, args.concat(rest));
};
export default curried;
|
Use the new Deck class | #Cards Against Humanity game engine
from cards import Deck, NoMoreCards
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck = Deck()
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False | #Cards Against Humanity game engine
class CAHGame:
def __init__(self):
self.status = "Loaded CAHGame."
#flag to keep track of whether or not game is running
self.running = False
#list of active players in a game
self.players = []
#dummy with a small deck for testing.
#replace with actual card loading from DB later
self.deck ={
'questions' : [
"_? There's an app for that.",
"I got 99 problems but _ ain't one.",
],
'answers' : [
"Flying sex snakes.",
"Michelle Obama's arms.",
"German dungeon porn.",
"White people.",
"Getting so angry that you pop a boner.",
"Freedom of Speech",
]
}
#add a new player to the game
def add_player(self, name):
self.players.append(Player(name))
#start the game
def start(self):
pass
def draw(self, color):
'''Draws a random card of <color> from the databse and returns a Card object.'''
pass
#Utility class to manage Players
class Player:
def __init__(self, name):
self.name = name #Player name (IRC nick)
self.score = 0
self.hand = {}
self.isCzar = False
#Utiliy class for a Card
class Card:
def __init__(self, color, body):
self.color = color
self.body = body
|
Sort versions in version list by 'version' descending | <?php
$page = new \Site\Page();
$page->requireRole('package manager');
// @TODO for PHP7 warnings, fix object inheritance Package\Version::get, Storage\File::get
error_reporting(E_ERROR | E_PARSE);
if (isset($_REQUEST['code'])) {
$package = new \Package\Package();
if (! $package->get($_REQUEST['code'])) $page->addError("Package not found");
}
if ($_REQUEST['dothis'] == 'publish') {
$version = new \Package\Version($_REQUEST['version_id']);
app_log($GLOBALS['_SESSION_']->customer->login." publishing version ".$version->version()." of ".$version->package->name,'notice');
$version->publish();
if ($version->error) $page->addError($version->error);
}
if ($_REQUEST['dothis'] == 'hide') {
$version = new \Package\Version($_REQUEST['version_id']);
app_log("Hiding version ".$version->version()." of ".$version->package->name,'notice');
$version->hide();
}
if ($_REQUEST['dothis'] == 'download') {
$version = new \Package\Version($_REQUEST['version_id']);
$version->download();
if ($version->error()) {
$page->addError($version->error());
} else {
exit;
}
}
$parameters = array();
$parameters['package_id'] = $package->id;
$parameters['_sort'] = 'version';
$parameters['_sort_desc'] = true;
$versionList = new \Package\VersionList();
$versions = $versionList->find(array('package_id' => $package->id));
| <?php
$page = new \Site\Page();
$page->requireRole('package manager');
// @TODO for PHP7 warnings, fix object inheritance Package\Version::get, Storage\File::get
error_reporting(E_ERROR | E_PARSE);
if (isset($_REQUEST['code'])) {
$package = new \Package\Package();
if (! $package->get($_REQUEST['code'])) $page->addError("Package not found");
}
if ($_REQUEST['dothis'] == 'publish') {
$version = new \Package\Version($_REQUEST['version_id']);
app_log($GLOBALS['_SESSION_']->customer->login." publishing version ".$version->version()." of ".$version->package->name,'notice');
$version->publish();
if ($version->error) $page->addError($version->error);
}
if ($_REQUEST['dothis'] == 'hide') {
$version = new \Package\Version($_REQUEST['version_id']);
app_log("Hiding version ".$version->version()." of ".$version->package->name,'notice');
$version->hide();
}
if ($_REQUEST['dothis'] == 'download') {
$version = new \Package\Version($_REQUEST['version_id']);
$version->download();
if ($version->error()) {
$page->addError($version->error());
} else {
exit;
}
}
$versionList = new \Package\VersionList();
$versions = $versionList->find(array('package_id' => $package->id));
|
Use isNaN() to check for NaN. Comparison op '!==='
doesn't work.
Also add a method 'selected' to factor out
retrieval of selected value | (function () {
var mr = sparks.activities.mr;
var str = sparks.string;
mr.ActivityDomHelper = {
ratedResistanceFormId: '#rated_resistance',
ratedResistanceValueId: '#rated_resistance_value_input',
ratedResistanceUnitId: '#rated_resitance_unit_select',
getAnswer: function (questionNum) {
var value, unit;
switch (questionNum) {
case 1:
value = $(this.ratedResistanceValueId).val();
unit = $(this.ratedResistanceUnitId).val();
return [value, unit];
case 2:
case 3:
case 4:
default:
alert('ERROR: ActivityDomHelper.getAnswer: invalid question number ' + questionNum);
return null;
}
},
validateNumberString: function (s) {
var s2 = str.strip(s);
return s2 !== '' && !isNaN(Number(s2));
},
selected: function(selectElem) {
return selectElem.children('option:selected').val();
}
};
})();
| (function () {
var mr = sparks.activities.mr;
var str = sparks.string;
mr.ActivityDomHelper = {
ratedResistanceFormId: '#rated_resistance',
ratedResistanceValueId: '#rated_resistance_value_input',
ratedResistanceUnitId: '#rated_resitance_unit_select',
getAnswer: function (questionNum) {
var value, unit;
switch (questionNum) {
case 1:
value = $(this.ratedResistanceValueId).val();
unit = $(this.ratedResistanceUnitId).val();
return [value, unit];
case 2:
case 3:
case 4:
default:
alert('ERROR: ActivityDomHelper.getAnswer: invalid question number ' + questionNum);
return null;
}
},
validateNumberString: function (s) {
var s2 = str.strip(s);
return s2 !== '' && Number(s2) !== NaN;
},
validateResistanceUnitString: function (s) {
}
};
})();
|
Add e.preventDefault to comments form. | app.Comments = React.createClass({
//get all loaded comments
getInitialState: function () {
return {
displaying: false,
comments: app.CommentStore.getAll(this.props.idea_id)
};
},
//when we mount the view setup event listener for store changes
componentDidMount: function () {
app.CommentStore.addChangeListener(function () {
if (this.isMounted()) {
this.setState({ comments: app.CommentStore.getAll(this.props.idea_id) });
}
}.bind(this));
},
show: function (e) {
e.preventDefault();
if (this.isMounted()) {
this.setState({ displaying: !this.state.displaying });
}
},
//render a comment component for each comment
render: function () {
var comments;
var commentForm;
var showCommentsButton;
//display comments if we are displaying, otherwise show buttons
if (this.state.displaying){
commentForm = <app.CommentForm idea_id={this.props.idea_id} />
comments = [];
//render a comment component for each comment
this.state.comments.forEach(function (comment) {
comments.push(
<app.Comment name={comment.name} key={comment._id} _id={comment._id} idea_id={comment.idea_id} />
);
});
}
showCommentsButton = <button className="pure-button" onClick={this.show}>{this.state.displaying? 'Hide' : 'Show'} Comments</button>
return (
<div ref="body">
{ showCommentsButton }
{ comments }
{ commentForm }
</div>
);
}
});
| app.Comments = React.createClass({
//get all loaded comments
getInitialState: function () {
return {
displaying: false,
comments: app.CommentStore.getAll(this.props.idea_id)
};
},
//when we mount the view setup event listener for store changes
componentDidMount: function () {
app.CommentStore.addChangeListener(function () {
if (this.isMounted()) {
this.setState({ comments: app.CommentStore.getAll(this.props.idea_id) });
}
}.bind(this));
},
show: function () {
if (this.isMounted()) {
this.setState({ displaying: !this.state.displaying });
}
},
//render a comment component for each comment
render: function () {
var comments;
var commentForm;
var showCommentsButton;
//display comments if we are displaying, otherwise show buttons
if (this.state.displaying){
commentForm = <app.CommentForm idea_id={this.props.idea_id} />
comments = [];
//render a comment component for each comment
this.state.comments.forEach(function (comment) {
comments.push(
<app.Comment name={comment.name} key={comment._id} _id={comment._id} idea_id={comment.idea_id} />
);
});
}
showCommentsButton = <button className="pure-button" onClick={this.show}>{this.state.displaying? 'Hide' : 'Show'} Comments</button>
return (
<div ref="body">
{ showCommentsButton }
{ comments }
{ commentForm }
</div>
);
}
});
|
Make version format PEP 440 compatible | import re
import sys
from collections import namedtuple
from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info', 'DEFAULT_TIMEOUT')
__version__ = '0.4.0a0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'c': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool, DEFAULT_TIMEOUT)
| import re
import sys
from collections import namedtuple
from .connection import connect, Connection, TIMEOUT as DEFAULT_TIMEOUT
from .cursor import Cursor
from .pool import create_pool, Pool
__all__ = ('connect', 'create_pool', 'Connection', 'Cursor', 'Pool',
'version', 'version_info', 'DEFAULT_TIMEOUT')
__version__ = '0.4.0a0'
version = __version__ + ' , Python ' + sys.version
VersionInfo = namedtuple('VersionInfo',
'major minor micro releaselevel serial')
def _parse_version(ver):
RE = (r'^(?P<major>\d+)\.(?P<minor>\d+)\.'
'(?P<micro>\d+)((?P<releaselevel>[a-z]+)(?P<serial>\d+)?)?$')
match = re.match(RE, ver)
try:
major = int(match.group('major'))
minor = int(match.group('minor'))
micro = int(match.group('micro'))
levels = {'rc': 'candidate',
'a': 'alpha',
'b': 'beta',
None: 'final'}
releaselevel = levels[match.group('releaselevel')]
serial = int(match.group('serial')) if match.group('serial') else 0
return VersionInfo(major, minor, micro, releaselevel, serial)
except Exception:
raise ImportError("Invalid package version {}".format(ver))
version_info = _parse_version(__version__)
# make pyflakes happy
(connect, create_pool, Connection, Cursor, Pool, DEFAULT_TIMEOUT)
|
Use Google Closure style of marking function parameters as optional. | 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array=} args Additional arguments to pass to `grunt`.
* @return {function(Object)} Testing function for `nodeunit`.
*/
function test(file, valid, args) {
return function(test) {
test.expect(2);
grunt.util.spawn({
grunt: true,
args: [
'--gruntfile', 'test/Gruntfile.js',
'--pkgFile', file
].concat(args || []).concat('npm-validate')
}, function(error, result, code) {
if (valid) {
test.ifError(error);
test.equal(code, 0);
} else {
test.notEqual(error, null);
test.notEqual(code, 0);
}
test.done();
});
};
}
module.exports = {
empty: test('fixtures/empty.json', false),
force: test('fixtures/empty.json', true, ['--force', true]),
minimal: test('fixtures/minimal.json', true),
package: test('../package.json', true),
strict: test('fixtures/minimal.json', false, ['--strict', true])
};
| 'use strict';
var grunt = require('grunt');
/**
* Constructs a test case.
*
* @param {string} file The `package.json` file to be tested.
* @param {boolean} valid Flag indicating whether the test is
* expected to pass.
* @param {Array} [args] Additional arguments to pass to `grunt`.
* @return {function(Object)} Testing function for `nodeunit`.
*/
function test(file, valid, args) {
return function(test) {
test.expect(2);
grunt.util.spawn({
grunt: true,
args: [
'--gruntfile', 'test/Gruntfile.js',
'--pkgFile', file
].concat(args || []).concat('npm-validate')
}, function(error, result, code) {
if (valid) {
test.ifError(error);
test.equal(code, 0);
} else {
test.notEqual(error, null);
test.notEqual(code, 0);
}
test.done();
});
};
}
module.exports = {
empty: test('fixtures/empty.json', false),
force: test('fixtures/empty.json', true, ['--force', true]),
minimal: test('fixtures/minimal.json', true),
package: test('../package.json', true),
strict: test('fixtures/minimal.json', false, ['--strict', true])
};
|
Remove old todo already done | Ext.namespace('ui','ui.component');
// ViewVCDiff
// config - {prefix, fid, fpath, fname, rev1, rev2}
ui.component.ViewVCDiff = Ext.extend(Ext.Panel,
{
layout : 'fit',
title : _('Diff From VCS'),
iconCls : 'iconDiffView',
collapsedIconCls : 'iconDiffView',
plugins : [Ext.ux.PanelCollapsedTitle],
initComponent : function()
{
Ext.apply(this,
{
items : {
id : this.prefix + '-diff-' + this.fid,
xtype : 'panel',
layout : 'fit',
items: [ new Ext.ux.IFrameComponent({
id : 'frame-' + this.prefix + '-diff-' + this.fid,
url : String.format(PhDOE.appConf.viewVcUrl, this.fpath + this.fname, this.rev1, this.rev2)
})
]
}
});
ui.component.ViewVCDiff.superclass.initComponent.call(this);
}
});
| Ext.namespace('ui','ui.component');
// TODO: Extract the URI specific at php's project into the config file to allow use of others projects
// ViewVCDiff
// config - {prefix, fid, fpath, fname, rev1, rev2}
ui.component.ViewVCDiff = Ext.extend(Ext.Panel,
{
layout : 'fit',
title : _('Diff From VCS'),
iconCls : 'iconDiffView',
collapsedIconCls : 'iconDiffView',
plugins : [Ext.ux.PanelCollapsedTitle],
initComponent : function()
{
Ext.apply(this,
{
items : {
id : this.prefix + '-diff-' + this.fid,
xtype : 'panel',
layout : 'fit',
items: [ new Ext.ux.IFrameComponent({
id : 'frame-' + this.prefix + '-diff-' + this.fid,
url : String.format(PhDOE.appConf.viewVcUrl, this.fpath + this.fname, this.rev1, this.rev2)
})
]
}
});
ui.component.ViewVCDiff.superclass.initComponent.call(this);
}
});
|
Fix display issue with versions in worker stats | import React from 'react';
import moment from 'moment';
import Actions from '../actions';
import WorkerStatsStore from '../stores/worker-stats-store';
export default class WorkerPage extends React.Component {
constructor() {
super();
this.state = WorkerStatsStore.getState();
this.fetchTimeout = null;
}
fetch() {
Actions.getWorkerStats();
}
componentDidMount() {
WorkerStatsStore.addChangeListener(this._onChange.bind(this));
this.setState(WorkerStatsStore.getState());
this.fetch();
}
componentWillUnmount() {
WorkerStatsStore.removeChangeListener(this._onChange.bind(this));
}
_onChange() {
this.setState(WorkerStatsStore.getState());
}
render() {
clearTimeout(this.fetchTimeout);
this.fetchTimeout = setTimeout(this.fetch.bind(this), 10000);
return (
<div className="worker-stats-page">
<h2 className="text-center">Worker stats</h2>
<ul className="worker-list">
{this.state.workers.map(worker => {
return (
<li>
<h3>{worker.get('host')}</h3>
{moment(worker.get('lastSeen')).fromNow()}
<dl className="versions">
{(worker.get('versions') || []).map((value, key) => {
return (
<span>
<dt>{key}</dt>
<dd>{value.get('current')}</dd>
</span>
);
})}
</dl>
</li>
);
})}
</ul>
</div>
);
}
}
| import React from 'react';
import moment from 'moment';
import Actions from '../actions';
import WorkerStatsStore from '../stores/worker-stats-store';
export default class WorkerPage extends React.Component {
constructor() {
super();
this.state = WorkerStatsStore.getState();
this.fetchTimeout = null;
}
fetch() {
Actions.getWorkerStats();
}
componentDidMount() {
WorkerStatsStore.addChangeListener(this._onChange.bind(this));
this.setState(WorkerStatsStore.getState());
this.fetch();
}
componentWillUnmount() {
WorkerStatsStore.removeChangeListener(this._onChange.bind(this));
}
_onChange() {
this.setState(WorkerStatsStore.getState());
}
render() {
clearTimeout(this.fetchTimeout);
this.fetchTimeout = setTimeout(this.fetch.bind(this), 10000);
return (
<div className="worker-stats-page">
<h2 className="text-center">Worker stats</h2>
<ul className="worker-list">
{this.state.workers.map(worker => {
return (
<li>
<h3>{worker.get('host')}</h3>
{moment(worker.get('lastSeen')).fromNow()}
<dl className="versions">
{(worker.get('versions') || []).map((value, key) => {
return (
<span>
<dt>{key}</dt>
<dd>{value}</dd>
</span>
);
})}
</dl>
</li>
);
})}
</ul>
</div>
);
}
}
|
Update to use new schema | <?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;
class PhoenixGalleryTransformer extends TransformerAbstract
{
/**
* Transform resource data.
*
* @param \Rogue\Models\Photo $photo
* @return array
*/
public function transform(Post $post)
{
$signup = $post->signup;
$result = [
'id' => $post->postable_id,
'status' => $post->status,
'caption' => $post->caption,
'uri' => $post->file_url,
'media' => [
'uri' => $post->file_url,
'type' => 'image',
],
'created_at' => $post->created_at->toIso8601String(),
'reportback' => [
'id' => $signup->id,
'created_at' => $signup->created_at->toIso8601String(),
'updated_at' => $signup->updated_at->toIso8601String(),
'quantity' => $signup->quantity,
'why_participated' => $signup->why_participated,
'flagged' => 'false',
],
];
return $result;
}
}
| <?php
namespace Rogue\Http\Transformers;
use Rogue\Models\Post;
use League\Fractal\TransformerAbstract;
class PhoenixGalleryTransformer extends TransformerAbstract
{
/**
* Transform resource data.
*
* @param \Rogue\Models\Photo $photo
* @return array
*/
public function transform(Post $post)
{
$signup = $post->signup;
$result = [
'id' => $post->postable_id,
'status' => $post->status,
'caption' => $post->content->caption,
'uri' => $post->content->file_url,
'media' => [
'uri' => $post->content->file_url,
'type' => 'image',
],
'created_at' => $post->created_at->toIso8601String(),
'reportback' => [
'id' => $signup->id,
'created_at' => $signup->created_at->toIso8601String(),
'updated_at' => $signup->updated_at->toIso8601String(),
'quantity' => $signup->quantity,
'why_participated' => $signup->why_participated,
'flagged' => 'false',
],
];
return $result;
}
}
|
Move imports in alphabet order | # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.adapter import *
from sheldon.config import *
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.storage import *
class Sheldon:
"""
Main class of the bot.
Run script creating new instance of this class and run it.
"""
def __init__(self, command_line_arguments):
"""
Function for loading bot.
:param command_line_arguments: dict, arguments for start script
:return:
"""
self._load_config(command_line_arguments)
def _load_config(self, command_line_arguments):
"""
Сreate and load bot config.
:param command_line_arguments: dict, arguments for creating config:
config-prefix - prefix of environment
variables.
Default - 'SHELDON_'
:return:
"""
# Config class is imported from sheldon.config
if 'config-prefix' in command_line_arguments:
self.config = Config(prefix=command_line_arguments['config-prefix'])
else:
self.config = Config()
| # -*- coding: utf-8 -*-
"""
@author: Seva Zhidkov
@contact: [email protected]
@license: The MIT license
Copyright (C) 2015
"""
from sheldon.exceptions import *
from sheldon.manager import *
from sheldon.config import *
from sheldon.adapter import *
from sheldon.storage import *
class Sheldon:
"""
Main class of the bot.
Run script creating new instance of this class and run it.
"""
def __init__(self, command_line_arguments):
"""
Function for loading bot.
:param command_line_arguments: dict, arguments for start script
:return:
"""
self._load_config(command_line_arguments)
def _load_config(self, command_line_arguments):
"""
Сreate and load bot config.
:param command_line_arguments: dict, arguments for creating config:
config-prefix - prefix of environment
variables.
Default - 'SHELDON_'
:return:
"""
# Config class is imported from sheldon.config
if 'config-prefix' in command_line_arguments:
self.config = Config(prefix=command_line_arguments['config-prefix'])
else:
self.config = Config()
|
Fix the recursion bug in KnowledgeBase after the previous refactor. | """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
def __setstate__(self, state):
self._project = state['project']
self.obj = state['obj']
self._plugins = state['plugins']
def __getstate__(self):
s = {
'project': self._project,
'obj': self.obj,
'plugins': self._plugins,
}
return s
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
| """Representing the artifacts of a project."""
from .knowledge_plugins.plugin import default_plugins
class KnowledgeBase(object):
"""Represents a "model" of knowledge about an artifact.
Contains things like a CFG, data references, etc.
"""
def __init__(self, project, obj):
self._project = project
self.obj = obj
self._plugins = {}
@property
def callgraph(self):
return self.functions.callgraph
@property
def unresolved_indirect_jumps(self):
return self.indirect_jumps.unresolved
@property
def resolved_indirect_jumps(self):
return self.indirect_jumps.resolved
#
# Plugin accessor
#
def __contains__(self, plugin_name):
return plugin_name in self._plugins
def __getattr__(self, v):
try:
return self.get_plugin(v)
except KeyError:
raise AttributeError(v)
#
# Plugins
#
def has_plugin(self, name):
return name in self._plugins
def get_plugin(self, name):
if name not in self._plugins:
p = default_plugins[name](self)
self.register_plugin(name, p)
return p
return self._plugins[name]
def register_plugin(self, name, plugin):
self._plugins[name] = plugin
return plugin
def release_plugin(self, name):
if name in self._plugins:
del self._plugins[name]
|
Fix test valid even though it was not | var program = require('commander'),
apiController = require('./apis/apiController')
colors = require('colors'),
ran = false;
var testCb = function(result, apiCall) {
console.log('Test results for ' + apiCall.bold);
if(result !== true) {
for(var i = 0; i < result.length; i++) {
var info = result[i];
switch(info.severity) {
case 'info':
console.log('Info:'.underline.green);
break;
case 'warning':
console.log('Warning:'.underline.yellow);
break;
case 'breaking':
process.exitCode = 1;
console.log('Breaking API change:'.underline.red);
break;
default:
console.log('Unkown severity'.underline.red);
}
console.log(info.type + ': (' + info.path + ')');
console.log('old type: ' + info.oldType);
console.log('new type: ' + info.newType)
if(program.verbose) {
console.log('old data: ', info.oldData);
console.log('new data: ', info.newData);
}
}
}
}
program.arguments('[apiPath]')
.option('-v, --verbose', 'show api dump')
.action(function(apiPath, options) {
ran = true;
if(apiPath) {
apiController.testApi(apiPath, testCb);
}
})
.parse(process.argv);
if(!ran) {
apiController.testAll(testCb);
}
| var program = require('commander'),
apiController = require('./apis/apiController')
colors = require('colors'),
ran = false;
var testCb = function(result, apiCall) {
console.log('Test results for ' + apiCall.bold);
if(result === true) {
process.exit(0);
} else {
for(var i = 0; i < result.length; i++) {
var info = result[i];
switch(info.severity) {
case 'info':
console.log('Info:'.underline.green);
break;
case 'warning':
console.log('Warning:'.underline.yellow);
break;
case 'breaking':
process.exitCode = 1;
console.log('Breaking API change:'.underline.red);
break;
default:
console.log('Unkown severity'.underline.red);
}
console.log(info.type + ': (' + info.path + ')');
console.log('old type: ' + info.oldType);
console.log('new type: ' + info.newType)
if(program.verbose) {
console.log('old data: ', info.oldData);
console.log('new data: ', info.newData);
}
}
}
}
program.arguments('[apiPath]')
.option('-v, --verbose', 'show api dump')
.action(function(apiPath, options) {
ran = true;
if(apiPath) {
apiController.testApi(apiPath, testCb);
}
})
.parse(process.argv);
if(!ran) {
apiController.testAll(testCb);
}
|
Include more exception data on exchange rate failure | import decimal
import logging
import sys
import threading
import requests
logger = logging.getLogger('btc.priceticker.exchangerate')
class ExchangeRate(threading.Thread):
YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv"
YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'}
SLEEP_TIME = 60 * 10
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rate = None
self.stop_event = threading.Event()
self.start()
def get_rate(self):
return self.rate
def stop(self):
self.stop_event.set()
def run(self):
while not self.stop_event.is_set():
try:
logger.debug("Fetching exchange rates from Yahoo Finance...")
csv = requests.get(ExchangeRate.YAHOO_FINANCE_URL, params=ExchangeRate.YAHOO_FINANCE_PARAMS).text
name, rate, date, time = csv.split(',')
self.rate = decimal.Decimal(rate)
self.stop_event.wait(ExchangeRate.SLEEP_TIME)
except:
# Likely a problem with Yahoo's service; log a warning and retry
# Try to include the response text in the log data if it is available
try:
extra = {'response': csv}
except NameError:
extra = {}
logger.warning(
"Couldn't look up USD/NOK exchange rate; ignoring and re-fetching instantly...",
exc_info=sys.exc_info(),
extra=extra,
)
| import decimal
import logging
import threading
import requests
logger = logging.getLogger('btc.priceticker.exchangerate')
class ExchangeRate(threading.Thread):
YAHOO_FINANCE_URL = "https://download.finance.yahoo.com/d/quotes.csv"
YAHOO_FINANCE_PARAMS = {'e': '.csv', 'f': 'sl1d1t1', 's': 'USDNOK=X'}
SLEEP_TIME = 60 * 10
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.rate = None
self.stop_event = threading.Event()
self.start()
def get_rate(self):
return self.rate
def stop(self):
self.stop_event.set()
def run(self):
while not self.stop_event.is_set():
try:
logger.debug("Fetching exchange rates from Yahoo Finance...")
csv = requests.get(ExchangeRate.YAHOO_FINANCE_URL, params=ExchangeRate.YAHOO_FINANCE_PARAMS).text
name, rate, date, time = csv.split(',')
self.rate = decimal.Decimal(rate)
self.stop_event.wait(ExchangeRate.SLEEP_TIME)
except Exception as e:
logger.warning("Unhandled exception: %s" % e)
logger.warning("Ignoring and trying to re-fetch exchange rate...")
|
Check that params can be null | package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Date: 07.06.14
* Time: 12:24
* <p>Representation of a JSON-RPC request</p>
*/
public class Request {
@Nullable
private final String jsonrpc;
@Nullable
private final String method;
@Nullable
private final JsonNode params;
@Nullable
private final ValueNode id;
public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc,
@JsonProperty("method") @Nullable String method,
@JsonProperty("params") @Nullable JsonNode params,
@JsonProperty("id") @Nullable ValueNode id) {
this.jsonrpc = jsonrpc;
this.method = method;
this.id = id;
this.params = params;
}
@Nullable
public String getJsonrpc() {
return jsonrpc;
}
@Nullable
public String getMethod() {
return method;
}
@NotNull
public ValueNode getId() {
return id != null ? id : NullNode.getInstance();
}
@NotNull
public JsonNode getParams() {
return params != null ? params : NullNode.getInstance();
}
@Override
public String toString() {
return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}";
}
}
| package com.github.arteam.simplejsonrpc.core.domain;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.NullNode;
import com.fasterxml.jackson.databind.node.ValueNode;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Date: 07.06.14
* Time: 12:24
* <p>Representation of a JSON-RPC request</p>
*/
public class Request {
@Nullable
private final String jsonrpc;
@Nullable
private final String method;
@NotNull
private final JsonNode params;
@Nullable
private final ValueNode id;
public Request(@JsonProperty("jsonrpc") @Nullable String jsonrpc,
@JsonProperty("method") @Nullable String method,
@JsonProperty("params") @NotNull JsonNode params,
@JsonProperty("id") @Nullable ValueNode id) {
this.jsonrpc = jsonrpc;
this.method = method;
this.id = id;
this.params = params;
}
@Nullable
public String getJsonrpc() {
return jsonrpc;
}
@Nullable
public String getMethod() {
return method;
}
@NotNull
public ValueNode getId() {
return id != null ? id : NullNode.getInstance();
}
@NotNull
public JsonNode getParams() {
return params;
}
@Override
public String toString() {
return "Request{jsonrpc=" + jsonrpc + ", method=" + method + ", id=" + id + ", params=" + params + "}";
}
}
|
Add comment to explain query/insert in migration | <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->timestamps();
$table->primary(['post_id', 'tag_id']);
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
});
$now = Carbon\Carbon::now();
// This is here to migrate any data someone might have into the new post-tag table.
collect(DB::table('post_tag_pivot')->get())->each(function ($item) {
DB::table('post_tag')->insert([
'post_id' => $item->post_id,
'tag_id' => $item->tag_id,
'created_at' => $now,
'updated_at' => $now,
]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('post_tag');
}
}
| <?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->integer('post_id')->unsigned();
$table->integer('tag_id')->unsigned();
$table->timestamps();
$table->primary(['post_id', 'tag_id']);
$table->foreign('post_id')->references('id')->on('posts')->onUpdate('cascade')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onUpdate('cascade')->onDelete('cascade');
});
$now = Carbon\Carbon::now();
collect(DB::table('post_tag_pivot')->get())->each(function ($item) {
DB::table('post_tag')->insert([
'post_id' => $item->post_id,
'tag_id' => $item->tag_id,
'created_at' => $now,
'updated_at' => $now,
]);
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('post_tag');
}
}
|
Remove useless SelectorFunction for ISO | package io.fotoapparat.parameter.selector;
import io.fotoapparat.parameter.range.Range;
/**
* Selector functions for sensor sensitivity (ISO).
*/
public class SensorSensitivitySelectors {
/**
* @param iso the specified ISO value
* @return {@link SelectorFunction} which selects the specified ISO value.
* If there is no specified value - selects default ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> manualSensorSensitivity(final int iso) {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
if(sensorSensitivityCapability.contains(iso)) {
return iso;
} else {
return null;
}
}
};
}
/**
* @return {@link SelectorFunction} which selects highest ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> highestSensorSensitivity() {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
return sensorSensitivityCapability.highest();
}
};
}
/**
* @return {@link SelectorFunction} which selects lowest ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> lowestSensorSensitivity() {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
return sensorSensitivityCapability.lowest();
}
};
}
}
| package io.fotoapparat.parameter.selector;
import io.fotoapparat.parameter.range.Range;
/**
* Selector functions for sensor sensitivity (ISO).
*/
public class SensorSensitivitySelectors {
/**
* @param iso the specified ISO value
* @return {@link SelectorFunction} which selects the specified ISO value.
* If there is no specified value - selects default ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> manualSensorSensitivity(final int iso) {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
if(sensorSensitivityCapability.contains(iso)) {
return iso;
} else {
return null;
}
}
};
}
/**
* @return {@link SelectorFunction} which selects highest ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> highestSensorSensitivity() {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
return sensorSensitivityCapability.highest();
}
};
}
/**
* @return {@link SelectorFunction} which selects lowest ISO value.
*/
public static SelectorFunction<Range<Integer>, Integer> lowestSensorSensitivity() {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> sensorSensitivityCapability) {
return sensorSensitivityCapability.lowest();
}
};
}
/**
* @return {@link SelectorFunction} which selects default ISO value.
*/
public static SelectorFunction<Range<Integer>,Integer> automaticSensorSensitivity() {
return new SelectorFunction<Range<Integer>, Integer>() {
@Override
public Integer select(Range<Integer> integerRange) {
return null;
}
};
}
}
|
Change selenium browser to firefox. | """
Module to hold basic home Selenium tests.
"""
from selenium import selenium
import unittest, time, re, os, sys, subprocess
def rel_to_abs(path):
"""
Function to take relative path and make absolute
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(current_dir, path)
class test_home(unittest.TestCase):
"""
Tests that the home page can be reached and home link can be used.
"""
def setUp(self):
self.verificationErrors = []
# Database
# Start application
config = rel_to_abs("../../lighttpd.conf")
self.server_proc = subprocess.Popen(["lighttpd -D -f %s" % config], shell = True)
# Start selenium
self.selenium = selenium("localhost", 4443, "*firefox", "http://localhost:8080/")
self.selenium.start()
def test_test_home(self):
"""
Actual test that checks the home page can be reached and home link can be used.
"""
sel = self.selenium
sel.open("/")
sel.click("link=Change by Us NYC")
sel.wait_for_page_to_load("20000")
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
self.server_proc.kill()
if __name__ == "__main__":
unittest.main()
| """
Module to hold basic home Selenium tests.
"""
from selenium import selenium
import unittest, time, re, os, sys, subprocess
def rel_to_abs(path):
"""
Function to take relative path and make absolute
"""
current_dir = os.path.abspath(os.path.dirname(__file__))
return os.path.join(current_dir, path)
class test_home(unittest.TestCase):
"""
Tests that the home page can be reached and home link can be used.
"""
def setUp(self):
self.verificationErrors = []
# Database
# Start application
config = rel_to_abs("../../lighttpd.conf")
self.server_proc = subprocess.Popen(["lighttpd -D -f %s" % config], shell = True)
# Start selenium
self.selenium = selenium("localhost", 4443, "*chrome", "http://localhost:8080/")
self.selenium.start()
def test_test_home(self):
"""
Actual test that checks the home page can be reached and home link can be used.
"""
sel = self.selenium
sel.open("/")
sel.click("link=Change by Us NYC")
sel.wait_for_page_to_load("20000")
def tearDown(self):
self.selenium.stop()
self.assertEqual([], self.verificationErrors)
self.server_proc.kill()
if __name__ == "__main__":
unittest.main()
|
Reduce results per page to 30 | import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = None
DM_SEARCH_PAGE_SIZE = 30
DM_ID_ONLY_SEARCH_PAGE_SIZE_MULTIPLIER = 10
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'search-api'
DM_PLAIN_TEXT_LOGS = False
DM_LOG_PATH = None
VCAP_SERVICES = None
DM_ELASTICSEARCH_SERVICE_NAME = "search_api_elasticsearch"
@staticmethod
def init_app(app):
pass
class Test(Config):
DEBUG = True
DM_PLAIN_TEXT_LOGS = True
DM_LOG_LEVEL = 'CRITICAL'
DM_SEARCH_API_AUTH_TOKENS = 'valid-token'
class Development(Config):
DEBUG = True
DM_PLAIN_TEXT_LOGS = True
DM_SEARCH_PAGE_SIZE = 5
DM_SEARCH_API_AUTH_TOKENS = 'myToken'
class Live(Config):
DEBUG = False
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
config = {
'development': Development,
'preview': Live,
'staging': Live,
'production': Live,
'test': Test,
}
| import os
from dmutils.status import get_version_label
basedir = os.path.abspath(os.path.dirname(__file__))
class Config:
VERSION = get_version_label(
os.path.abspath(os.path.dirname(__file__))
)
AUTH_REQUIRED = True
ELASTICSEARCH_HOST = 'localhost:9200'
DM_SEARCH_API_AUTH_TOKENS = None
DM_SEARCH_PAGE_SIZE = 100
DM_ID_ONLY_SEARCH_PAGE_SIZE_MULTIPLIER = 10
# Logging
DM_LOG_LEVEL = 'DEBUG'
DM_APP_NAME = 'search-api'
DM_PLAIN_TEXT_LOGS = False
DM_LOG_PATH = None
VCAP_SERVICES = None
DM_ELASTICSEARCH_SERVICE_NAME = "search_api_elasticsearch"
@staticmethod
def init_app(app):
pass
class Test(Config):
DEBUG = True
DM_PLAIN_TEXT_LOGS = True
DM_LOG_LEVEL = 'CRITICAL'
DM_SEARCH_API_AUTH_TOKENS = 'valid-token'
class Development(Config):
DEBUG = True
DM_PLAIN_TEXT_LOGS = True
DM_SEARCH_PAGE_SIZE = 5
DM_SEARCH_API_AUTH_TOKENS = 'myToken'
class Live(Config):
DEBUG = False
DM_LOG_PATH = '/var/log/digitalmarketplace/application.log'
config = {
'development': Development,
'preview': Live,
'staging': Live,
'production': Live,
'test': Test,
}
|
UPDATE: Throw exception if we are going to divide by 0 | <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author Cam Spiers <[email protected]>
* @package Statistical Classifier
*/
class DocumentLength
{
public function __invoke($tfidf)
{
$transform = $tfidf;
foreach ($tfidf as $category => $documents) {
foreach ($documents as $documentIndex => $document) {
$denominator = 0;
foreach ($document as $count) {
$denominator += $count * $count;
}
$denominator = sqrt($denominator);
if ($denominator != 0) {
foreach ($document as $token => $count) {
$transform
[$category]
[$documentIndex]
[$token] = $count / $denominator;
}
} else {
throw new \RuntimeException("Cannot divide by 0 in DocumentLength transform");
}
}
}
return $transform;
}
}
| <?php
/**
* This file is part of the Statistical Classifier package.
*
* (c) Cam Spiers <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Camspiers\StatisticalClassifier\Transform;
/**
* @author Cam Spiers <[email protected]>
* @package Statistical Classifier
*/
class DocumentLength
{
public function __invoke($tfidf)
{
$transform = $tfidf;
foreach ($tfidf as $category => $documents) {
foreach ($documents as $documentIndex => $document) {
$denominator = 0;
foreach ($document as $count) {
$denominator += $count * $count;
}
$denominator = sqrt($denominator);
if ($denominator !== 0) {
foreach ($document as $token => $count) {
$transform
[$category]
[$documentIndex]
[$token] = $count / $denominator;
}
} else {
throw new \RuntimeException("Cannot divide by 0 in DocumentLength transform");
}
}
}
return $transform;
}
}
|
Remove useless TODO from codebase. | """
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
| """
funsize.fetch
~~~~~~~~~~~~~~~~~~
This module contains fetch functions
"""
import logging
import requests
from .csum import verify
from .oddity import DownloadError
def downloadmar(url, checksum, cipher='sha512', output_file=None):
""" Downloads the file specified by url, verifies the checksum.
The file is written to the location specified by output file,
if not specified, the downloaded file is returned.
List of Ciphers supported is the same as those supported by
`csum.py`
"""
logging.debug('Starting download for %s with checksum: %s', url, checksum)
response = requests.get(url)
if response.status_code != requests.codes.ok:
logging.debug('HTTP Request to %s failed with error code %d',
url, response.status_code)
raise DownloadError('HTTP Request response error')
mar = response.content
if not verify(mar, checksum, cipher):
logging.warning('Verification of %s with checksum %s failed',
url, checksum)
raise DownloadError('Checksums do not match')
else:
logging.info('Verified download of %s', url)
if output_file:
try:
logging.info('Writing download %s to file %s', url, output_file)
# TODO ROUGHEDGE write in blocks of 1MB anc check afterwards?
with open(output_file, 'wb') as fobj:
fobj.write(mar)
except:
logging.error('Error while downloading %s to file %s on disk',
url, output_file)
raise DownloadError('Failed to write file to disk')
else:
return None
else:
return mar
|
Reposition tooltips when window is resized | define(
["jquery"],
function($) {
function Tutorial(steps, content) {
var _this = this;
var currentIdx;
function show(idx) {
var step = steps[idx];
if (step.init) step.init.apply(_this);
step.$content = $('[data-step="' + step.name + '"]', content);
step.$content.dialog({
dialogClass: [].concat("tutorial-dialog", step.dialogClass || []).join(' '),
maxWidth: 300,
modal: false,
resizable: false,
position: step.position
});
step.resize = function resize() {
step.$content.dialog("option", "position", step.position);
};
$(window).on('resize', step.resize);
}
function hide(idx) {
var step = steps[idx];
if (step.destroy) step.destroy.apply(_this);
step.$content.dialog('destroy');
$(window).off('resize', step.resize);
}
this.start = function() {
currentIdx = 0;
show(currentIdx);
};
this.next = function() {
if (currentIdx >= steps.length) return;
hide(currentIdx);
currentIdx++;
if (currentIdx < steps.length) show(currentIdx);
}
this.end = function() {
hide(currentIdx);
currentIdx = steps.length;
};
$('.tutorial-next', content).click(function () {
_this.next();
return false;
});
$('.tutorial-end', content).click(function () {
_this.end();
return false;
});
return this;
};
return Tutorial;
}
);
| define(
["jquery"],
function($) {
function Tutorial(steps, content) {
var _this = this;
var currentIdx;
function show(idx) {
var step = steps[idx];
if (step.init) step.init.apply(_this);
step.$content = $('[data-step="' + step.name + '"]', content);
step.$content.dialog({
dialogClass: [].concat("tutorial-dialog", step.dialogClass || []).join(' '),
maxWidth: 300,
modal: false,
resizable: false,
position: step.position
});
}
function hide(idx) {
var step = steps[idx];
if (step.destroy) step.destroy.apply(_this);
step.$content.dialog('destroy');
}
this.start = function() {
currentIdx = 0;
show(currentIdx);
};
this.next = function() {
if (currentIdx >= steps.length) return;
hide(currentIdx);
currentIdx++;
if (currentIdx < steps.length) show(currentIdx);
}
this.end = function() {
hide(currentIdx);
currentIdx = steps.length;
};
$('.tutorial-next', content).click(function () {
_this.next();
return false;
});
$('.tutorial-end', content).click(function () {
_this.end();
return false;
});
return this;
};
return Tutorial;
}
);
|
feat: Add method that updates all focusable elements when called | import Ember from 'ember';
import $ from 'jquery';
export default Ember.Mixin.create({
focusableElementQuery: 'select:not([disabled]), button:not([disabled]), [tabindex="0"], input:not([disabled]), a[href]',
lockBackground (obj) {
const element = document.getElementById(obj.elementId);
this.set('trapElementID', obj.elementId);
this.set('focusableElements', element.querySelectorAll(this.get('focusableElementQuery')));
let backgroundActiveEl = document.activeElement;
// Focus first element in modal
firstEl.focus();
$(element).keydown(event => {
// If Esc pressed
if (event.keyCode === 27) {
backgroundActiveEl.focus();
$(`#${obj.elementId}`).off('keydown');
obj.callback.call(this);
return;
}
// Trap Tab key while modal open
this.trapTabKey(event);
event.stopPropagation();
});
},
trapTabKey (event) {
if (event.keyCode === 9) {
if (event.shiftKey) {
if (document.activeElement === this.get('focusableElements')[0]) {
event.preventDefault();
return this.get('focusableElements')[this.get('focusableElements').length - 1].focus();
}
} else {
if (document.activeElement === this.get('focusableElements')[this.get('focusableElements').length - 1]) {
event.preventDefault();
return this.get('focusableElements')[0].focus();
}
}
}
},
updateRegisteredKeys () {
const element = document.getElementById(this.get('trapElementID'));
return this.set('focusableElements', element.querySelectorAll(this.get('focusableElementQuery')));
}
});
| import Ember from 'ember';
import $ from 'jquery';
export default Ember.Mixin.create({
lockBackground (obj) {
const focusableElementQuery = 'select:not([disabled]), button:not([disabled]), [tabindex="0"], input:not([disabled]), a[href]';
const element = document.getElementById(obj.elementId);
const backgroundActiveEl = document.activeElement;
const focusableElements = element.querySelectorAll(focusableElementQuery);
const firstEl = focusableElements[0];
const lastEl = focusableElements[focusableElements.length - 1];
// Focus first element in modal
firstEl.focus();
$(element).keydown(event => {
// If Esc pressed
if (event.keyCode === 27) {
backgroundActiveEl.focus();
obj.callback.call(this);
return;
}
// Trap Tab key while modal open
this.trapTabKey(event, firstEl, lastEl);
});
},
trapTabKey (event, ...params) {
const [ firstEl, lastEl ] = params;
if (event.keyCode === 9) {
if (event.shiftKey) {
if (document.activeElement === firstEl) {
event.preventDefault();
return lastEl.focus();
}
} else {
if (document.activeElement === lastEl) {
event.preventDefault();
return firstEl.focus();
}
}
}
}
});
|
Add user to db.session only when it has been created | from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda **context: code.interact('', local=context)
else:
ipython = InteractiveShellEmbed(banner1='')
return lambda **context: ipython(global_ns={}, local_ns=context)
def get_oauth2_handler():
GITHUB = current_app.config['GITHUB']
return OAuth2(
GITHUB['client_id'], GITHUB['client_secret'], GITHUB['auth_url'],
'', GITHUB['authorize_url'], GITHUB['token_url']
)
def get_user_by_token(access_token):
api = Github(access_token)
github_user = api.get_user()
user = db.session.query(User).filter_by(github_id=github_user.id).first()
if user is None:
user = User(
github_access_token=access_token,
github_id=github_user.id,
name=github_user.name,
email=github_user.email,
login=github_user.login,
)
db.session.add(user)
else:
user.github_access_token = access_token
user.login = github_user.login
db.session.commit()
return user
| from alfred_db.models import User
from flask import current_app
from github import Github
from requests_oauth2 import OAuth2
from .database import db
def get_shell():
try:
from IPython.frontend.terminal.embed import InteractiveShellEmbed
except ImportError:
import code
return lambda **context: code.interact('', local=context)
else:
ipython = InteractiveShellEmbed(banner1='')
return lambda **context: ipython(global_ns={}, local_ns=context)
def get_oauth2_handler():
GITHUB = current_app.config['GITHUB']
return OAuth2(
GITHUB['client_id'], GITHUB['client_secret'], GITHUB['auth_url'],
'', GITHUB['authorize_url'], GITHUB['token_url']
)
def get_user_by_token(access_token):
api = Github(access_token)
github_user = api.get_user()
user = db.session.query(User).filter_by(github_id=github_user.id).first()
if user is None:
user = User(
github_access_token=access_token,
github_id=github_user.id,
name=github_user.name,
email=github_user.email,
login=github_user.login,
)
else:
user.github_access_token = access_token
user.login = github_user.login
db.session.add(user)
db.session.commit()
return user
|
Remove unnecessary dependency from unit test | package com.mdaniline.spring.autoproperties;
import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
public class AutoPropertiesRegistrarTest {
private BeanDefinitionRegistry registry;
private AnnotationMetadata metadata;
private AutoPropertiesRegistrar underTest;
@Before
public void setUp() throws Exception {
metadata = new StandardAnnotationMetadata(TestConfig.class, true);
registry = new DefaultListableBeanFactory();
underTest = new AutoPropertiesRegistrar();
}
@Test
public void givenPackageWithAnnotatedInterfaces_registerDefinitions_addsExpectedBeansToRegistryWithExpectedNames() {
underTest.setResourceLoader(new DefaultResourceLoader());
underTest.setEnvironment(new StandardEnvironment());
underTest.registerBeanDefinitions(metadata, registry);
List<String> beanNames = Arrays.asList(registry.getBeanDefinitionNames());
assertThat(beanNames, contains("testBasicProperties"));
}
@EnableAutoProperties(basePackageClasses = TestBasicProperties.class)
private class TestConfig {
}
} | package com.mdaniline.spring.autoproperties;
import com.mdaniline.spring.autoproperties.testclasses.TestBasicProperties;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;
import java.util.Arrays;
import java.util.List;
import static org.hamcrest.Matchers.contains;
import static org.junit.Assert.*;
public class AutoPropertiesRegistrarTest {
private BeanDefinitionRegistry registry;
private AnnotationMetadata metadata;
private AutoPropertiesRegistrar underTest;
@Before
public void setUp() throws Exception {
metadata = new StandardAnnotationMetadata(TestConfig.class, true);
registry = new DefaultListableBeanFactory();
underTest = new AutoPropertiesRegistrar();
}
@Test
public void givenPackageWithAnnotatedInterfaces_registerDefinitions_addsExpectedBeansToRegistryWithExpectedNames() {
underTest.setResourceLoader(new DefaultResourceLoader());
underTest.setEnvironment(new StandardEnvironment());
underTest.registerBeanDefinitions(metadata, registry);
List<String> beanNames = Arrays.asList(registry.getBeanDefinitionNames());
assertThat(beanNames, contains("testBasicProperties"));
}
@EnableAutoProperties(basePackageClasses = TestBasicProperties.class)
private class TestConfig {
}
} |
Fix for typing mistake of requireds which should be required in create user form | @extends(Config::get('cpanel::views.layout'))
@section('header')
<h3>
<i class="icon-user"></i>
Users
</h3>
@stop
@section('help')
<p class="lead">Users</p>
<p>
From here you can create, edit or delete users. Also you can assign custom permissions to a single user.
</p>
@stop
@section('content')
<div class="row">
<div class="span12">
{{Former::horizontal_open( route('admin.users.store') )}}
<div class="block">
<p class="block-heading">Add User</p>
<div class="block-body">
<legend><small>items mark with * are required.</small></legend>
{{ Former::xlarge_text('first_name', 'First Name')->required() }}
{{ Former::xlarge_text('last_name', 'Last Name')->required() }}
{{ Former::xlarge_text('email','Email')->required() }}
<legend>Password</legend>
{{ Former::xlarge_password('password', 'Password')->required() }}
{{ Former::xlarge_password('password_confirmation', 'Confirm Password')->required() }}
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<a href="{{route('admin.users.index')}}" class="btn">Cancel</a>
</div>
</div>
</div>
{{Former::close()}}
</div>
</div>
@stop
| @extends(Config::get('cpanel::views.layout'))
@section('header')
<h3>
<i class="icon-user"></i>
Users
</h3>
@stop
@section('help')
<p class="lead">Users</p>
<p>
From here you can create, edit or delete users. Also you can assign custom permissions to a single user.
</p>
@stop
@section('content')
<div class="row">
<div class="span12">
{{Former::horizontal_open( route('admin.users.store') )}}
<div class="block">
<p class="block-heading">Add User</p>
<div class="block-body">
<legend><small>items mark with * are required.</small></legend>
{{ Former::xlarge_text('first_name', 'First Name')->requireds() }}
{{ Former::xlarge_text('last_name', 'Last Name')->requireds() }}
{{ Former::xlarge_text('email','Email')->requireds() }}
<legend>Password</legend>
{{ Former::xlarge_password('password', 'Password')->requireds() }}
{{ Former::xlarge_password('password_confirmation', 'Confirm Password')->requireds() }}
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<a href="{{route('admin.users.index')}}" class="btn">Cancel</a>
</div>
</div>
</div>
{{Former::close()}}
</div>
</div>
@stop
|
Set no of records per page to 500 in search current actions call. | <?php
namespace LaravelLb;
use LaravelLb\LogicBoxes;
class LogicBoxesActions extends LogicBoxes {
public function __construct()
{
parent::__construct();
$this->resource = "actions";
}
/**
* Gets the Current Actions based on the criteria specified.
* http://manage.logicboxes.com/kb/answer/908
* @return LogicboxesCommon
*/
public function searchCurrentActions($variables = [], $pageNo = 1, $noOfRecords = 500)
{
$method = 'search-current';
$variables = array_merge($variables, [
'page-no' => $pageNo,
'no-of-records' => $noOfRecords,
]);
$response = $this->get($this->resource, $method, $variables);
return $this;
}
/**
* Searches the Archived Actions based on the criteria specified.
* http://manage.logicboxes.com/kb/answer/909
* @return LogicboxesCommon
*/
public function searchArchivedActions($variables = [], $pageNo = 1, $noOfRecords = 500)
{
$method = 'search-archived';
$variables = array_merge($variables, [
'page-no' => $pageNo,
'no-of-records' => $noOfRecords,
]);
$response = $this->get($this->resource, $method, $variables);
return $this;
}
}
| <?php
namespace LaravelLb;
use LaravelLb\LogicBoxes;
class LogicBoxesActions extends LogicBoxes {
public function __construct()
{
parent::__construct();
$this->resource = "actions";
}
/**
* Gets the Current Actions based on the criteria specified.
* http://manage.logicboxes.com/kb/answer/908
* @return LogicboxesCommon
*/
public function searchCurrentActions($variables = [], $pageNo = 1, $noOfRecords = 100)
{
$method = 'search-current';
$variables = array_merge($variables, [
'page-no' => $pageNo,
'no-of-records' => $noOfRecords,
]);
$response = $this->get($this->resource, $method, $variables);
return $this;
}
/**
* Searches the Archived Actions based on the criteria specified.
* http://manage.logicboxes.com/kb/answer/909
* @return LogicboxesCommon
*/
public function searchArchivedActions($variables = [], $pageNo = 1, $noOfRecords = 100)
{
$method = 'search-archived';
$variables = array_merge($variables, [
'page-no' => $pageNo,
'no-of-records' => $noOfRecords,
]);
$response = $this->get($this->resource, $method, $variables);
return $this;
}
}
|
Throw an error, not just a plain string | "use strict";
import Guard from './Guard';
class EventContext {
constructor(modelId, eventType, event) {
Guard.isString(modelId, "The modelId should be a string");
Guard.isString(eventType, "The eventType should be a string");
Guard.isDefined(event, "The event should be defined");
this._modelId = modelId;
this._eventType = eventType;
this._event = event;
this._isCanceled = false;
this._isCommitted = false;
}
get isCanceled() {
return this._isCanceled;
}
get isCommitted() {
return this._isCommitted;
}
get modelId() {
return this._modelId;
}
get event() {
return this._event;
}
get eventType() {
return this._eventType;
}
cancel() {
if(!this._isCanceled) {
this._isCanceled = true;
} else {
throw new Error('event is already cancelled');
}
}
commit() {
if(!this._isCommitted) {
this._isCommitted = true;
} else {
throw 'event is already committed';
}
}
}
export default EventContext;
| "use strict";
import Guard from './Guard';
class EventContext {
constructor(modelId, eventType, event) {
Guard.isString(modelId, "The modelId should be a string");
Guard.isString(eventType, "The eventType should be a string");
Guard.isDefined(event, "The event should be defined");
this._modelId = modelId;
this._eventType = eventType;
this._event = event;
this._isCanceled = false;
this._isCommitted = false;
}
get isCanceled() {
return this._isCanceled;
}
get isCommitted() {
return this._isCommitted;
}
get modelId() {
return this._modelId;
}
get event() {
return this._event;
}
get eventType() {
return this._eventType;
}
cancel() {
if(!this._isCanceled) {
this._isCanceled = true;
} else {
throw 'event is already canceled';
}
}
commit() {
if(!this._isCommitted) {
this._isCommitted = true;
} else {
throw 'event is already committed';
}
}
}
export default EventContext;
|
Fix stress test which was not changed to receive one client value
Change-Id: I186f2827c91d8b1eabd0769dda4765a973bf42b4
Closes-Bug: 1413980 | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from tempest.common.utils import data_utils
import tempest.stress.stressaction as stressaction
class VolumeCreateDeleteTest(stressaction.StressAction):
def run(self):
name = data_utils.rand_name("volume")
self.logger.info("creating %s" % name)
volumes_client = self.manager.volumes_client
volume = volumes_client.create_volume(size=1,
display_name=name)
vol_id = volume['id']
volumes_client.wait_for_volume_status(vol_id, 'available')
self.logger.info("created %s" % volume['id'])
self.logger.info("deleting %s" % name)
volumes_client.delete_volume(vol_id)
volumes_client.wait_for_resource_deletion(vol_id)
self.logger.info("deleted %s" % vol_id)
| # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from tempest.common.utils import data_utils
import tempest.stress.stressaction as stressaction
class VolumeCreateDeleteTest(stressaction.StressAction):
def run(self):
name = data_utils.rand_name("volume")
self.logger.info("creating %s" % name)
volumes_client = self.manager.volumes_client
_, volume = volumes_client.create_volume(size=1,
display_name=name)
vol_id = volume['id']
volumes_client.wait_for_volume_status(vol_id, 'available')
self.logger.info("created %s" % volume['id'])
self.logger.info("deleting %s" % name)
volumes_client.delete_volume(vol_id)
volumes_client.wait_for_resource_deletion(vol_id)
self.logger.info("deleted %s" % vol_id)
|
Fix for "java.lang.IllegalArgumentException: Cannot pass a null GrantedAuthority array" | /**
*
*/
package org.jenkinsci.plugins;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.kohsuke.github.GHUser;
import javax.annotation.Nonnull;
import java.io.IOException;
/**
* @author Mike
*
*/
@SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS")
public class GithubOAuthUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
private boolean hasGrantedAuthorities;
private final GithubAuthenticationToken authenticationToken;
public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GrantedAuthority[] authorities) {
super(login, "", true, true, true, true, authorities);
this.authenticationToken = null;
this.hasGrantedAuthorities = true;
}
public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GithubAuthenticationToken authenticationToken) {
super(login, "", true, true, true, true, new GrantedAuthority[0]);
this.authenticationToken = authenticationToken;
this.hasGrantedAuthorities = false;
}
@Override
public GrantedAuthority[] getAuthorities() {
if (!hasGrantedAuthorities) {
try {
GHUser user = authenticationToken.loadUser(getUsername());
setAuthorities(authenticationToken.getGrantedAuthorities(user));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return super.getAuthorities();
}
}
| /**
*
*/
package org.jenkinsci.plugins;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import org.kohsuke.github.GHUser;
import javax.annotation.Nonnull;
import java.io.IOException;
/**
* @author Mike
*
*/
@SuppressFBWarnings("EQ_DOESNT_OVERRIDE_EQUALS")
public class GithubOAuthUserDetails extends User implements UserDetails {
private static final long serialVersionUID = 1L;
private final GithubAuthenticationToken authenticationToken;
public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GrantedAuthority[] authorities) {
super(login, "", true, true, true, true, authorities);
this.authenticationToken = null;
}
public GithubOAuthUserDetails(@Nonnull String login, @Nonnull GithubAuthenticationToken authenticationToken) {
super(login, "", true, true, true, true, null);
this.authenticationToken = authenticationToken;
}
@Override
public GrantedAuthority[] getAuthorities() {
if (super.getAuthorities() == null) {
try {
GHUser user = authenticationToken.loadUser(getUsername());
setAuthorities(authenticationToken.getGrantedAuthorities(user));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
return super.getAuthorities();
}
}
|
Use normal Resource as default for ResourceList
to avoid potential circular import. | from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
| from pale.fields.base import BaseField, ListField
from pale.resource import Resource
class ResourceField(BaseField):
"""A field that contains a nested resource"""
value_type = 'resource'
def __init__(self,
description,
details=None,
resource_type=Resource,
subfields=None):
self.description = description
self.details = details
self.resource_type = resource_type
if subfields is None:
subfields = resource_type._default_fields
self.subfields = subfields
self.resource_instance = self.resource_type(
'nested_resource',
fields=self.subfields)
def doc_dict(self):
doc = super(ResourceField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
doc['default_fields'] = self.subfields
def render(self, obj, name, context):
instance = getattr(obj, name)
renderer = self.resource_instance._render_serializable
output = renderer(instance, context)
return output
class ResourceListField(ListField):
"""A Field that contains a list of Fields."""
value_type = 'list'
def __init__(self,
description,
details=None,
resource_type=DebugResource,
subfields=None):
self.description = description
self.details = details
self.item_type = ResourceField
self.resource_type = resource_type
def doc_dict(self):
doc = super(ResourceListField, self).doc_dict()
doc['resource_type'] = self.resource_type._value_type
return doc
|
Handle the case where the user may already exist in the database | """
A management command to create a user with a given email.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from ixprofile_client.webservice import UserWebService
from optparse import make_option
class Command(BaseCommand):
"""
The command to create a superuser with a given email.
"""
option_list = BaseCommand.option_list + (
make_option('--email', default=None,
help='Specifies the email for the superuser.'),
make_option('--noinput',
action='store_false',
dest='interactive',
default=True,
help='Tells Django to NOT prompt the user for input of ' +
'any kind. You must use --email with --noinput.'),
)
def handle(self, *args, **options):
interactive = options.get('interactive')
email = options.get('email')
verbosity = int(options.get('verbosity', 1))
if interactive and not email:
email = raw_input("Email: ")
if not email:
raise CommandError("No email given.")
with transaction.atomic():
user, created = User.objects.get_or_create(email=email)
user.set_password(None)
user.is_active = True
user.is_staff = True
user.is_superuser = True
user_ws = UserWebService()
user_ws.connect(user)
if verbosity >= 1:
if created:
self.stdout.write("Superuser created successfully.")
else:
self.stdout.write("Superuser flag added successfully.")
| """
A management command to create a user with a given email.
"""
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand, CommandError
from ixprofile_client.webservice import UserWebService
from optparse import make_option
class Command(BaseCommand):
"""
The command to create a superuser with a given email.
"""
option_list = BaseCommand.option_list + (
make_option('--email', default=None,
help='Specifies the email for the superuser.'),
make_option('--noinput',
action='store_false',
dest='interactive',
default=True,
help='Tells Django to NOT prompt the user for input of ' +
'any kind. You must use --email with --noinput.'),
)
def handle(self, *args, **options):
interactive = options.get('interactive')
email = options.get('email')
verbosity = int(options.get('verbosity', 1))
if interactive and not email:
email = raw_input("Email: ")
if not email:
raise CommandError("No email given.")
user = User()
user.email = email
user.set_password(None)
user.is_active = True
user.is_staff = True
user.is_superuser = True
user_ws = UserWebService()
user_ws.connect(user)
if verbosity >= 1:
self.stdout.write("Superuser created successfully.")
|
Remove calculation finishing the test | <?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\Calculation;
use AppBundle\Model\CalculationFactory;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SimpleRasterTest extends WebTestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* @var Calculation $project
*/
protected $calculation;
/**
* {@inheritDoc}
*/
public function setUp()
{
self::bootKernel();
$this->entityManager = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
}
/**
*
*/
public function testAddMultipleArrayToCalculatedValues()
{
$submittedValues = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$this->calculation = CalculationFactory::create();
$this->calculation->setValues($submittedValues);
$this->entityManager->persist($this->calculation);
$this->entityManager->flush();
$this->entityManager->clear();
$calculation = $this->entityManager->getRepository('AppBundle:Calculation')
->findOneBy(array(
'id' => $this->calculation->getId()
))
;
$values = $calculation->getValues();
$this->assertEquals($submittedValues, $values);
$this->entityManager->remove($calculation);
$this->entityManager->flush();
}
/**
* {@inheritDoc}
*/
protected function tearDown()
{
}
}
| <?php
namespace AppBundle\Tests\Entity;
use AppBundle\Entity\Calculation;
use AppBundle\Model\CalculationFactory;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class SimpleRasterTest extends WebTestCase
{
/**
* @var \Doctrine\ORM\EntityManager
*/
protected $entityManager;
/**
* @var Calculation $project
*/
protected $calculation;
/**
* {@inheritDoc}
*/
public function setUp()
{
self::bootKernel();
$this->entityManager = static::$kernel->getContainer()
->get('doctrine')
->getManager()
;
}
/**
*
*/
public function testAddMultipleArrayToCalculatedValues()
{
$submittedValues = array(
array(1,2,3),
array(4,5,6),
array(7,8,9)
);
$this->calculation = CalculationFactory::create();
$this->calculation->setValues($submittedValues);
$this->entityManager->persist($this->calculation);
$this->entityManager->flush();
$this->entityManager->clear();
$calculation = $this->entityManager->getRepository('AppBundle:Calculation')
->findOneBy(array(
'id' => $this->calculation->getId()
))
;
$values = $calculation->getValues();
$this->assertEquals($submittedValues, $values);
}
/**
* {@inheritDoc}
*/
protected function tearDown()
{
}
}
|
Remove some weird space in the test configuration. | <?php
use Arvici\Heart\Config\Configuration;
use Arvici\Component\View\View;
/**
* Template Configuration
*/
Configuration::define('database', function() {
return [
/**
* The default fetch type to use.
*/
'fetchType' => \Arvici\Heart\Database\Database::FETCH_ASSOC,
/**
* Database Connection names and configuration values.
*
* 'default' is used when no connection name is provided, or using SweetORM.
*/
'connections' => [
'default' => [
'driver' => 'MySQL',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'port' => 3306,
'database' => 'arvici_test'
],
'incomplete' => [
'driver' => 'MySQL',
],
'nodriver' => [
]
],
];
});
| <?php
use Arvici\Heart\Config\Configuration;
use Arvici\Component\View\View;
/**
* Template Configuration
*/
Configuration::define('database', function() {
return [
/**
* The default fetch type to use.
*/
'fetchType' => \Arvici\Heart\Database\Database::FETCH_ASSOC,
/**
* Database Connection names and configuration values.
*
* 'default' is used when no connection name is provided, or using SweetORM.
*/
'connections' => [
'default' => [
'driver' => 'MySQL',
'host' => 'localhost',
'username' => 'root',
'password' => '',
'port' => 3306,
'database' => 'arvici_test'
],
'incomplete' => [
'driver' => 'MySQL',
],
'nodriver' => [
]
],
];
});
|
application: Add warning about db connection issues to the fork class | <?php
/**
* Process forking implementation
* @author M2Mobi, Heinz Wiesinger
*/
class Fork
{
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* Start multiple parallel child processes
* WARNING: make sure to not reuse an already existing DB-Connection established by the parent
* in the children. Best would be to not establish a DB-Connection in the parent at all.
* @param Integer $number Amount of child processes to start
* @param Mixed $call The call that should be executed by the child processes
* either "function" or "array('class','method')"
* @param Array $data Prepared array of data to be processed by the child processes
* this array should be size() = $number
* @return Mixed Either false if run out of CLI context or an array of child process statuses
*/
public static function fork($number, $call, $data)
{
global $cli;
if ($cli)
{
for($i = 0; $i < $number; ++$i)
{
$pids[$i] = pcntl_fork();
if(!$pids[$i])
{
// child process
call_user_func_array($call,$data[$i]);
exit();
}
}
$result = SplFixedArray($number);
for($i = 0; $i < $number; ++$i)
{
pcntl_waitpid($pids[$i], $status, WUNTRACED);
$result[$i] = $status;
}
return $result;
}
else
{
return FALSE;
}
}
}
?> | <?php
/**
* Process forking implementation
* @author M2Mobi, Heinz Wiesinger
*/
class Fork
{
/**
* Constructor
*/
public function __construct()
{
}
/**
* Destructor
*/
public function __destruct()
{
}
/**
* Start multiple parallel child processes
* @param Integer $number Amount of child processes to start
* @param Mixed $call The call that should be executed by the child processes
* either "function" or "array('class','method')"
* @param Array $data Prepared array of data to be processed by the child processes
* this array should be size() = $number
* @return Mixed Either false if run out of CLI context or an array of child process statuses
*/
public static function fork($number, $call, $data)
{
global $cli;
if ($cli)
{
for($i = 0; $i < $number; ++$i)
{
$pids[$i] = pcntl_fork();
if(!$pids[$i])
{
// child process
call_user_func_array($call,$data[$i]);
exit();
}
}
$result = SplFixedArray($number);
for($i = 0; $i < $number; ++$i)
{
pcntl_waitpid($pids[$i], $status, WUNTRACED);
$result[$i] = $status;
}
return $result;
}
else
{
return FALSE;
}
}
}
?> |
Disable asyncpg prepared statement cache | import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
self._conn = await asyncpg.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
# https://github.com/MagicStack/asyncpg/issues/76
# we want to rely on pgbouncer
max_cached_statement_lifetime=0,
)
return self._conn
async def close(self):
if self._conn:
await self._conn.close()
self._conn = None
async def fetch(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return await conn.fetch(*args, **kwargs)
async def execute(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return await conn.execute(*args, **kwargs)
async def transaction(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return conn.transaction(*args, **kwargs)
| import asyncpg
class Database:
def __init__(self, host: str, port: int, user: str, password: str, database: str):
self.host = host
self.port = port
self.user = user
self.password = password
self.database = database
self._conn = None
async def connect(self):
self._conn = await asyncpg.connect(
host=self.host,
port=self.port,
user=self.user,
password=self.password,
database=self.database,
)
return self._conn
async def close(self):
if self._conn:
await self._conn.close()
self._conn = None
async def fetch(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return await conn.fetch(*args, **kwargs)
async def execute(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return await conn.execute(*args, **kwargs)
async def transaction(self, *args, **kwargs):
if not self._conn:
conn = await self.connect()
else:
conn = self._conn
return conn.transaction(*args, **kwargs)
|
Enable toolbar buttons only within certain tags | define('scribe-plugin-image-inserter', [
'eventsWithPromises',
'rangy-core',
'rangy-selectionsaverestore',
'filter-event'
],
function (eventsWithPromises, rangy, rangySelectionSaveRestore, filterEvent) {
'use strict';
/**
* This plugin adds a command for editing/creating links via LinkEditor/LinkInserter
*/
return function (context) {
return function (scribe) {
var insertImageCommand = new scribe.api.Command('insertHTML');
insertImageCommand.nodeName = 'P';
insertImageCommand.validNodes = ['P','LI','A'];
insertImageCommand.execute = function () {
return true;
};
insertImageCommand.queryState = function () {
return false;
};
insertImageCommand.queryEnabled = function() {
var selection = new scribe.api.Selection();
return selection.getContaining(function (node) {
return insertImageCommand.validNodes.indexOf(node.nodeName) !== -1;
});
};
insertImageCommand.insert = function (url) {
scribe.api.SimpleCommand.prototype.execute.call(this, '<img src="'+ url +'">');
};
insertImageCommand.handleInsertPublished = function(eventData) {
if(!eventData.val) return;
this.insert(eventData.val);
};
insertImageCommand.setupEvents = function() {
eventsWithPromises.subscribe('insertmanager:insert-published',
filterEvent(this.handleInsertPublished.bind(this), context)
);
};
insertImageCommand.init = function() {
this.setupEvents();
};
insertImageCommand.init();
scribe.commands.insertImage = insertImageCommand;
};
};
});
| define('scribe-plugin-image-inserter', [
'eventsWithPromises',
'rangy-core',
'rangy-selectionsaverestore',
'filter-event'
],
function (eventsWithPromises, rangy, rangySelectionSaveRestore, filterEvent) {
'use strict';
/**
* This plugin adds a command for editing/creating links via LinkEditor/LinkInserter
*/
return function (context) {
return function (scribe) {
var insertImageCommand = new scribe.api.Command('insertHTML');
insertImageCommand.nodeName = 'IMG';
insertImageCommand.execute = function () {
return true;
};
insertImageCommand.queryState = function () {
return false;
};
insertImageCommand.queryEnabled = function() {
return true;
};
insertImageCommand.insert = function (url) {
scribe.api.SimpleCommand.prototype.execute.call(this, '<img src="'+ url +'">');
};
insertImageCommand.handleInsertPublished = function(eventData) {
if(!eventData.val) return;
this.insert(eventData.val);
};
insertImageCommand.setupEvents = function() {
eventsWithPromises.subscribe('insertmanager:insert-published',
filterEvent(this.handleInsertPublished.bind(this), context)
);
};
insertImageCommand.init = function() {
this.setupEvents();
};
insertImageCommand.init();
scribe.commands.insertImage = insertImageCommand;
};
};
});
|
Add list of channels to group index | @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">All Groups</div>
<div class="panel-body">
<a class="pull-right btn btn-default" href="{{ url('admin/groups/create') }}">New</a>
@if (count($groups))
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Owners</th>
<th>Channels</th>
</tr>
</thead>
@foreach ($groups as $group)
<tr>
<td>{{ $group->id }}</td>
<td>{{ $group->name }}</td>
<td>{{ $group->owners }}</td>
<td>
@foreach ($group->channels as $channel)
<div>{{ $channel->name }}</div>
@endforeach
</td>
</tr>
@endforeach
</table>
@else
<p>No groups to display.</p>
@endif
</div>
</div>
</div>
</div>
</div>
@endsection
| @extends('app')
@section('content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">All Groups</div>
<div class="panel-body">
<a class="pull-right btn btn-default" href="{{ url('admin/groups/create') }}">New</a>
@if (count($groups))
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Owners</th>
</tr>
</thead>
@foreach ($groups as $group)
<tr>
<td>{{ $group->id }}</td>
<td>{{ $group->name }}</td>
<td>{{ $group->owners }}</td>
</tr>
@endforeach
</table>
@else
<p>No groups to display.</p>
@endif
</div>
</div>
</div>
</div>
</div>
@endsection
|
Set the githubIssue field to the actual GitHub URL fo the issue instead of the issue number. | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + ' (#' + str(self.current_issue) + ')'
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.html_url
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
| # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
from github import Github
class AddGitHubIssueVisitor(AbstractVisitor):
def __init__(self, args):
self.github = Github(args.github_token)
self.repo = self.github.get_repo(args.github_repository)
self.issues = list(self.repo.get_issues())
self.current_issue = -1
super(AddGitHubIssueVisitor, self).__init__()
def visit_edit_node(self, node, post):
if post:
return
if 'commitMessage' not in node:
node['commitMessage'] = '(#' + str(self.current_issue) + ')'
else:
node['commitMessage'] = node['commitMessage'] + ' (#' + str(self.current_issue) + ')'
def visit_node(self, node):
if 'type' in node and node['type'] == 'article':
title = 'Article ' + str(node['order'])
body = node['content']
found = False
for issue in self.issues:
if issue.title == title:
found = True
node['githubIssue'] = issue.number
self.current_issue = issue.number
if issue.body != body:
issue.edit(title=title, body=body)
if not found:
issue = self.repo.create_issue(title=title, body=body)
self.current_issue = issue.number
super(AddGitHubIssueVisitor, self).visit_node(node)
|
Add phonelog to postgres models copied by copy_domain | from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
from phonelog.models import DeviceReportEntry
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list of doc-ids from a remote postgres
database to the locally configured one.
"""
# can make this more configurable or less hard coded eventually
# also note that ordering here is important for foreign key dependencies
postgres_models = [
(SQLProduct, 'product_id'),
(StockReport, 'form_id'),
(StockTransaction, 'case_id'),
(DocDomainMapping, 'doc_id'),
# StockState objects are "derived" and get created by StockTransaction post_save signal.
# We may want to directly port these over in the future.
# (StockState, 'case_id'),
(DeviceReportEntry, 'xform_id'),
]
for model, doc_field in postgres_models:
query_set = model.objects.using(remote_postgres_slug).filter(
**{'{}__in'.format(doc_field): doc_ids}
)
count = query_set.count()
print "Copying {} models ({})".format(model.__name__, count)
if not simulate:
for i, item in enumerate(query_set):
# this can cause primary key conflicts to overwrite local data I think. Oh well?
item.save(using='default')
print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
| from casexml.apps.stock.models import StockReport, StockTransaction, DocDomainMapping
from corehq.apps.products.models import SQLProduct
def copy_postgres_data_for_docs(remote_postgres_slug, doc_ids, simulate=False):
"""
Copies a set of data associated with a list of doc-ids from a remote postgres
database to the locally configured one.
"""
# can make this more configurable or less hard coded eventually
# also note that ordering here is important for foreign key dependencies
postgres_models = [
(SQLProduct, 'product_id'),
(StockReport, 'form_id'),
(StockTransaction, 'case_id'),
(DocDomainMapping, 'doc_id'),
# StockState objects are "derived" and get created by StockTransaction post_save signal.
# We may want to directly port these over in the future.
# (StockState, 'case_id'),
]
for model, doc_field in postgres_models:
query_set = model.objects.using(remote_postgres_slug).filter(
**{'{}__in'.format(doc_field): doc_ids}
)
count = query_set.count()
print "Copying {} models ({})".format(model.__name__, count)
if not simulate:
for i, item in enumerate(query_set):
# this can cause primary key conflicts to overwrite local data I think. Oh well?
item.save(using='default')
print 'Synced {}/{} {}'.format(i + 1, count, model.__name__)
|
Allow clients to provide their own function to decide whether form is valid before submission | $.fn.informantSubscribeForm = function (options) {
var settings = $.extend({
renderResults: false,
resultContainer: null,
validate: function (form, evt) { return true; }
}, options);
this.each(function () {
var self = $(this);
function renderResults(htmlContent) {
if (settings.renderResults) {
settings.resultContainer.html(htmlContent);
}
};
self.submit(function (evt) {
if (settings.validate($(this), evt)) {
evt.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function () {}, 'html')
.success(function (response) {
renderResults(response);
self.trigger('informantSubscribeOk', response.responseText);
})
.error(function (response) {
if (response.status != 400)
renderResults(response.statusText);
else
renderResults(response.responseText);
self.trigger('informantSubscribeError', response.responseText);
});
}
return false;
});
});
}; | $.fn.informantSubscribeForm = function (options) {
var settings = $.extend({
renderResults: false,
resultContainer: null
}, options);
this.each(function () {
var self = $(this);
function renderResults(htmlContent) {
if (settings.renderResults) {
settings.resultContainer.html(htmlContent);
}
};
self.submit(function (evt) {
evt.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function () {}, 'html')
.success(function (response) {
renderResults(response);
self.trigger('informantSubscribeOk', response.responseText);
})
.error(function (response) {
if (response.status != 400)
renderResults(response.statusText);
else
renderResults(response.responseText);
self.trigger('informantSubscribeError', response.responseText);
});
return false;
});
});
}; |
Remove redundant 'ckernel' overload match | """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
# Default overload is CKERNEL, so no need to look it up again
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
| """
Lift ckernels to their appropriate rank so they always consume the full array
arguments.
"""
from __future__ import absolute_import, division, print_function
import datashape
from pykit.ir import transform, Op
#------------------------------------------------------------------------
# Run
#------------------------------------------------------------------------
def run(func, env):
strategies = env['strategies']
transform(CKernelImplementations(strategies), func)
#------------------------------------------------------------------------
# Extract CKernel Implementations
#------------------------------------------------------------------------
class CKernelImplementations(object):
"""
For kernels that are implemented via ckernels, this
grabs the ckernel_deferred and turns it into a ckernel
op.
"""
def __init__(self, strategies):
self.strategies = strategies
def op_kernel(self, op):
if self.strategies[op] != 'ckernel':
return
function = op.metadata['kernel']
overload = op.metadata['overload']
func = overload.func
polysig = overload.sig
monosig = overload.resolved_sig
argtypes = datashape.coretypes.Tuple(monosig.argtypes)
try:
overload = function.best_match('ckernel', argtypes)
except datashape.CoercionError:
return op
impl = overload.func
assert monosig == overload.resolved_sig, (monosig,
overload.resolved_sig)
new_op = Op('ckernel', op.type, [impl, op.args[1:]], op.result)
new_op.add_metadata({'rank': 0,
'parallel': True})
return new_op
|
Put the type unwrapping into a separat method | from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
ret_type = self.type_unwrap(space, w_ret_type)
arg_types = [self.type_unwrap(space, w_type)
for w_type in space.listview(w_arg_types)]
# code for type object
def type_unwrap(self, space, w_type):
if space.is_kind_of(w_type, space.getclassfor(W_TypeObject)):
return self
try:
sym = Coerce.symbol(space, w_type)
key = sym.upper()
if key in W_TypeObject.basics:
return W_TypeObject.basics[key]
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
| from topaz.objects.objectobject import W_Object
from topaz.module import ClassDef
from topaz.modules.ffi.type import W_TypeObject
from topaz.error import RubyError
from topaz.coerce import Coerce
class W_FunctionObject(W_Object):
classdef = ClassDef('Function', W_Object.classdef)
@classdef.singleton_method('allocate')
def singleton_method_allocate(self, space, args_w):
return W_FunctionObject(space)
@classdef.method('initialize')
def method_initialize(self, space, w_ret_type, w_arg_types, w_function, w_options):
if not space.is_kind_of(w_ret_type, space.getclassfor(W_TypeObject)):
try:
sym = Coerce.symbol(space, w_ret_type)
if sym.upper() in W_TypeObject.basics:
# code for string object
pass
else:
raise space.error(space.w_TypeError,
"can't convert Symbol into Type")
except RubyError:
tp = w_ret_type.getclass(space).name
raise space.error(space.w_TypeError,
"can't convert %s into Type" % tp)
# code for type object
|
Add a simple UnicodeCSVWriter, probably flawed. | # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chunk = itertools.islice(it, n)
try:
first = next(chunk)
except StopIteration:
return
yield itertools.chain([first], chunk)
class UnicodeCSVReader(object):
"""
An extremely minimal wrapper around csv.reader to assist in
reading Unicode data.
"""
def __init__(self, *args, **kwargs):
self.encoding = kwargs.pop('encoding', 'utf8')
self.pad_to = kwargs.pop('pad_to', 0)
self.pad_with = kwargs.pop('pad_with', '')
self.reader = csv.reader(*args, **kwargs)
def next(self):
row = self.reader.next()
padding = [self.pad_with] * (self.pad_to - len(row))
return [unicode(c, self.encoding) for c in row] + padding
def __iter__(self):
return self
@property
def dialect(self):
return self.reader.dialect
@property
def line_num(self):
return self.reader.line_num
class UnicodeCSVWriter(object):
def __init__(self, *args, **kwargs):
self.encoding = kwargs.pop('encoding', 'utf8')
self.writer = csv.writer(*args, **kwargs)
def writerow(self, row):
self.writer.writerow([
column.encode(self.encoding) for column in row
])
def writerows(self, rows):
for row in rows:
self.writerow(row)
| # -*- coding: utf-8 -*-
import csv
import itertools
def grouper(iterable, n):
"""
Slice up `iterable` into iterables of `n` items.
:param iterable: Iterable to splice.
:param n: Number of items per slice.
:returns: iterable of iterables
"""
it = iter(iterable)
while True:
chunk = itertools.islice(it, n)
try:
first = next(chunk)
except StopIteration:
return
yield itertools.chain([first], chunk)
class UnicodeCSVReader(object):
"""
An extremely minimal wrapper around csv.reader to assist in
reading Unicode data.
"""
def __init__(self, *args, **kwargs):
self.encoding = kwargs.pop('encoding', 'utf8')
self.pad_to = kwargs.pop('pad_to', 0)
self.pad_with = kwargs.pop('pad_with', '')
self.reader = csv.reader(*args, **kwargs)
def next(self):
row = self.reader.next()
padding = [self.pad_with] * (self.pad_to - len(row))
return [unicode(c, self.encoding) for c in row] + padding
def __iter__(self):
return self
@property
def dialect(self):
return self.reader.dialect
@property
def line_num(self):
return self.reader.line_num
|
Fix JSON serialisation problem with AJAX basket
six.moves.map returns itertools.imap which won't serialize to JSON.
This commit unpacks the list into a normal list of strings to circumvent
the issue. | import six
from django.contrib import messages
from six.moves import map
class FlashMessages(object):
"""
Intermediate container for flash messages.
This is useful as, at the time of creating the message, we don't know
whether the response is an AJAX response or not.
"""
def __init__(self):
self.msgs = {}
def add_message(self, level, message):
self.msgs.setdefault(level, []).append(message)
def add_messages(self, level, messages):
for msg in messages:
self.add_message(level, msg)
def info(self, message):
self.add_message(messages.INFO, message)
def warning(self, message):
self.add_message(messages.WARNING, message)
def error(self, message):
self.add_message(messages.ERROR, message)
def success(self, message):
self.add_message(messages.SUCCESS, message)
def to_json(self):
payload = {}
for level, msgs in self.msgs.items():
tag = messages.DEFAULT_TAGS.get(level, 'info')
payload[tag] = [six.text_type(msg) for msg in msgs]
return payload
def apply_to_request(self, request):
for level, msgs in self.msgs.items():
for msg in msgs:
messages.add_message(request, level, msg)
| import six
from django.contrib import messages
from six.moves import map
class FlashMessages(object):
"""
Intermediate container for flash messages.
This is useful as, at the time of creating the message, we don't know
whether the response is an AJAX response or not.
"""
def __init__(self):
self.msgs = {}
def add_message(self, level, message):
self.msgs.setdefault(level, []).append(message)
def add_messages(self, level, messages):
for msg in messages:
self.add_message(level, msg)
def info(self, message):
self.add_message(messages.INFO, message)
def warning(self, message):
self.add_message(messages.WARNING, message)
def error(self, message):
self.add_message(messages.ERROR, message)
def success(self, message):
self.add_message(messages.SUCCESS, message)
def to_json(self):
payload = {}
for level, msgs in self.msgs.items():
tag = messages.DEFAULT_TAGS.get(level, 'info')
payload[tag] = map(six.text_type, msgs)
return payload
def apply_to_request(self, request):
for level, msgs in self.msgs.items():
for msg in msgs:
messages.add_message(request, level, msg)
|
Abort when test is not found. | <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $data['test'])
{
return $app->abort(404, 'Test not found.');
}
$logs = $app['mongo']->logs->find(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
$data['log'] = array();
foreach ($logs as $log)
{
$data['log'][] = $log;
}
return $app['twig']->render('Test.twig', $data);
}
public function delete(\Silex\Application $app)
{
$test = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $test)
{
return $app->abort(404, 'Test not found.');
}
$app['mongo']->tests->remove(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$app['mongo']->logs->remove(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
return $app->redirect('/project/' . $test['project_id']);
}
}
| <?php
namespace Criterion\UI\Controller;
class TestController
{
public function view(\Silex\Application $app)
{
$data['test'] = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$logs = $app['mongo']->logs->find(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
$data['log'] = array();
foreach ($logs as $log)
{
$data['log'][] = $log;
}
return $app['twig']->render('Test.twig', $data);
}
public function delete(\Silex\Application $app)
{
$test = $app['mongo']->tests->findOne(array(
'_id' => new \MongoId($app['request']->get('id'))
));
if ( ! $test)
{
return $app->redirect('/');
}
$app['mongo']->tests->remove(array(
'_id' => new \MongoId($app['request']->get('id'))
));
$app['mongo']->logs->remove(array(
'test_id' => new \MongoId($app['request']->get('id'))
));
return $app->redirect('/project/' . $test['project_id']);
}
} |
Fix E722 error while executing flake8. | from setuptools import setup
f = open("README.rst")
try:
try:
readme_content = f.read()
except Exception:
readme_content = ""
finally:
f.close()
setup(
name='restea',
packages=['restea', 'restea.adapters'],
version='0.3.7',
description='Simple RESTful server toolkit',
long_description=readme_content,
author='Walery Jadlowski',
author_email='[email protected]',
url='https://github.com/bodbdigr/restea',
keywords=['rest', 'restful', 'restea'],
install_requires=[
'future==0.16.0',
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
'pytest-cov',
'pytest-mock',
],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP',
]
)
| from setuptools import setup
f = open("README.rst")
try:
try:
readme_content = f.read()
except:
readme_content = ""
finally:
f.close()
setup(
name='restea',
packages=['restea', 'restea.adapters'],
version='0.3.7',
description='Simple RESTful server toolkit',
long_description=readme_content,
author='Walery Jadlowski',
author_email='[email protected]',
url='https://github.com/bodbdigr/restea',
keywords=['rest', 'restful', 'restea'],
install_requires=[
'future==0.16.0',
],
setup_requires=[
'pytest-runner',
],
tests_require=[
'pytest',
'pytest-cov',
'pytest-mock',
],
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: Implementation :: CPython',
'Programming Language :: Python :: Implementation :: PyPy',
'Topic :: Internet :: WWW/HTTP',
]
)
|
Add Sink class to initial spotify-connect import | from __future__ import unicode_literals
import spotifyconnect
__all__ = [
'Sink'
]
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want to
turn the sink back on.
"""
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
spotifyconnect._session_instance.player.on(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
def off(self):
"""Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
"""
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
self._close()
def _on_music_delivery(self, audio_format, frames, num_frames, pending, session):
# This method is called from an internal libspotify thread and must
# not block in any way.
raise NotImplementedError
def _close(self):
pass
| from __future__ import unicode_literals
import spotifyconnect
class Sink(object):
def on(self):
"""Turn on the alsa_sink sink.
This is done automatically when the sink is instantiated, so you'll
only need to call this method if you ever call :meth:`off` and want to
turn the sink back on.
"""
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
spotifyconnect._session_instance.player.on(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
def off(self):
"""Turn off the alsa_sink sink.
This disconnects the sink from the relevant session events.
"""
spotifyconnect._session_instance.player.off(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY, self._on_music_delivery)
assert spotifyconnect._session_instance.player.num_listeners(
spotifyconnect.PlayerEvent.MUSIC_DELIVERY) == 0
self._close()
def _on_music_delivery(self, audio_format, frames, num_frames, pending, session):
# This method is called from an internal libspotify thread and must
# not block in any way.
raise NotImplementedError
def _close(self):
pass
|
Fix non existing Model\AlbumTableGateway::class FQN | <?php
namespace Album;
use Zend\Db\Adapter\Adapter;
use Zend\Db\Adapter\AdapterInterface;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\AlbumTable::class => function ($container) {
$tableGateway = $container->get('Model\AlbumTableGateway');
return new Model\AlbumTable($tableGateway);
},
'Model\AlbumTableGateway' => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\AlbumController::class => function ($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
],
];
}
}
| <?php
namespace Album;
use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\ModuleManager\Feature\ConfigProviderInterface;
class Module implements ConfigProviderInterface
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfig()
{
return [
'factories' => [
Model\AlbumTable::class => function ($container) {
$tableGateway = $container->get(Model\AlbumTableGateway::class);
return new Model\AlbumTable($tableGateway);
},
Model\AlbumTableGateway::class => function ($container) {
$dbAdapter = $container->get(AdapterInterface::class);
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Model\Album());
return new TableGateway('album', $dbAdapter, null, $resultSetPrototype);
},
],
];
}
public function getControllerConfig()
{
return [
'factories' => [
Controller\AlbumController::class => function ($container) {
return new Controller\AlbumController(
$container->get(Model\AlbumTable::class)
);
},
],
];
}
}
|
:bug: Fix by targeting zeros within values only | 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (item, i, parent) {
if (item.content === '0') {
if (parent.type === 'dimension') {
var next = parent.content[i + 1] || false;
if (units.indexOf(next.content) !== -1) {
if (!parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'No unit allowed for values of 0'
});
}
}
}
else {
if (parent.type === 'value') {
if (parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'Unit required for values of 0'
});
}
}
}
}
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
var units = ['em', 'ex', 'ch', 'rem', 'vh', 'vw', 'vmin', 'vmax',
'px', 'mm', 'cm', 'in', 'pt', 'pc'];
module.exports = {
'name': 'zero-unit',
'defaults': {
'include': false
},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('number', function (item, i, parent) {
if (item.content === '0') {
if (parent.type === 'dimension') {
var next = parent.content[i + 1] || false;
if (units.indexOf(next.content) !== -1) {
if (!parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'No unit allowed for values of 0'
});
}
}
}
else {
if (parser.options.include) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'severity': parser.severity,
'line': item.end.line,
'column': item.end.column,
'message': 'Unit required for values of 0'
});
}
}
}
});
return result;
}
};
|
Address review: Put translated line on one line. | /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-view'],
function(DataTableView, WorldMapView) {
// Enrollment by country map
var enrollmentGeographyMap = new WorldMapView({
el: '[data-view=world-map]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
// eslint-disable-next-line max-len
tooltip: gettext('Learner location is determined from IP address. This map shows where learners most recently connected.')
}),
// Enrollment by country table
enrollmentGeographyTable = new DataTableView({
el: '[data-role=enrollment-location-table]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
columns: [
{key: 'countryName', title: gettext('Country')},
{key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'},
// Translators: The noun count (e.g. number of learners)
{key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'}
],
sorting: ['-count']
});
enrollmentGeographyTable.renderIfDataAvailable();
enrollmentGeographyMap.renderIfDataAvailable();
}
);
});
| /**
* This is the first script called by the enrollment geography page. It loads
* the libraries and kicks off the application.
*/
require(['vendor/domReady!', 'load/init-page'], function(doc, page) {
'use strict';
// this is your page specific code
require(['views/data-table-view', 'views/world-map-view'],
function(DataTableView, WorldMapView) {
// Enrollment by country map
var enrollmentGeographyMap = new WorldMapView({
el: '[data-view=world-map]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
// eslint-disable-next-line max-len
tooltip: gettext('Learner location is determined from IP address. This map shows where learners ' +
'most recently connected.')
}),
// Enrollment by country table
enrollmentGeographyTable = new DataTableView({
el: '[data-role=enrollment-location-table]',
model: page.models.courseModel,
modelAttribute: 'enrollmentByCountry',
columns: [
{key: 'countryName', title: gettext('Country')},
{key: 'percent', title: gettext('Percent'), className: 'text-right', type: 'percent'},
// Translators: The noun count (e.g. number of learners)
{key: 'count', title: gettext('Current Enrollment'), className: 'text-right', type: 'number'}
],
sorting: ['-count']
});
enrollmentGeographyTable.renderIfDataAvailable();
enrollmentGeographyMap.renderIfDataAvailable();
}
);
});
|
Allow setting cell style on isolate override | /**
* Focus on a single presentation.
*/
ds.models.transform.Isolate = function(options) {
'use strict'
var self =
limivorous.observable()
.extend(ds.models.transform.transform, {
display_name: 'Isolate',
transform_name: 'isolate',
transform_type: 'presentation'
})
.property('style', {init: 'well'})
.build()
self.transform = function(item) {
var section = ds.models.section()
.add(ds.models.row()
.add(ds.models.cell()
.set_span(12)
.set_style(self.style)
.add(item.set_height(6)
.set_interactive(true))))
.add(ds.models.row()
.add(ds.models.cell()
.set_span(12)
.add(ds.models.summation_table({query: item.query}))))
/* HACK - everything about the interactive flag is a hack right now */
if (item.query.options) {
item.query.options.fire_only = false
}
return section
}
self.toJSON = function() {
return ds.models.transform.transform.json(self, {})
}
return self
}
| /**
* Focus on a single presentation.
*/
ds.models.transform.Isolate = function(options) {
'use strict'
var self =
limivorous.observable()
.extend(ds.models.transform.transform, {
display_name: 'Isolate',
transform_name: 'isolate',
transform_type: 'presentation'
})
.build()
self.transform = function(item) {
var section = ds.models.section()
.add(ds.models.row()
.add(ds.models.cell()
.set_span(12)
.add(item.set_height(6)
.set_interactive(true))))
.add(ds.models.row()
.add(ds.models.cell()
.set_span(12)
.add(ds.models.summation_table({query: item.query}))))
/* HACK - everything about the interactive flag is a hack right now */
if (item.query.options) {
item.query.options.fire_only = false
}
return section
}
self.toJSON = function() {
return ds.models.transform.transform.json(self, {})
}
return self
}
|
Use the column module and just extend from that. | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
}); | define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
});
|
Add support for Android back button | import React, { Component } from 'react';
import { addNavigationHelpers, NavigationActions } from 'react-navigation';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { BackAndroid, View } from 'react-native';
import * as actions from './actions';
import { AppContainerStyles } from './styles/containers';
import { AppNavigator } from './navigators';
class App extends Component {
componentDidMount() {
BackAndroid.addEventListener('backPress', () => this.handleBackPress(this.props));
}
componentWillUnmount() {
BackAndroid.removeEventListener('backPress');
}
handleBackPress({dispatch, navigation}) {
// Close the app if no route to go back to
if (navigation.index === 0) {
return false;
}
dispatch(NavigationActions.back());
return true;
}
handleNavigationStateChange({SWIPEOUT_TASK}) {
SWIPEOUT_TASK(null);
}
render() {
const
{ dispatch, navigation, tasks, ...actionProps } = this.props,
navigationHelpers = addNavigationHelpers({ state: navigation, dispatch });
return (
<View style={AppContainerStyles.container}>
<AppNavigator
screenProps={{...tasks, ...actionProps}}
navigation={navigationHelpers}
onNavigationStateChange={(prevState, currentState) => this.handleNavigationStateChange(actionProps) }
/>
</View>
);
}
}
const
mapStateToProps = state => ({
navigation: state.navigation,
tasks: state.tasks
});
mapDispatchToProps = dispatch => ({
...bindActionCreators(actions, dispatch),
dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
| import React, { Component } from 'react';
import { addNavigationHelpers } from 'react-navigation';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { View } from 'react-native';
import * as actions from './actions';
import { AppContainerStyles } from './styles/containers';
import { AppNavigator } from './navigators';
class App extends Component {
handleNavigationStateChange({SWIPEOUT_TASK}) {
SWIPEOUT_TASK(null);
}
render() {
const
{ dispatch, navigation, tasks, ...actionProps } = this.props,
navigationHelpers = addNavigationHelpers({ state: navigation, dispatch });
return (
<View style={AppContainerStyles.container}>
<AppNavigator
screenProps={{...tasks, ...actionProps}}
navigation={navigationHelpers}
onNavigationStateChange={(prevState, currentState) => this.handleNavigationStateChange(actionProps) }
/>
</View>
);
}
}
const
mapStateToProps = state => ({
navigation: state.navigation,
tasks: state.tasks
});
mapDispatchToProps = dispatch => ({
...bindActionCreators(actions, dispatch),
dispatch
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
Fix history adding too many things when clicked | import Clipboard from 'clipboard';
import React from 'react';
import { Colours } from '../../modules/colours';
import { Saved } from '../../modules/saved';
export class History extends React.Component {
constructor (props) {
super(props);
this.max = 10;
this.state = {
history: new Array(this.max)
};
this.pushToStack = this.pushToStack.bind(this);
}
componentWillMount () {
this.pushToStack(this.props.colour);
}
componentWillReceiveProps (nextProps) {
this.pushToStack(nextProps.colour);
}
pushToStack (item) {
if (item !== this.state.history[this.state.history.length - 1]) {
let stack = this.state.history;
stack.push(item);
// Only keep newest max amount of items
stack.splice(0, stack.length - this.max);
}
}
render () {
return (
<div className='history'>
{ this.state.history.map((colour, i) => {
let formattedColour = Colours.format(colour, this.props.format);
return (
<div key={i} className='history__item copy'
style={{ backgroundColor: colour }}
data-colour={formattedColour}
data-clipboard-text={formattedColour}
onClick={() => Saved.add(colour)} />
);
}) }
</div>
);
}
}
| import Clipboard from 'clipboard';
import React from 'react';
import { Colours } from '../../modules/colours';
import { Saved } from '../../modules/saved';
export class History extends React.Component {
constructor (props) {
super(props);
this.max = 10;
this.state = {
history: new Array(this.max)
};
this.pushToStack = this.pushToStack.bind(this);
}
componentWillMount () {
this.pushToStack(this.props.colour);
}
componentWillReceiveProps (nextProps) {
this.pushToStack(nextProps.colour);
}
pushToStack (item) {
let stack = this.state.history;
stack.push(item);
// Only keep newest max amount of items
stack.splice(0, stack.length - this.max);
}
render () {
return (
<div className='history'>
{ this.state.history.map((colour, i) => {
let formattedColour = Colours.format(colour, this.props.format);
return (
<div key={i} className='history__item copy'
style={{ backgroundColor: colour }}
data-colour={formattedColour}
data-clipboard-text={formattedColour}
onClick={() => Saved.add(colour)} />
);
}) }
</div>
);
}
}
|
Change comment counter in CommentsContainer | 'use strict';
import React, {PropTypes} from 'react';
import Comment from './Comment.component.js';
import {isEmpty, take} from 'lodash';
class CommentsContainerComponent extends React.Component {
constructor() {
super();
this.toggleExpand = this.toggleExpand.bind(this);
this.state = {isExpanded: true};
}
toggleExpand() {
this.setState({isExpanded: !this.state.isExpanded});
}
render() {
const expandButtonText = this.state.isExpanded ? 'Se flere kommentarer' : 'Vis færre kommentarer';
const allComments = this.props.comments;
const visibleComments = this.state.isExpanded ? take(allComments, 2) : allComments;
const comments = !(isEmpty(visibleComments)) ? visibleComments.map((val) => {
return (
<Comment
commentContent={val.content}
key={val.id}
ownerEmail={val.owner.email}
ownerImageUrl={val.owner.imageUrl ? val.owner.imageUrl : '/dummy.jpg'}
/>
);
}) : (<div className='noComments' />);
return (
<div>
<h4>{allComments.length} Kommentarer</h4>
<button className='tiny' onClick={this.toggleExpand}>{expandButtonText}</button>
<hr />
{comments}
</div>
);
}
}
CommentsContainerComponent.displayName = 'CommentsContainer.component';
CommentsContainerComponent.propTypes = {
comments: PropTypes.array.isRequired
};
export default CommentsContainerComponent;
| 'use strict';
import React, {PropTypes} from 'react';
import Comment from './Comment.component.js';
import {isEmpty, take} from 'lodash';
class CommentsContainerComponent extends React.Component {
constructor() {
super();
this.toggleExpand = this.toggleExpand.bind(this);
this.state = {isExpanded: true};
}
toggleExpand() {
this.setState({isExpanded: !this.state.isExpanded});
}
render() {
const expandButtonText = this.state.isExpanded ? 'Se flere kommentarer' : 'Vis færre kommentarer';
const allComments = this.props.comments;
const visibleComments = this.state.isExpanded ? take(allComments, 2) : allComments;
const comments = !(isEmpty(visibleComments)) ? visibleComments.map((val) => {
return (
<Comment
commentContent={val.content}
key={val.id}
ownerEmail={val.owner.email}
ownerImageUrl={val.owner.imageUrl ? val.owner.imageUrl : '/dummy.jpg'}
/>
);
}) : (<div className='noComments' />);
return (
<div>
<h4>{comments.length} Kommentarer</h4>
<button className='tiny' onClick={this.toggleExpand}>{expandButtonText}</button>
<hr />
{comments}
</div>
);
}
}
CommentsContainerComponent.displayName = 'CommentsContainer.component';
CommentsContainerComponent.propTypes = {
comments: PropTypes.array.isRequired
};
export default CommentsContainerComponent;
|
Remove console logging and make email required | 'use strict';
const Joi = require('joi');
const Boom = require('boom');
exports.addTicket = {
description: 'Add new support ticket',
validate: {
payload: {
subject: Joi.string().max(500).allow(''),
email: Joi.string().max(100),
description: Joi.string().max(5000).allow('')
},
failAction: function(request, reply, source, error) {
// Boom bad request
return reply.reply(Boom.badRequest(error));
}
},
auth: {
mode: 'try',
strategy: 'standard'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
handler: function(request, reply) {
var ticket = {
subject: request.payload.subject,
email: request.payload.email,
description: request.payload.description
};
var freshDesk = request.server.plugins.freshdesk;
freshDesk.newTicket(ticket, function() {
return reply({
statusCode: 200,
message: 'Successfully created ticket.'
});
});
}
};
| 'use strict';
const Joi = require('joi');
const Boom = require('boom');
exports.addTicket = {
description: 'Add new support ticket',
validate: {
payload: {
subject: Joi.string().max(500).allow(''),
email: Joi.string().max(100).allow(''),
description: Joi.string().max(5000).allow('')
},
failAction: function(request, reply, source, error) {
// Boom bad request
return reply.reply(Boom.badRequest(error));
}
},
auth: {
mode: 'try',
strategy: 'standard'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
handler: function(request, reply) {
var ticket = {
subject: request.payload.subject,
email: request.payload.email,
description: request.payload.description
};
console.log(ticket);
var freshDesk = request.server.plugins.freshdesk;
freshDesk.newTicket(ticket, function() {
return reply({
statusCode: 200,
message: 'Successfully created ticket.'
});
});
}
};
|
Change field defaults from NULL to 0
MariaDB doesn't seem to like numeric/boolean fields to have NULL for a
default value | ->default(0)<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachineSurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machine_surveydata', function (Blueprint $table) {
$table->integer('id')->unsigned();
$table->integer('machine_id')->unsigned()->default(0);
$table->boolean('gendata')->default(0);
$table->boolean('collimatordata')->default(0);
$table->boolean('radoutputdata')->default(0);
$table->boolean('radsurveydata')->default(0);
$table->boolean('hvldata')->default(0);
$table->boolean('fluorodata')->default(0);
$table->boolean('maxfluorodata')->default(0);
$table->boolean('receptorentrance')->default(0);
$table->index(['machine_id', 'id']);
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
| <?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMachineSurveydataTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('machine_surveydata', function (Blueprint $table) {
$table->integer('id')->unsigned();
$table->integer('machine_id')->unsigned()->nullable()->default(null);
$table->boolean('gendata')->nullable()->default(null);
$table->boolean('collimatordata')->nullable()->default(null);
$table->boolean('radoutputdata')->nullable()->default(null);
$table->boolean('radsurveydata')->nullable()->default(null);
$table->boolean('hvldata')->nullable()->default(null);
$table->boolean('fluorodata')->nullable()->default(null);
$table->boolean('maxfluorodata')->nullable()->default(null);
$table->boolean('receptorentrance')->nullable()->default(null);
$table->index(['machine_id', 'id']);
$table->softDeletes();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
//
}
}
|
Exclude Videos article and non-scrapable info-galleries and picture-galleries via URL-pattern | from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '(?<!(vid|bid|iid))(-1\.\d*)$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES,
fromEncoding='utf-8')
self.meta = soup.findAll('meta')
# category
keywords = soup.find('meta', {'property': 'vr:category'})
self.category = self.compute_category(keywords['content'] if keywords else '')
#article headline
elt = soup.find('meta', {'property': 'og:title'})
if elt is None:
self.real_article = False
return
self.title = elt['content']
# byline / author
author = soup.find('meta', {'itemprop': 'author'})
self.byline = author['content'] if author else ''
# article date
created_at = soup.find('meta', {'property': 'vr:published_time'})
self.date = created_at['content'] if created_at else ''
#article content
div = soup.find('div', {'class': 'main-text '})
if div is None:
self.real_article = False
return
div = self.remove_non_content(div)
self.body = '\n' + '\n\n'.join([x.getText() for x in div.childGenerator()
if isinstance(x, Tag) and x.name == 'p'])
| from baseparser import BaseParser
from BeautifulSoup import BeautifulSoup, Tag
class RPOParser(BaseParser):
domains = ['www.rp-online.de']
feeder_pat = '1\.\d*$'
feeder_pages = ['http://www.rp-online.de/']
def _parse(self, html):
soup = BeautifulSoup(html, convertEntities=BeautifulSoup.HTML_ENTITIES,
fromEncoding='utf-8')
self.meta = soup.findAll('meta')
# category
keywords = soup.find('meta', {'property': 'vr:category'})
self.category = self.compute_category(keywords['content'] if keywords else '')
#article headline
elt = soup.find('meta', {'property': 'og:title'})
if elt is None:
self.real_article = False
return
self.title = elt['content']
# byline / author
author = soup.find('meta', {'itemprop': 'author'})
self.byline = author['content'] if author else ''
# article date
created_at = soup.find('meta', {'property': 'vr:published_time'})
self.date = created_at['content'] if created_at else ''
#article content
div = soup.find('div', {'class': 'main-text '})
if div is None:
self.real_article = False
return
div = self.remove_non_content(div)
self.body = '\n' + '\n\n'.join([x.getText() for x in div.childGenerator()
if isinstance(x, Tag) and x.name == 'p'])
|
Add support for git push --no-verify | 'use strict';
var async = require('grunt').util.async;
var grunt = require('grunt');
var ArgUtil = require('flopmang');
module.exports = function (task, exec, done) {
var argUtil = new ArgUtil(task, [
{
option: 'all',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'upstream',
defaultValue: false,
useAsFlag: true,
useValue: false,
flag: '--set-upstream'
},
{
option: 'tags',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'force',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'noVerify',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'remote',
defaultValue: 'origin',
useAsFlag: false,
useValue: true
},
{
option: 'branch',
defaultValue: null,
useAsFlag: false,
useValue: true
}
]);
var args = ['push'].concat(argUtil.getArgFlags());
// Add callback
args.push(done);
exec.apply(this, args);
};
module.exports.description = 'Pushes to a remote.';
| 'use strict';
var async = require('grunt').util.async;
var grunt = require('grunt');
var ArgUtil = require('flopmang');
module.exports = function (task, exec, done) {
var argUtil = new ArgUtil(task, [
{
option: 'all',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'upstream',
defaultValue: false,
useAsFlag: true,
useValue: false,
flag: '--set-upstream'
},
{
option: 'tags',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'force',
defaultValue: false,
useAsFlag: true,
useValue: false
},
{
option: 'remote',
defaultValue: 'origin',
useAsFlag: false,
useValue: true
},
{
option: 'branch',
defaultValue: null,
useAsFlag: false,
useValue: true
}
]);
var args = ['push'].concat(argUtil.getArgFlags());
// Add callback
args.push(done);
exec.apply(this, args);
};
module.exports.description = 'Pushes to a remote.';
|
tests: Disable some PHP insights sniffs | <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff::class,
ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
SlevomatCodingStandard\Sniffs\Commenting\DocCommentSpacingSniff::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
| <?php
declare(strict_types=1);
return [
/*
|--------------------------------------------------------------------------
| Default Preset
|--------------------------------------------------------------------------
|
| This option controls the default preset that will be used by PHP Insights
| to make your code reliable, simple, and clean. However, you can always
| adjust the `Metrics` and `Insights` below in this configuration file.
|
| Supported: "default", "laravel", "symfony"
|
*/
'preset' => 'symfony',
/*
|--------------------------------------------------------------------------
| Configuration
|--------------------------------------------------------------------------
|
| Here you may adjust all the various `Insights` that will be used by PHP
| Insights. You can either add, remove or configure `Insights`. Keep in
| mind, that all added `Insights` must belong to a specific `Metric`.
|
*/
'add' => [
// ExampleMetric::class => [
// ExampleInsight::class,
// ]
],
'remove' => [
// ExampleInsight::class,
ObjectCalisthenics\Sniffs\NamingConventions\ElementNameMinimalLengthSniff::class,
ObjectCalisthenics\Sniffs\Classes\ForbiddenPublicPropertySniff::class,
ObjectCalisthenics\Sniffs\NamingConventions\NoSetterSniff::class,
],
'config' => [
// ExampleInsight::class => [
// 'key' => 'value',
// ],
],
];
|
Create select with hook up to store | import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {updateValue} from '../actions/controls';
import {connect} from '../store';
class Select extends Component {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
}),
).isRequired,
style: PropTypes.string,
initialValue: PropTypes.string,
placeholder: PropTypes.string,
};
componentDidMount() {
const {initialValue, name} = this.props;
if (initialValue) {
// this.props.updateValue(name, initialValue); TODO
}
}
render() {
const {className, id, name, style, placeholder} = this.props;
const options = this.props.options.map(option => (
<option key={option.value} value={option.value}>
{option.name}
</option>
));
if (placeholder) {
options.unshift(
<option key={placeholder} value="" disabled>
{placeholder}
</option>,
);
}
return (
<select
id={id}
name={name}
value={this.props.value || ""}
className={className}
style={style}
onChange={e => this.props.updateValue(name, e.target.value)}
>
{options}
</select>
);
}
}
const mapStateToProps = ({controls}, props) => ({
value: controls.get(props.name),
});
const mapDispatchToProps = {
updateValue,
};
export default connect(mapStateToProps, mapDispatchToProps)(Select);
| import React from 'react';
import PropTypes from 'prop-types';
import Control from './Control';
class Select extends Control {
static propTypes = {
className: PropTypes.string,
id: PropTypes.string,
name: PropTypes.string.isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
}),
).isRequired,
style: PropTypes.string,
initialValue: PropTypes.string,
placeholder: PropTypes.string,
};
componentDidMount() {
if (this.props.initialValue) {
this._onChange(this.props.initialValue);
}
}
render() {
const {className, id, name, style, value, placeholder} = this.props;
const options = this.props.options.map(option => (
<option key={option.value} value={option.value}>
{option.name}
</option>
));
if (placeholder) {
options.unshift(
<option key={placeholder} value="" disabled>
{placeholder}
</option>,
);
}
return (
<select
id={id}
name={name}
value={this._getValue() || ""}
className={className}
style={style}
onChange={e => this._onChange(e.target.value)}
>
{options}
</select>
);
}
}
export default Select;
|
Implement lazy continuation rule for block quotes. | <?php
namespace FluxBB\CommonMark\Parser\Block;
use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;
class BlockquoteParser extends AbstractBlockParser
{
/**
* Parse the given content.
*
* Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
* in the chain.
*
* @param Text $content
* @param Container $target
* @return void
*/
public function parseBlock(Text $content, Container $target)
{
$content->handle(
'/
^
[ ]{0,3} # up to 3 leading spaces
\> # block quote marker
[ ]? # an optional space
[^\n]* # until end of line
(?: # lazy continuation
\n
[^\-*=\ ].*
)*
$
/mx',
function (Text $content) use ($target) {
// Remove block quote marker plus surrounding whitespace on each line
$content->replace('/^[ ]{0,3}\>[ ]?/m', '');
$blockquote = new Blockquote();
$target->acceptBlockquote($blockquote);
$this->first->parseBlock($content, $blockquote);
},
function (Text $part) use ($target) {
$this->next->parseBlock($part, $target);
}
);
}
}
| <?php
namespace FluxBB\CommonMark\Parser\Block;
use FluxBB\CommonMark\Common\Text;
use FluxBB\CommonMark\Node\Blockquote;
use FluxBB\CommonMark\Node\Container;
use FluxBB\CommonMark\Parser\AbstractBlockParser;
class BlockquoteParser extends AbstractBlockParser
{
/**
* Parse the given content.
*
* Any newly created nodes should be pushed to the stack. Any remaining content should be passed to the next parser
* in the chain.
*
* @param Text $content
* @param Container $target
* @return void
*/
public function parseBlock(Text $content, Container $target)
{
$content->handle(
'/
^
[ ]{0,3} # up to 3 leading spaces
\> # block quote marker
[ ]? # an optional space
[^\n]* # until end of line
( # and repeat multiple times...
\n
[ ]{0,3}
\>
[ ]?
[^\n]*
)*
$
/mx',
function (Text $content) use ($target) {
// Remove block quote marker plus surrounding whitespace on each line
$content->replace('/^[ ]{0,3}\>[ ]?/m', '');
$blockquote = new Blockquote();
$target->acceptBlockquote($blockquote);
$this->first->parseBlock($content, $blockquote);
},
function (Text $part) use ($target) {
$this->next->parseBlock($part, $target);
}
);
}
}
|
Use a realistic User-Agent for reddit | from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand):
triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"}
def trigger_url(self, context, user, channel, match):
if user == 'JustCommit':
return
try:
url = match.group(1)
agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.124 Safari/537.36'
response = requests.get(url, headers={ 'User-Agent': agent })
except (requests.exceptions.ConnectionError) as e:
print "Failed to load URL: %s" % url
print "Message: %s" % e
else:
soup = BeautifulSoup(response.text)
if soup.title and soup.title.text:
title = soup.title.string
title = title.replace('\n', '') # remove newlines
title = title.replace('\x01', '') # remove dangerous control character \001
title = ' '.join(title.split()) # normalise all other whitespace
# Truncate length
if len(title) > 120:
title = title[:117] + "..."
return title
else:
print "URL has no title: %s" % url
| from plugins.categories import ISilentCommand
try:
import requests_pyopenssl
from requests.packages.urllib3 import connectionpool
connectionpool.ssl_wrap_socket = requests_pyopenssl.ssl_wrap_socket
except ImportError:
pass
import requests
from bs4 import BeautifulSoup
class URLGrabber (ISilentCommand):
triggers = {r'.*(http[s]?://[A-Za-z0-9&?%._~!/=+-:]+).*': "url"}
def trigger_url(self, context, user, channel, match):
if user == 'JustCommit':
return
try:
url = match.group(1)
response = requests.get(url)
except (requests.exceptions.ConnectionError) as e:
print "Failed to load URL: %s" % url
print "Message: %s" % e
else:
soup = BeautifulSoup(response.text)
if soup.title and soup.title.text:
title = soup.title.string
title = title.replace('\n', '') # remove newlines
title = title.replace('\x01', '') # remove dangerous control character \001
title = ' '.join(title.split()) # normalise all other whitespace
# Truncate length
if len(title) > 120:
title = title[:117] + "..."
return title
else:
print "URL has no title: %s" % url
|
Fix auto remove thanks to @themouette | /*global window */
define(
[
'text!templates/canvas.html',
'underscore',
'jquery',
'backbone',
'ventilator'
],
function (template, _, $, Backbone, ventilator) {
"use strict";
return new (Backbone.View.extend({
template: _.template(template),
noticeTemplate: _.template($(template).filter('#message-notice').html()),
initialize: function () {
ventilator.on('canvas:message:notice', function (message) {
this.addNotice(message);
}, this);
},
render: function () {
this.$el.html(this.template);
},
addNotice: function (message) {
var $message = $(this.noticeTemplate({
message: message
}));
$('.messages').append($message);
window.setTimeout(function() {
$message.remove();
}, 3000);
}
}))();
}
);
| /*global window */
define(
[
'text!templates/canvas.html',
'underscore',
'jquery',
'backbone',
'ventilator'
],
function (template, _, $, Backbone, ventilator) {
"use strict";
return new (Backbone.View.extend({
template: _.template(template),
noticeTemplate: _.template($(template).filter('#message-notice').html()),
initialize: function () {
ventilator.on('canvas:message:notice', function (message) {
this.addNotice(message);
}, this);
},
render: function () {
this.$el.html(this.template);
},
addNotice: function (message) {
$('.messages').append(this.noticeTemplate({
message: message
}));
window.setTimeout(function() {
$('.messages > div:last-child').hide();
}, 3000);
}
}))();
}
);
|
Remove extraneous Groups from the View in the VU Meter demo. |
from traits.api import HasTraits, Instance
from traitsui.api import View, UItem, Item, RangeEditor, Group, VGroup
from enable.api import ComponentEditor
from enable.gadgets.vu_meter import VUMeter
class Demo(HasTraits):
vu = Instance(VUMeter)
traits_view = \
View(
VGroup(
Group(
UItem('vu', editor=ComponentEditor(size=(60, 60)),
style='custom'),
),
Item('object.vu.percent',
editor=RangeEditor(low=0.0, high=200.0,
mode='slider')),
),
'_',
VGroup(
Item('object.vu.angle', label="angle",
editor=RangeEditor(low=0.0, high=89.0,
mode='slider')),
Item('object.vu._beta',
editor=RangeEditor(low=0.0, high=1.0,
mode='slider')),
),
width=450,
height=380,
title="VU Meter",
resizable=True,
)
if __name__ == "__main__":
color = (0.9, 0.85, 0.7)
vu = VUMeter(border_visible=True, border_width=2, bgcolor=color)
demo = Demo(vu=vu)
demo.configure_traits()
|
from traits.api import HasTraits, Instance
from traitsui.api import View, UItem, Item, RangeEditor, Group, VGroup, HGroup
from enable.api import ComponentEditor
from enable.gadgets.vu_meter import VUMeter
class Demo(HasTraits):
vu = Instance(VUMeter)
traits_view = \
View(
HGroup(
VGroup(
VGroup(
Group(
UItem('vu', editor=ComponentEditor(size=(60, 60)),
style='custom'),
),
Item('object.vu.percent',
editor=RangeEditor(low=0.0, high=200.0,
mode='slider')),
),
'_',
VGroup(
Item('object.vu.angle', label="angle",
editor=RangeEditor(low=0.0, high=89.0,
mode='slider')),
Item('object.vu._beta',
editor=RangeEditor(low=0.0, high=1.0,
mode='slider')),
),
),
),
width=450,
height=380,
title="VU Meter",
resizable=True,
)
if __name__ == "__main__":
color = (0.9, 0.85, 0.7)
vu = VUMeter(border_visible=True, border_width=2, bgcolor=color)
demo = Demo(vu=vu)
demo.configure_traits()
|
Fix issues identified by Psalm | <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject\Rule;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\MethodNameConstraint;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class MethodName
{
/**
* @var Constraint
*/
private $constraint;
/**
* @param Constraint|string $constraint
*
* @throws InvalidArgumentException
*/
public function __construct($constraint)
{
if (\is_string($constraint)) {
$constraint = new MethodNameConstraint($constraint);
}
if (!$constraint instanceof Constraint) {
throw InvalidArgumentException::create(1, 'PHPUnit\Framework\Constraint\Constraint object or string');
}
$this->constraint = $constraint;
}
public function toString(): string
{
return 'method name ' . $this->constraint->toString();
}
/**
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function matches(BaseInvocation $invocation): bool
{
return $this->matchesName($invocation->getMethodName());
}
public function matchesName(string $methodName): bool
{
return $this->constraint->evaluate($methodName, '', true);
}
}
| <?php declare(strict_types=1);
/*
* This file is part of PHPUnit.
*
* (c) Sebastian Bergmann <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPUnit\Framework\MockObject\Rule;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\InvalidArgumentException;
use PHPUnit\Framework\MockObject\Invocation as BaseInvocation;
use PHPUnit\Framework\MockObject\MethodNameConstraint;
/**
* @internal This class is not covered by the backward compatibility promise for PHPUnit
*/
final class MethodName
{
/**
* @var Constraint
*/
private $constraint;
/**
* @param Constraint|string
*
* @throws Constraint
* @throws \PHPUnit\Framework\Exception
*/
public function __construct($constraint)
{
if (!$constraint instanceof Constraint) {
if (!\is_string($constraint)) {
throw InvalidArgumentException::create(1, 'string');
}
$constraint = new MethodNameConstraint($constraint);
}
$this->constraint = $constraint;
}
public function toString(): string
{
return 'method name ' . $this->constraint->toString();
}
/**
* @throws \PHPUnit\Framework\ExpectationFailedException
* @throws \SebastianBergmann\RecursionContext\InvalidArgumentException
*/
public function matches(BaseInvocation $invocation): bool
{
return $this->matchesName($invocation->getMethodName());
}
public function matchesName(string $methodName): bool
{
return $this->constraint->evaluate($methodName, '', true);
}
}
|
:bug: Replace deprecated node type simpleSelector with selector | 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content === 'extend') {
parent.forEach('selector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) {
if (selectorPiece.type === 'placeholder') {
placeholder = true;
}
});
if (!placeholder) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': selector.start.line,
'column': selector.start.column,
'message': '@extend must be used with a %placeholder',
'severity': parser.severity
});
}
});
}
});
});
return result;
}
};
| 'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content === 'extend') {
parent.forEach('simpleSelector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) {
if (selectorPiece.type === 'placeholder') {
placeholder = true;
}
});
if (!placeholder) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': selector.start.line,
'column': selector.start.column,
'message': '@extend must be used with a %placeholder',
'severity': parser.severity
});
}
});
}
});
});
return result;
}
};
|
Make pivot table generation more robust | <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:pivot';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a pivot table';
public function fire()
{
$tables = $this->sortDesiredTables();
$this->call(
'generate:migration',
array(
'name' => "pivot_{$tables[0]}_{$tables[1]}_table",
'--fields' => implode(', ', array(
"{$tables[0]}_id:integer:unsigned:index",
"{$tables[1]}_id:integer:unsigned:index",
"{$tables[0]}_id:foreign:references('id'):on('{$tables[0]}'):onDelete('cascade')",
"{$tables[1]}_id:foreign:references('id'):on('{$tables[1]}'):onDelete('cascade')"
))
)
);
}
public function sortDesiredTables()
{
$tableOne = str_singular($this->argument('tableOne'));
$tableTwo = str_singular($this->argument('tableTwo'));
$tables = array($tableOne, $tableTwo);
sort($tables);
return $tables;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
);
}
}
| <?php namespace Way\Generators\Commands;
use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;
class PivotGeneratorCommand extends BaseGeneratorCommand {
/**
* The console command name.
*
* @var string
*/
protected $name = 'generate:pivot';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Generate a pivot table';
public function fire()
{
$tables = $this->sortDesiredTables();
$this->call(
'generate:migration',
array(
'name' => "pivot_{$tables[0]}_{$tables[1]}_table",
'--fields' => "{$tables[0]}_id:integer:unsigned, {$tables[1]}_id:integer:unsigned"
)
);
}
public function sortDesiredTables()
{
$tableOne = str_singular($this->argument('tableOne'));
$tableTwo = str_singular($this->argument('tableTwo'));
$tables = array($tableOne, $tableTwo);
sort($tables);
return $tables;
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return array(
array('tableOne', InputArgument::REQUIRED, 'Name of the first table.'),
array('tableTwo', InputArgument::REQUIRED, 'Name of the second table.')
);
}
}
|
Fix a typo in the documentation of FileReaderDecorator. | # Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzinator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(kwargs['test'], 'rb') as f:
issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
| # Copyright (c) 2017-2018 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import os
from . import CallableDecorator
class FileReaderDecorator(CallableDecorator):
"""
Decorator for SUTs that take input as a file path: saves the content of
the failing test case.
Moreover, the issue (if any) is also extended with the new ``'filename'``
property containing the name of the test case (as received in the ``test``
argument).
**Example configuration snippet:**
.. code-block:: ini
[sut.foo]
call=fuzzinator.call.SubprocessCall
call.decorate(0)=fuzzionator.call.FileReaderDecorator
[sut.foo.call]
# assuming that foo takes one file as input specified on command line
command=/home/alice/foo/bin/foo {test}
"""
def decorator(self, **kwargs):
def wrapper(fn):
def reader(*args, **kwargs):
issue = fn(*args, **kwargs)
if issue is not None:
with open(kwargs['test'], 'rb') as f:
issue['filename'] = os.path.basename(kwargs['test'])
issue['test'] = f.read()
return issue
return reader
return wrapper
|
Read test logs in bytes mode | import os
from datetime import datetime
def save_logs(groomer, test_description):
divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
test_log_path = 'tests/test_logs/{}.log'.format(test_description)
with open(test_log_path, 'w+') as test_log:
test_log.write(divider.format('TEST LOG'))
test_log.write(str(datetime.now().time()) + '\n')
test_log.write(test_description + '\n')
test_log.write('-' * 20 + '\n')
with open(groomer.logger.log_path, 'rb') as logfile:
log = logfile.read()
test_log.write(log)
if os.path.exists(groomer.logger.log_debug_err):
test_log.write(divider.format('ERR LOG'))
with open(groomer.logger.log_debug_err, 'rb') as debug_err:
err = debug_err.read()
test_log.write(err)
if os.path.exists(groomer.logger.log_debug_out):
test_log.write(divider.format('OUT LOG'))
with open(groomer.logger.log_debug_out, 'rb') as debug_out:
out = debug_out.read()
test_log.write(out)
| import os
from datetime import datetime
def save_logs(groomer, test_description):
divider = ('=' * 10 + '{}' + '=' * 10 + '\n')
test_log_path = 'tests/test_logs/{}.log'.format(test_description)
with open(test_log_path, 'w+') as test_log:
test_log.write(divider.format('TEST LOG'))
test_log.write(str(datetime.now().time()) + '\n')
test_log.write(test_description + '\n')
test_log.write('-' * 20 + '\n')
with open(groomer.logger.log_path, 'r') as logfile:
log = logfile.read()
test_log.write(log)
if os.path.exists(groomer.logger.log_debug_err):
test_log.write(divider.format('ERR LOG'))
with open(groomer.logger.log_debug_err, 'r') as debug_err:
err = debug_err.read()
test_log.write(err)
if os.path.exists(groomer.logger.log_debug_out):
test_log.write(divider.format('OUT LOG'))
with open(groomer.logger.log_debug_out, 'r') as debug_out:
out = debug_out.read()
test_log.write(out)
|
Tweak on seeder for categories.
5000 was too much. 200 is fine. | <?php
use Illuminate\Database\Seeder;
use App\Category;
use App\Product;
class CategoriesTableSeeder extends Seeder
{
public function run()
{
$faker = \App::make('Faker\Generator');
/**
* Clear up the tables before adding new data
*/
Category::truncate();
Product::truncate();
/**
* Create 50 categories
*/
factory(Category::class, 200)->create()->each(function ($category) use ($faker) {
/**
* For each category 2 to 5 products will
* be created and assigned
*/
$quantity = $faker->numberBetween(2, 5);
/**
* Generate in memory the products
*/
$products = factory(Product::class, $quantity)->make();
foreach ($products as $product) {
/**
* Using the relatioship save the products
* to the category
*/
$category->products()->save($product);
}
});
}
}
| <?php
use Illuminate\Database\Seeder;
use App\Category;
use App\Product;
class CategoriesTableSeeder extends Seeder
{
public function run()
{
$faker = \App::make('Faker\Generator');
/**
* Clear up the tables before adding new data
*/
Category::truncate();
Product::truncate();
/**
* Create 50 categories
*/
factory(Category::class, 5000)->create()->each(function ($category) use ($faker) {
/**
* For each category 2 to 5 products will
* be created and assigned
*/
$quantity = $faker->numberBetween(2, 5);
/**
* Generate in memory the products
*/
$products = factory(Product::class, $quantity)->make();
foreach ($products as $product) {
/**
* Using the relatioship save the products
* to the category
*/
$category->products()->save($product);
}
});
}
}
|
Fix OBO serializer assuming `Ontology._terms` is properly ordered | import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
writer = io.TextIOWrapper(file)
try:
# dump the header
if self.ont.metadata:
header = self._to_header_frame(self.ont.metadata)
file.write(str(header).encode("utf-8"))
if self.ont._terms or self.ont._relationships:
file.write(b"\n")
# dump terms
if self.ont._terms:
for i, id in enumerate(sorted(self.ont._terms)):
data = self.ont._terms[id]
frame = self._to_term_frame(Term(self.ont, data))
file.write(str(frame).encode("utf-8"))
if i < len(self.ont._terms) - 1 or self.ont._relationships:
file.write(b"\n")
# dump typedefs
if self.ont._relationships:
for i, id in enumerate(sorted(self.ont._relationships)):
data = self.ont._relationships[id]
frame = self._to_typedef_frame(Relationship(self.ont, data))
file.write(str(frame).encode("utf-8"))
if i < len(self.ont._relationships) - 1:
file.write(b"\n")
finally:
writer.detach()
| import io
from typing import BinaryIO, ClassVar
from ..term import Term, TermData
from ..relationship import Relationship, RelationshipData
from ._fastobo import FastoboSerializer
from .base import BaseSerializer
class OboSerializer(FastoboSerializer, BaseSerializer):
format = "obo"
def dump(self, file):
writer = io.TextIOWrapper(file)
try:
# dump the header
if self.ont.metadata:
header = self._to_header_frame(self.ont.metadata)
file.write(str(header).encode("utf-8"))
if self.ont._terms or self.ont._relationships:
file.write(b"\n")
# dump terms
if self.ont._terms:
for i, (id, data) in enumerate(self.ont._terms.items()):
frame = self._to_term_frame(Term(self.ont, data))
file.write(str(frame).encode("utf-8"))
if i < len(self.ont._terms) - 1 or self.ont._relationships:
file.write(b"\n")
# dump typedefs
if self.ont._relationships:
for i, (id, data) in enumerate(self.ont._relationships.items()):
frame = self._to_typedef_frame(Relationship(self.ont, data))
file.write(str(frame).encode("utf-8"))
if i < len(self.ont._relationships) - 1:
file.write(b"\n")
finally:
writer.detach()
|
Use an instance variable instead of a non-standard argument to __repr__ | from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
__repr_attrs__ = ('id',)
def __init__(self, provider, **kwargs):
self._provider = provider
self._lazy_properties = {}
for attr in getattr(self, '__attrs__', []):
if isinstance(kwargs.get(attr, None), LazyEntityProperty):
self._lazy_properties[attr] = kwargs[attr]
else:
setattr(self, attr, kwargs.get(attr, None))
provider._new_entity(self)
def __repr__(self):
return u'<{0}({1})>'.format(
util.clsname(self), ','.join(
'{0}={1!r}'.format(i, getattr(self, i))
for i in self.__repr_attrs__))
def __getattr__(self, name):
if name in self._lazy_properties:
value = self._lazy_properties[name]()
del self._lazy_properties[name]
setattr(self, name, value)
return value
else:
raise AttributeError(name)
def to_dict(self):
return dict((attr, getattr(self, attr)) for attr in self.__attrs__
if getattr(self, attr))
| from busbus import util
class LazyEntityProperty(object):
def __init__(self, f, *args, **kwargs):
self.f = f
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.f(*self.args, **self.kwargs)
class BaseEntity(object):
def __init__(self, provider, **kwargs):
self._provider = provider
self._lazy_properties = {}
for attr in getattr(self, '__attrs__', []):
if isinstance(kwargs.get(attr, None), LazyEntityProperty):
self._lazy_properties[attr] = kwargs[attr]
else:
setattr(self, attr, kwargs.get(attr, None))
provider._new_entity(self)
def __repr__(self, args=['id']):
return u'<{0}({1})>'.format(
util.clsname(self),
','.join('{0}={1!r}'.format(i, getattr(self, i)) for i in args))
def __getattr__(self, name):
if name in self._lazy_properties:
value = self._lazy_properties[name]()
del self._lazy_properties[name]
setattr(self, name, value)
return value
else:
raise AttributeError(name)
def to_dict(self):
return dict((attr, getattr(self, attr)) for attr in self.__attrs__
if getattr(self, attr))
|
Disable slash escaping by default | <?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakefoundation.org CakePHP(tm) Project
* @since 4.3.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Log\Formatter;
class JsonFormatter extends AbstractFormatter
{
/**
* Default config for this class
*
* @var array<string, mixed>
*/
protected $_defaultConfig = [
'dateFormat' => DATE_ATOM,
'flags' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
];
/**
* @param array<string, mixed> $config Formatter config
*/
public function __construct(array $config = [])
{
$this->setConfig($config);
}
/**
* @inheritDoc
*/
public function format($level, string $message, array $context = []): string
{
$log = ['date' => date($this->_config['dateFormat']), 'level' => (string)$level, 'message' => $message];
return json_encode($log, $this->_config['flags']);
}
}
| <?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakefoundation.org CakePHP(tm) Project
* @since 4.3.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Log\Formatter;
class JsonFormatter extends AbstractFormatter
{
/**
* Default config for this class
*
* @var array<string, mixed>
*/
protected $_defaultConfig = [
'dateFormat' => DATE_ATOM,
'flags' => JSON_UNESCAPED_UNICODE,
];
/**
* @param array<string, mixed> $config Formatter config
*/
public function __construct(array $config = [])
{
$this->setConfig($config);
}
/**
* @inheritDoc
*/
public function format($level, string $message, array $context = []): string
{
$log = ['date' => date($this->_config['dateFormat']), 'level' => (string)$level, 'message' => $message];
return json_encode($log, $this->_config['flags']);
}
}
|
Fix spelling error in API key creation modal | import React from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { Alert, Icon } from "../../../base";
const StyledCreateAPIKeyInfo = styled(Alert)`
display: flex;
margin-bottom: 5px;
i {
line-height: 20px;
}
p {
margin-left: 5px;
}
`;
export const CreateAPIKeyInfo = ({ administrator }) => {
if (administrator) {
return (
<StyledCreateAPIKeyInfo>
<Icon name="user-shield" />
<div>
<p>
<strong>You are an administrator and can create API keys with any permissions you want.</strong>
</p>
<p>
If you lose your administrator role, this API key will revert to your new limited set of
permissions.
</p>
</div>
</StyledCreateAPIKeyInfo>
);
}
return null;
};
const mapStateToProps = state => ({
administrator: state.account.administrator
});
export default connect(mapStateToProps)(CreateAPIKeyInfo);
| import React from "react";
import styled from "styled-components";
import { connect } from "react-redux";
import { Alert, Icon } from "../../../base";
const StyledCreateAPIKeyInfo = styled(Alert)`
display: flex;
margin-bottom: 5px;
i {
line-height: 20px;
}
p {
margin-left: 5px;
}
`;
export const CreateAPIKeyInfo = ({ administrator }) => {
if (administrator) {
return (
<StyledCreateAPIKeyInfo>
<Icon name="user-shield" />
<div>
<p>
<strong>You are an administrator and can create API keys with any permissions you want.</strong>
</p>
<p>
If you lose you administrator role, this API key will revert to your new limited set of
permissions.
</p>
</div>
</StyledCreateAPIKeyInfo>
);
}
return null;
};
const mapStateToProps = state => ({
administrator: state.account.administrator
});
export default connect(mapStateToProps)(CreateAPIKeyInfo);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.